]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/intel_display.c
drm/i915: Use a loop for the "three times for luck" DPLL procedure
[karo-tx-linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_clflush.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 static bool is_mmio_work(struct intel_flip_work *work)
53 {
54         return work->mmio_work.func;
55 }
56
57 /* Primary plane formats for gen <= 3 */
58 static const uint32_t i8xx_primary_formats[] = {
59         DRM_FORMAT_C8,
60         DRM_FORMAT_RGB565,
61         DRM_FORMAT_XRGB1555,
62         DRM_FORMAT_XRGB8888,
63 };
64
65 /* Primary plane formats for gen >= 4 */
66 static const uint32_t i965_primary_formats[] = {
67         DRM_FORMAT_C8,
68         DRM_FORMAT_RGB565,
69         DRM_FORMAT_XRGB8888,
70         DRM_FORMAT_XBGR8888,
71         DRM_FORMAT_XRGB2101010,
72         DRM_FORMAT_XBGR2101010,
73 };
74
75 static const uint32_t skl_primary_formats[] = {
76         DRM_FORMAT_C8,
77         DRM_FORMAT_RGB565,
78         DRM_FORMAT_XRGB8888,
79         DRM_FORMAT_XBGR8888,
80         DRM_FORMAT_ARGB8888,
81         DRM_FORMAT_ABGR8888,
82         DRM_FORMAT_XRGB2101010,
83         DRM_FORMAT_XBGR2101010,
84         DRM_FORMAT_YUYV,
85         DRM_FORMAT_YVYU,
86         DRM_FORMAT_UYVY,
87         DRM_FORMAT_VYUY,
88 };
89
90 /* Cursor formats */
91 static const uint32_t intel_cursor_formats[] = {
92         DRM_FORMAT_ARGB8888,
93 };
94
95 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
96                                 struct intel_crtc_state *pipe_config);
97 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
98                                    struct intel_crtc_state *pipe_config);
99
100 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
101                                   struct drm_i915_gem_object *obj,
102                                   struct drm_mode_fb_cmd2 *mode_cmd);
103 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
104 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
105 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
106 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
107                                          struct intel_link_m_n *m_n,
108                                          struct intel_link_m_n *m2_n2);
109 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
110 static void haswell_set_pipeconf(struct drm_crtc *crtc);
111 static void haswell_set_pipemisc(struct drm_crtc *crtc);
112 static void vlv_prepare_pll(struct intel_crtc *crtc,
113                             const struct intel_crtc_state *pipe_config);
114 static void chv_prepare_pll(struct intel_crtc *crtc,
115                             const struct intel_crtc_state *pipe_config);
116 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
117 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
118 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
119                                     struct intel_crtc_state *crtc_state);
120 static void skylake_pfit_enable(struct intel_crtc *crtc);
121 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
122 static void ironlake_pfit_enable(struct intel_crtc *crtc);
123 static void intel_modeset_setup_hw_state(struct drm_device *dev,
124                                          struct drm_modeset_acquire_ctx *ctx);
125 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
126
127 struct intel_limit {
128         struct {
129                 int min, max;
130         } dot, vco, n, m, m1, m2, p, p1;
131
132         struct {
133                 int dot_limit;
134                 int p2_slow, p2_fast;
135         } p2;
136 };
137
138 /* returns HPLL frequency in kHz */
139 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
140 {
141         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
142
143         /* Obtain SKU information */
144         mutex_lock(&dev_priv->sb_lock);
145         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
146                 CCK_FUSE_HPLL_FREQ_MASK;
147         mutex_unlock(&dev_priv->sb_lock);
148
149         return vco_freq[hpll_freq] * 1000;
150 }
151
152 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
153                       const char *name, u32 reg, int ref_freq)
154 {
155         u32 val;
156         int divider;
157
158         mutex_lock(&dev_priv->sb_lock);
159         val = vlv_cck_read(dev_priv, reg);
160         mutex_unlock(&dev_priv->sb_lock);
161
162         divider = val & CCK_FREQUENCY_VALUES;
163
164         WARN((val & CCK_FREQUENCY_STATUS) !=
165              (divider << CCK_FREQUENCY_STATUS_SHIFT),
166              "%s change in progress\n", name);
167
168         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
169 }
170
171 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
172                            const char *name, u32 reg)
173 {
174         if (dev_priv->hpll_freq == 0)
175                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
176
177         return vlv_get_cck_clock(dev_priv, name, reg,
178                                  dev_priv->hpll_freq);
179 }
180
181 static void intel_update_czclk(struct drm_i915_private *dev_priv)
182 {
183         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
184                 return;
185
186         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
187                                                       CCK_CZ_CLOCK_CONTROL);
188
189         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
190 }
191
192 static inline u32 /* units of 100MHz */
193 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
194                     const struct intel_crtc_state *pipe_config)
195 {
196         if (HAS_DDI(dev_priv))
197                 return pipe_config->port_clock; /* SPLL */
198         else if (IS_GEN5(dev_priv))
199                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
200         else
201                 return 270000;
202 }
203
204 static const struct intel_limit intel_limits_i8xx_dac = {
205         .dot = { .min = 25000, .max = 350000 },
206         .vco = { .min = 908000, .max = 1512000 },
207         .n = { .min = 2, .max = 16 },
208         .m = { .min = 96, .max = 140 },
209         .m1 = { .min = 18, .max = 26 },
210         .m2 = { .min = 6, .max = 16 },
211         .p = { .min = 4, .max = 128 },
212         .p1 = { .min = 2, .max = 33 },
213         .p2 = { .dot_limit = 165000,
214                 .p2_slow = 4, .p2_fast = 2 },
215 };
216
217 static const struct intel_limit intel_limits_i8xx_dvo = {
218         .dot = { .min = 25000, .max = 350000 },
219         .vco = { .min = 908000, .max = 1512000 },
220         .n = { .min = 2, .max = 16 },
221         .m = { .min = 96, .max = 140 },
222         .m1 = { .min = 18, .max = 26 },
223         .m2 = { .min = 6, .max = 16 },
224         .p = { .min = 4, .max = 128 },
225         .p1 = { .min = 2, .max = 33 },
226         .p2 = { .dot_limit = 165000,
227                 .p2_slow = 4, .p2_fast = 4 },
228 };
229
230 static const struct intel_limit intel_limits_i8xx_lvds = {
231         .dot = { .min = 25000, .max = 350000 },
232         .vco = { .min = 908000, .max = 1512000 },
233         .n = { .min = 2, .max = 16 },
234         .m = { .min = 96, .max = 140 },
235         .m1 = { .min = 18, .max = 26 },
236         .m2 = { .min = 6, .max = 16 },
237         .p = { .min = 4, .max = 128 },
238         .p1 = { .min = 1, .max = 6 },
239         .p2 = { .dot_limit = 165000,
240                 .p2_slow = 14, .p2_fast = 7 },
241 };
242
243 static const struct intel_limit intel_limits_i9xx_sdvo = {
244         .dot = { .min = 20000, .max = 400000 },
245         .vco = { .min = 1400000, .max = 2800000 },
246         .n = { .min = 1, .max = 6 },
247         .m = { .min = 70, .max = 120 },
248         .m1 = { .min = 8, .max = 18 },
249         .m2 = { .min = 3, .max = 7 },
250         .p = { .min = 5, .max = 80 },
251         .p1 = { .min = 1, .max = 8 },
252         .p2 = { .dot_limit = 200000,
253                 .p2_slow = 10, .p2_fast = 5 },
254 };
255
256 static const struct intel_limit intel_limits_i9xx_lvds = {
257         .dot = { .min = 20000, .max = 400000 },
258         .vco = { .min = 1400000, .max = 2800000 },
259         .n = { .min = 1, .max = 6 },
260         .m = { .min = 70, .max = 120 },
261         .m1 = { .min = 8, .max = 18 },
262         .m2 = { .min = 3, .max = 7 },
263         .p = { .min = 7, .max = 98 },
264         .p1 = { .min = 1, .max = 8 },
265         .p2 = { .dot_limit = 112000,
266                 .p2_slow = 14, .p2_fast = 7 },
267 };
268
269
270 static const struct intel_limit intel_limits_g4x_sdvo = {
271         .dot = { .min = 25000, .max = 270000 },
272         .vco = { .min = 1750000, .max = 3500000},
273         .n = { .min = 1, .max = 4 },
274         .m = { .min = 104, .max = 138 },
275         .m1 = { .min = 17, .max = 23 },
276         .m2 = { .min = 5, .max = 11 },
277         .p = { .min = 10, .max = 30 },
278         .p1 = { .min = 1, .max = 3},
279         .p2 = { .dot_limit = 270000,
280                 .p2_slow = 10,
281                 .p2_fast = 10
282         },
283 };
284
285 static const struct intel_limit intel_limits_g4x_hdmi = {
286         .dot = { .min = 22000, .max = 400000 },
287         .vco = { .min = 1750000, .max = 3500000},
288         .n = { .min = 1, .max = 4 },
289         .m = { .min = 104, .max = 138 },
290         .m1 = { .min = 16, .max = 23 },
291         .m2 = { .min = 5, .max = 11 },
292         .p = { .min = 5, .max = 80 },
293         .p1 = { .min = 1, .max = 8},
294         .p2 = { .dot_limit = 165000,
295                 .p2_slow = 10, .p2_fast = 5 },
296 };
297
298 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
299         .dot = { .min = 20000, .max = 115000 },
300         .vco = { .min = 1750000, .max = 3500000 },
301         .n = { .min = 1, .max = 3 },
302         .m = { .min = 104, .max = 138 },
303         .m1 = { .min = 17, .max = 23 },
304         .m2 = { .min = 5, .max = 11 },
305         .p = { .min = 28, .max = 112 },
306         .p1 = { .min = 2, .max = 8 },
307         .p2 = { .dot_limit = 0,
308                 .p2_slow = 14, .p2_fast = 14
309         },
310 };
311
312 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
313         .dot = { .min = 80000, .max = 224000 },
314         .vco = { .min = 1750000, .max = 3500000 },
315         .n = { .min = 1, .max = 3 },
316         .m = { .min = 104, .max = 138 },
317         .m1 = { .min = 17, .max = 23 },
318         .m2 = { .min = 5, .max = 11 },
319         .p = { .min = 14, .max = 42 },
320         .p1 = { .min = 2, .max = 6 },
321         .p2 = { .dot_limit = 0,
322                 .p2_slow = 7, .p2_fast = 7
323         },
324 };
325
326 static const struct intel_limit intel_limits_pineview_sdvo = {
327         .dot = { .min = 20000, .max = 400000},
328         .vco = { .min = 1700000, .max = 3500000 },
329         /* Pineview's Ncounter is a ring counter */
330         .n = { .min = 3, .max = 6 },
331         .m = { .min = 2, .max = 256 },
332         /* Pineview only has one combined m divider, which we treat as m2. */
333         .m1 = { .min = 0, .max = 0 },
334         .m2 = { .min = 0, .max = 254 },
335         .p = { .min = 5, .max = 80 },
336         .p1 = { .min = 1, .max = 8 },
337         .p2 = { .dot_limit = 200000,
338                 .p2_slow = 10, .p2_fast = 5 },
339 };
340
341 static const struct intel_limit intel_limits_pineview_lvds = {
342         .dot = { .min = 20000, .max = 400000 },
343         .vco = { .min = 1700000, .max = 3500000 },
344         .n = { .min = 3, .max = 6 },
345         .m = { .min = 2, .max = 256 },
346         .m1 = { .min = 0, .max = 0 },
347         .m2 = { .min = 0, .max = 254 },
348         .p = { .min = 7, .max = 112 },
349         .p1 = { .min = 1, .max = 8 },
350         .p2 = { .dot_limit = 112000,
351                 .p2_slow = 14, .p2_fast = 14 },
352 };
353
354 /* Ironlake / Sandybridge
355  *
356  * We calculate clock using (register_value + 2) for N/M1/M2, so here
357  * the range value for them is (actual_value - 2).
358  */
359 static const struct intel_limit intel_limits_ironlake_dac = {
360         .dot = { .min = 25000, .max = 350000 },
361         .vco = { .min = 1760000, .max = 3510000 },
362         .n = { .min = 1, .max = 5 },
363         .m = { .min = 79, .max = 127 },
364         .m1 = { .min = 12, .max = 22 },
365         .m2 = { .min = 5, .max = 9 },
366         .p = { .min = 5, .max = 80 },
367         .p1 = { .min = 1, .max = 8 },
368         .p2 = { .dot_limit = 225000,
369                 .p2_slow = 10, .p2_fast = 5 },
370 };
371
372 static const struct intel_limit intel_limits_ironlake_single_lvds = {
373         .dot = { .min = 25000, .max = 350000 },
374         .vco = { .min = 1760000, .max = 3510000 },
375         .n = { .min = 1, .max = 3 },
376         .m = { .min = 79, .max = 118 },
377         .m1 = { .min = 12, .max = 22 },
378         .m2 = { .min = 5, .max = 9 },
379         .p = { .min = 28, .max = 112 },
380         .p1 = { .min = 2, .max = 8 },
381         .p2 = { .dot_limit = 225000,
382                 .p2_slow = 14, .p2_fast = 14 },
383 };
384
385 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
386         .dot = { .min = 25000, .max = 350000 },
387         .vco = { .min = 1760000, .max = 3510000 },
388         .n = { .min = 1, .max = 3 },
389         .m = { .min = 79, .max = 127 },
390         .m1 = { .min = 12, .max = 22 },
391         .m2 = { .min = 5, .max = 9 },
392         .p = { .min = 14, .max = 56 },
393         .p1 = { .min = 2, .max = 8 },
394         .p2 = { .dot_limit = 225000,
395                 .p2_slow = 7, .p2_fast = 7 },
396 };
397
398 /* LVDS 100mhz refclk limits. */
399 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
400         .dot = { .min = 25000, .max = 350000 },
401         .vco = { .min = 1760000, .max = 3510000 },
402         .n = { .min = 1, .max = 2 },
403         .m = { .min = 79, .max = 126 },
404         .m1 = { .min = 12, .max = 22 },
405         .m2 = { .min = 5, .max = 9 },
406         .p = { .min = 28, .max = 112 },
407         .p1 = { .min = 2, .max = 8 },
408         .p2 = { .dot_limit = 225000,
409                 .p2_slow = 14, .p2_fast = 14 },
410 };
411
412 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
413         .dot = { .min = 25000, .max = 350000 },
414         .vco = { .min = 1760000, .max = 3510000 },
415         .n = { .min = 1, .max = 3 },
416         .m = { .min = 79, .max = 126 },
417         .m1 = { .min = 12, .max = 22 },
418         .m2 = { .min = 5, .max = 9 },
419         .p = { .min = 14, .max = 42 },
420         .p1 = { .min = 2, .max = 6 },
421         .p2 = { .dot_limit = 225000,
422                 .p2_slow = 7, .p2_fast = 7 },
423 };
424
425 static const struct intel_limit intel_limits_vlv = {
426          /*
427           * These are the data rate limits (measured in fast clocks)
428           * since those are the strictest limits we have. The fast
429           * clock and actual rate limits are more relaxed, so checking
430           * them would make no difference.
431           */
432         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
433         .vco = { .min = 4000000, .max = 6000000 },
434         .n = { .min = 1, .max = 7 },
435         .m1 = { .min = 2, .max = 3 },
436         .m2 = { .min = 11, .max = 156 },
437         .p1 = { .min = 2, .max = 3 },
438         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
439 };
440
441 static const struct intel_limit intel_limits_chv = {
442         /*
443          * These are the data rate limits (measured in fast clocks)
444          * since those are the strictest limits we have.  The fast
445          * clock and actual rate limits are more relaxed, so checking
446          * them would make no difference.
447          */
448         .dot = { .min = 25000 * 5, .max = 540000 * 5},
449         .vco = { .min = 4800000, .max = 6480000 },
450         .n = { .min = 1, .max = 1 },
451         .m1 = { .min = 2, .max = 2 },
452         .m2 = { .min = 24 << 22, .max = 175 << 22 },
453         .p1 = { .min = 2, .max = 4 },
454         .p2 = { .p2_slow = 1, .p2_fast = 14 },
455 };
456
457 static const struct intel_limit intel_limits_bxt = {
458         /* FIXME: find real dot limits */
459         .dot = { .min = 0, .max = INT_MAX },
460         .vco = { .min = 4800000, .max = 6700000 },
461         .n = { .min = 1, .max = 1 },
462         .m1 = { .min = 2, .max = 2 },
463         /* FIXME: find real m2 limits */
464         .m2 = { .min = 2 << 22, .max = 255 << 22 },
465         .p1 = { .min = 2, .max = 4 },
466         .p2 = { .p2_slow = 1, .p2_fast = 20 },
467 };
468
469 static bool
470 needs_modeset(struct drm_crtc_state *state)
471 {
472         return drm_atomic_crtc_needs_modeset(state);
473 }
474
475 /*
476  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
477  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
478  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
479  * The helpers' return value is the rate of the clock that is fed to the
480  * display engine's pipe which can be the above fast dot clock rate or a
481  * divided-down version of it.
482  */
483 /* m1 is reserved as 0 in Pineview, n is a ring counter */
484 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
485 {
486         clock->m = clock->m2 + 2;
487         clock->p = clock->p1 * clock->p2;
488         if (WARN_ON(clock->n == 0 || clock->p == 0))
489                 return 0;
490         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
491         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
492
493         return clock->dot;
494 }
495
496 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
497 {
498         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
499 }
500
501 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
502 {
503         clock->m = i9xx_dpll_compute_m(clock);
504         clock->p = clock->p1 * clock->p2;
505         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
506                 return 0;
507         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
508         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
509
510         return clock->dot;
511 }
512
513 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
514 {
515         clock->m = clock->m1 * clock->m2;
516         clock->p = clock->p1 * clock->p2;
517         if (WARN_ON(clock->n == 0 || clock->p == 0))
518                 return 0;
519         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
520         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
521
522         return clock->dot / 5;
523 }
524
525 int chv_calc_dpll_params(int refclk, struct dpll *clock)
526 {
527         clock->m = clock->m1 * clock->m2;
528         clock->p = clock->p1 * clock->p2;
529         if (WARN_ON(clock->n == 0 || clock->p == 0))
530                 return 0;
531         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
532                         clock->n << 22);
533         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
534
535         return clock->dot / 5;
536 }
537
538 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
539 /**
540  * Returns whether the given set of divisors are valid for a given refclk with
541  * the given connectors.
542  */
543
544 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
545                                const struct intel_limit *limit,
546                                const struct dpll *clock)
547 {
548         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
549                 INTELPllInvalid("n out of range\n");
550         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
551                 INTELPllInvalid("p1 out of range\n");
552         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
553                 INTELPllInvalid("m2 out of range\n");
554         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
555                 INTELPllInvalid("m1 out of range\n");
556
557         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
558             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
559                 if (clock->m1 <= clock->m2)
560                         INTELPllInvalid("m1 <= m2\n");
561
562         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
563             !IS_GEN9_LP(dev_priv)) {
564                 if (clock->p < limit->p.min || limit->p.max < clock->p)
565                         INTELPllInvalid("p out of range\n");
566                 if (clock->m < limit->m.min || limit->m.max < clock->m)
567                         INTELPllInvalid("m out of range\n");
568         }
569
570         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
571                 INTELPllInvalid("vco out of range\n");
572         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
573          * connector, etc., rather than just a single range.
574          */
575         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
576                 INTELPllInvalid("dot out of range\n");
577
578         return true;
579 }
580
581 static int
582 i9xx_select_p2_div(const struct intel_limit *limit,
583                    const struct intel_crtc_state *crtc_state,
584                    int target)
585 {
586         struct drm_device *dev = crtc_state->base.crtc->dev;
587
588         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
589                 /*
590                  * For LVDS just rely on its current settings for dual-channel.
591                  * We haven't figured out how to reliably set up different
592                  * single/dual channel state, if we even can.
593                  */
594                 if (intel_is_dual_link_lvds(dev))
595                         return limit->p2.p2_fast;
596                 else
597                         return limit->p2.p2_slow;
598         } else {
599                 if (target < limit->p2.dot_limit)
600                         return limit->p2.p2_slow;
601                 else
602                         return limit->p2.p2_fast;
603         }
604 }
605
606 /*
607  * Returns a set of divisors for the desired target clock with the given
608  * refclk, or FALSE.  The returned values represent the clock equation:
609  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
610  *
611  * Target and reference clocks are specified in kHz.
612  *
613  * If match_clock is provided, then best_clock P divider must match the P
614  * divider from @match_clock used for LVDS downclocking.
615  */
616 static bool
617 i9xx_find_best_dpll(const struct intel_limit *limit,
618                     struct intel_crtc_state *crtc_state,
619                     int target, int refclk, struct dpll *match_clock,
620                     struct dpll *best_clock)
621 {
622         struct drm_device *dev = crtc_state->base.crtc->dev;
623         struct dpll clock;
624         int err = target;
625
626         memset(best_clock, 0, sizeof(*best_clock));
627
628         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
629
630         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
631              clock.m1++) {
632                 for (clock.m2 = limit->m2.min;
633                      clock.m2 <= limit->m2.max; clock.m2++) {
634                         if (clock.m2 >= clock.m1)
635                                 break;
636                         for (clock.n = limit->n.min;
637                              clock.n <= limit->n.max; clock.n++) {
638                                 for (clock.p1 = limit->p1.min;
639                                         clock.p1 <= limit->p1.max; clock.p1++) {
640                                         int this_err;
641
642                                         i9xx_calc_dpll_params(refclk, &clock);
643                                         if (!intel_PLL_is_valid(to_i915(dev),
644                                                                 limit,
645                                                                 &clock))
646                                                 continue;
647                                         if (match_clock &&
648                                             clock.p != match_clock->p)
649                                                 continue;
650
651                                         this_err = abs(clock.dot - target);
652                                         if (this_err < err) {
653                                                 *best_clock = clock;
654                                                 err = this_err;
655                                         }
656                                 }
657                         }
658                 }
659         }
660
661         return (err != target);
662 }
663
664 /*
665  * Returns a set of divisors for the desired target clock with the given
666  * refclk, or FALSE.  The returned values represent the clock equation:
667  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
668  *
669  * Target and reference clocks are specified in kHz.
670  *
671  * If match_clock is provided, then best_clock P divider must match the P
672  * divider from @match_clock used for LVDS downclocking.
673  */
674 static bool
675 pnv_find_best_dpll(const struct intel_limit *limit,
676                    struct intel_crtc_state *crtc_state,
677                    int target, int refclk, struct dpll *match_clock,
678                    struct dpll *best_clock)
679 {
680         struct drm_device *dev = crtc_state->base.crtc->dev;
681         struct dpll clock;
682         int err = target;
683
684         memset(best_clock, 0, sizeof(*best_clock));
685
686         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
687
688         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
689              clock.m1++) {
690                 for (clock.m2 = limit->m2.min;
691                      clock.m2 <= limit->m2.max; clock.m2++) {
692                         for (clock.n = limit->n.min;
693                              clock.n <= limit->n.max; clock.n++) {
694                                 for (clock.p1 = limit->p1.min;
695                                         clock.p1 <= limit->p1.max; clock.p1++) {
696                                         int this_err;
697
698                                         pnv_calc_dpll_params(refclk, &clock);
699                                         if (!intel_PLL_is_valid(to_i915(dev),
700                                                                 limit,
701                                                                 &clock))
702                                                 continue;
703                                         if (match_clock &&
704                                             clock.p != match_clock->p)
705                                                 continue;
706
707                                         this_err = abs(clock.dot - target);
708                                         if (this_err < err) {
709                                                 *best_clock = clock;
710                                                 err = this_err;
711                                         }
712                                 }
713                         }
714                 }
715         }
716
717         return (err != target);
718 }
719
720 /*
721  * Returns a set of divisors for the desired target clock with the given
722  * refclk, or FALSE.  The returned values represent the clock equation:
723  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
724  *
725  * Target and reference clocks are specified in kHz.
726  *
727  * If match_clock is provided, then best_clock P divider must match the P
728  * divider from @match_clock used for LVDS downclocking.
729  */
730 static bool
731 g4x_find_best_dpll(const struct intel_limit *limit,
732                    struct intel_crtc_state *crtc_state,
733                    int target, int refclk, struct dpll *match_clock,
734                    struct dpll *best_clock)
735 {
736         struct drm_device *dev = crtc_state->base.crtc->dev;
737         struct dpll clock;
738         int max_n;
739         bool found = false;
740         /* approximately equals target * 0.00585 */
741         int err_most = (target >> 8) + (target >> 9);
742
743         memset(best_clock, 0, sizeof(*best_clock));
744
745         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
746
747         max_n = limit->n.max;
748         /* based on hardware requirement, prefer smaller n to precision */
749         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
750                 /* based on hardware requirement, prefere larger m1,m2 */
751                 for (clock.m1 = limit->m1.max;
752                      clock.m1 >= limit->m1.min; clock.m1--) {
753                         for (clock.m2 = limit->m2.max;
754                              clock.m2 >= limit->m2.min; clock.m2--) {
755                                 for (clock.p1 = limit->p1.max;
756                                      clock.p1 >= limit->p1.min; clock.p1--) {
757                                         int this_err;
758
759                                         i9xx_calc_dpll_params(refclk, &clock);
760                                         if (!intel_PLL_is_valid(to_i915(dev),
761                                                                 limit,
762                                                                 &clock))
763                                                 continue;
764
765                                         this_err = abs(clock.dot - target);
766                                         if (this_err < err_most) {
767                                                 *best_clock = clock;
768                                                 err_most = this_err;
769                                                 max_n = clock.n;
770                                                 found = true;
771                                         }
772                                 }
773                         }
774                 }
775         }
776         return found;
777 }
778
779 /*
780  * Check if the calculated PLL configuration is more optimal compared to the
781  * best configuration and error found so far. Return the calculated error.
782  */
783 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
784                                const struct dpll *calculated_clock,
785                                const struct dpll *best_clock,
786                                unsigned int best_error_ppm,
787                                unsigned int *error_ppm)
788 {
789         /*
790          * For CHV ignore the error and consider only the P value.
791          * Prefer a bigger P value based on HW requirements.
792          */
793         if (IS_CHERRYVIEW(to_i915(dev))) {
794                 *error_ppm = 0;
795
796                 return calculated_clock->p > best_clock->p;
797         }
798
799         if (WARN_ON_ONCE(!target_freq))
800                 return false;
801
802         *error_ppm = div_u64(1000000ULL *
803                                 abs(target_freq - calculated_clock->dot),
804                              target_freq);
805         /*
806          * Prefer a better P value over a better (smaller) error if the error
807          * is small. Ensure this preference for future configurations too by
808          * setting the error to 0.
809          */
810         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
811                 *error_ppm = 0;
812
813                 return true;
814         }
815
816         return *error_ppm + 10 < best_error_ppm;
817 }
818
819 /*
820  * Returns a set of divisors for the desired target clock with the given
821  * refclk, or FALSE.  The returned values represent the clock equation:
822  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
823  */
824 static bool
825 vlv_find_best_dpll(const struct intel_limit *limit,
826                    struct intel_crtc_state *crtc_state,
827                    int target, int refclk, struct dpll *match_clock,
828                    struct dpll *best_clock)
829 {
830         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
831         struct drm_device *dev = crtc->base.dev;
832         struct dpll clock;
833         unsigned int bestppm = 1000000;
834         /* min update 19.2 MHz */
835         int max_n = min(limit->n.max, refclk / 19200);
836         bool found = false;
837
838         target *= 5; /* fast clock */
839
840         memset(best_clock, 0, sizeof(*best_clock));
841
842         /* based on hardware requirement, prefer smaller n to precision */
843         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
844                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
845                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
846                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
847                                 clock.p = clock.p1 * clock.p2;
848                                 /* based on hardware requirement, prefer bigger m1,m2 values */
849                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
850                                         unsigned int ppm;
851
852                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
853                                                                      refclk * clock.m1);
854
855                                         vlv_calc_dpll_params(refclk, &clock);
856
857                                         if (!intel_PLL_is_valid(to_i915(dev),
858                                                                 limit,
859                                                                 &clock))
860                                                 continue;
861
862                                         if (!vlv_PLL_is_optimal(dev, target,
863                                                                 &clock,
864                                                                 best_clock,
865                                                                 bestppm, &ppm))
866                                                 continue;
867
868                                         *best_clock = clock;
869                                         bestppm = ppm;
870                                         found = true;
871                                 }
872                         }
873                 }
874         }
875
876         return found;
877 }
878
879 /*
880  * Returns a set of divisors for the desired target clock with the given
881  * refclk, or FALSE.  The returned values represent the clock equation:
882  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
883  */
884 static bool
885 chv_find_best_dpll(const struct intel_limit *limit,
886                    struct intel_crtc_state *crtc_state,
887                    int target, int refclk, struct dpll *match_clock,
888                    struct dpll *best_clock)
889 {
890         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
891         struct drm_device *dev = crtc->base.dev;
892         unsigned int best_error_ppm;
893         struct dpll clock;
894         uint64_t m2;
895         int found = false;
896
897         memset(best_clock, 0, sizeof(*best_clock));
898         best_error_ppm = 1000000;
899
900         /*
901          * Based on hardware doc, the n always set to 1, and m1 always
902          * set to 2.  If requires to support 200Mhz refclk, we need to
903          * revisit this because n may not 1 anymore.
904          */
905         clock.n = 1, clock.m1 = 2;
906         target *= 5;    /* fast clock */
907
908         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
909                 for (clock.p2 = limit->p2.p2_fast;
910                                 clock.p2 >= limit->p2.p2_slow;
911                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
912                         unsigned int error_ppm;
913
914                         clock.p = clock.p1 * clock.p2;
915
916                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
917                                         clock.n) << 22, refclk * clock.m1);
918
919                         if (m2 > INT_MAX/clock.m1)
920                                 continue;
921
922                         clock.m2 = m2;
923
924                         chv_calc_dpll_params(refclk, &clock);
925
926                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
927                                 continue;
928
929                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
930                                                 best_error_ppm, &error_ppm))
931                                 continue;
932
933                         *best_clock = clock;
934                         best_error_ppm = error_ppm;
935                         found = true;
936                 }
937         }
938
939         return found;
940 }
941
942 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
943                         struct dpll *best_clock)
944 {
945         int refclk = 100000;
946         const struct intel_limit *limit = &intel_limits_bxt;
947
948         return chv_find_best_dpll(limit, crtc_state,
949                                   target_clock, refclk, NULL, best_clock);
950 }
951
952 bool intel_crtc_active(struct intel_crtc *crtc)
953 {
954         /* Be paranoid as we can arrive here with only partial
955          * state retrieved from the hardware during setup.
956          *
957          * We can ditch the adjusted_mode.crtc_clock check as soon
958          * as Haswell has gained clock readout/fastboot support.
959          *
960          * We can ditch the crtc->primary->fb check as soon as we can
961          * properly reconstruct framebuffers.
962          *
963          * FIXME: The intel_crtc->active here should be switched to
964          * crtc->state->active once we have proper CRTC states wired up
965          * for atomic.
966          */
967         return crtc->active && crtc->base.primary->state->fb &&
968                 crtc->config->base.adjusted_mode.crtc_clock;
969 }
970
971 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
972                                              enum pipe pipe)
973 {
974         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
975
976         return crtc->config->cpu_transcoder;
977 }
978
979 static bool pipe_dsl_stopped(struct drm_i915_private *dev_priv, enum pipe pipe)
980 {
981         i915_reg_t reg = PIPEDSL(pipe);
982         u32 line1, line2;
983         u32 line_mask;
984
985         if (IS_GEN2(dev_priv))
986                 line_mask = DSL_LINEMASK_GEN2;
987         else
988                 line_mask = DSL_LINEMASK_GEN3;
989
990         line1 = I915_READ(reg) & line_mask;
991         msleep(5);
992         line2 = I915_READ(reg) & line_mask;
993
994         return line1 == line2;
995 }
996
997 /*
998  * intel_wait_for_pipe_off - wait for pipe to turn off
999  * @crtc: crtc whose pipe to wait for
1000  *
1001  * After disabling a pipe, we can't wait for vblank in the usual way,
1002  * spinning on the vblank interrupt status bit, since we won't actually
1003  * see an interrupt when the pipe is disabled.
1004  *
1005  * On Gen4 and above:
1006  *   wait for the pipe register state bit to turn off
1007  *
1008  * Otherwise:
1009  *   wait for the display line value to settle (it usually
1010  *   ends up stopping at the start of the next frame).
1011  *
1012  */
1013 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1014 {
1015         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1016         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1017         enum pipe pipe = crtc->pipe;
1018
1019         if (INTEL_GEN(dev_priv) >= 4) {
1020                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1021
1022                 /* Wait for the Pipe State to go off */
1023                 if (intel_wait_for_register(dev_priv,
1024                                             reg, I965_PIPECONF_ACTIVE, 0,
1025                                             100))
1026                         WARN(1, "pipe_off wait timed out\n");
1027         } else {
1028                 /* Wait for the display line to settle */
1029                 if (wait_for(pipe_dsl_stopped(dev_priv, pipe), 100))
1030                         WARN(1, "pipe_off wait timed out\n");
1031         }
1032 }
1033
1034 /* Only for pre-ILK configs */
1035 void assert_pll(struct drm_i915_private *dev_priv,
1036                 enum pipe pipe, bool state)
1037 {
1038         u32 val;
1039         bool cur_state;
1040
1041         val = I915_READ(DPLL(pipe));
1042         cur_state = !!(val & DPLL_VCO_ENABLE);
1043         I915_STATE_WARN(cur_state != state,
1044              "PLL state assertion failure (expected %s, current %s)\n",
1045                         onoff(state), onoff(cur_state));
1046 }
1047
1048 /* XXX: the dsi pll is shared between MIPI DSI ports */
1049 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1050 {
1051         u32 val;
1052         bool cur_state;
1053
1054         mutex_lock(&dev_priv->sb_lock);
1055         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1056         mutex_unlock(&dev_priv->sb_lock);
1057
1058         cur_state = val & DSI_PLL_VCO_EN;
1059         I915_STATE_WARN(cur_state != state,
1060              "DSI PLL state assertion failure (expected %s, current %s)\n",
1061                         onoff(state), onoff(cur_state));
1062 }
1063
1064 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1065                           enum pipe pipe, bool state)
1066 {
1067         bool cur_state;
1068         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1069                                                                       pipe);
1070
1071         if (HAS_DDI(dev_priv)) {
1072                 /* DDI does not have a specific FDI_TX register */
1073                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1074                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1075         } else {
1076                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1077                 cur_state = !!(val & FDI_TX_ENABLE);
1078         }
1079         I915_STATE_WARN(cur_state != state,
1080              "FDI TX state assertion failure (expected %s, current %s)\n",
1081                         onoff(state), onoff(cur_state));
1082 }
1083 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1084 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1085
1086 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1087                           enum pipe pipe, bool state)
1088 {
1089         u32 val;
1090         bool cur_state;
1091
1092         val = I915_READ(FDI_RX_CTL(pipe));
1093         cur_state = !!(val & FDI_RX_ENABLE);
1094         I915_STATE_WARN(cur_state != state,
1095              "FDI RX state assertion failure (expected %s, current %s)\n",
1096                         onoff(state), onoff(cur_state));
1097 }
1098 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1099 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1100
1101 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1102                                       enum pipe pipe)
1103 {
1104         u32 val;
1105
1106         /* ILK FDI PLL is always enabled */
1107         if (IS_GEN5(dev_priv))
1108                 return;
1109
1110         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1111         if (HAS_DDI(dev_priv))
1112                 return;
1113
1114         val = I915_READ(FDI_TX_CTL(pipe));
1115         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1116 }
1117
1118 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1119                        enum pipe pipe, bool state)
1120 {
1121         u32 val;
1122         bool cur_state;
1123
1124         val = I915_READ(FDI_RX_CTL(pipe));
1125         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1126         I915_STATE_WARN(cur_state != state,
1127              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1128                         onoff(state), onoff(cur_state));
1129 }
1130
1131 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1132 {
1133         i915_reg_t pp_reg;
1134         u32 val;
1135         enum pipe panel_pipe = PIPE_A;
1136         bool locked = true;
1137
1138         if (WARN_ON(HAS_DDI(dev_priv)))
1139                 return;
1140
1141         if (HAS_PCH_SPLIT(dev_priv)) {
1142                 u32 port_sel;
1143
1144                 pp_reg = PP_CONTROL(0);
1145                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1146
1147                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1148                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1149                         panel_pipe = PIPE_B;
1150                 /* XXX: else fix for eDP */
1151         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1152                 /* presumably write lock depends on pipe, not port select */
1153                 pp_reg = PP_CONTROL(pipe);
1154                 panel_pipe = pipe;
1155         } else {
1156                 pp_reg = PP_CONTROL(0);
1157                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1158                         panel_pipe = PIPE_B;
1159         }
1160
1161         val = I915_READ(pp_reg);
1162         if (!(val & PANEL_POWER_ON) ||
1163             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1164                 locked = false;
1165
1166         I915_STATE_WARN(panel_pipe == pipe && locked,
1167              "panel assertion failure, pipe %c regs locked\n",
1168              pipe_name(pipe));
1169 }
1170
1171 static void assert_cursor(struct drm_i915_private *dev_priv,
1172                           enum pipe pipe, bool state)
1173 {
1174         bool cur_state;
1175
1176         if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
1177                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1178         else
1179                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1180
1181         I915_STATE_WARN(cur_state != state,
1182              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1183                         pipe_name(pipe), onoff(state), onoff(cur_state));
1184 }
1185 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1186 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1187
1188 void assert_pipe(struct drm_i915_private *dev_priv,
1189                  enum pipe pipe, bool state)
1190 {
1191         bool cur_state;
1192         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1193                                                                       pipe);
1194         enum intel_display_power_domain power_domain;
1195
1196         /* if we need the pipe quirk it must be always on */
1197         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1198             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1199                 state = true;
1200
1201         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1202         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1203                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1204                 cur_state = !!(val & PIPECONF_ENABLE);
1205
1206                 intel_display_power_put(dev_priv, power_domain);
1207         } else {
1208                 cur_state = false;
1209         }
1210
1211         I915_STATE_WARN(cur_state != state,
1212              "pipe %c assertion failure (expected %s, current %s)\n",
1213                         pipe_name(pipe), onoff(state), onoff(cur_state));
1214 }
1215
1216 static void assert_plane(struct drm_i915_private *dev_priv,
1217                          enum plane plane, bool state)
1218 {
1219         u32 val;
1220         bool cur_state;
1221
1222         val = I915_READ(DSPCNTR(plane));
1223         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1224         I915_STATE_WARN(cur_state != state,
1225              "plane %c assertion failure (expected %s, current %s)\n",
1226                         plane_name(plane), onoff(state), onoff(cur_state));
1227 }
1228
1229 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1230 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1231
1232 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1233                                    enum pipe pipe)
1234 {
1235         int i;
1236
1237         /* Primary planes are fixed to pipes on gen4+ */
1238         if (INTEL_GEN(dev_priv) >= 4) {
1239                 u32 val = I915_READ(DSPCNTR(pipe));
1240                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1241                      "plane %c assertion failure, should be disabled but not\n",
1242                      plane_name(pipe));
1243                 return;
1244         }
1245
1246         /* Need to check both planes against the pipe */
1247         for_each_pipe(dev_priv, i) {
1248                 u32 val = I915_READ(DSPCNTR(i));
1249                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1250                         DISPPLANE_SEL_PIPE_SHIFT;
1251                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1252                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1253                      plane_name(i), pipe_name(pipe));
1254         }
1255 }
1256
1257 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1258                                     enum pipe pipe)
1259 {
1260         int sprite;
1261
1262         if (INTEL_GEN(dev_priv) >= 9) {
1263                 for_each_sprite(dev_priv, pipe, sprite) {
1264                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1265                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1266                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1267                              sprite, pipe_name(pipe));
1268                 }
1269         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1270                 for_each_sprite(dev_priv, pipe, sprite) {
1271                         u32 val = I915_READ(SPCNTR(pipe, PLANE_SPRITE0 + sprite));
1272                         I915_STATE_WARN(val & SP_ENABLE,
1273                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1274                              sprite_name(pipe, sprite), pipe_name(pipe));
1275                 }
1276         } else if (INTEL_GEN(dev_priv) >= 7) {
1277                 u32 val = I915_READ(SPRCTL(pipe));
1278                 I915_STATE_WARN(val & SPRITE_ENABLE,
1279                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1280                      plane_name(pipe), pipe_name(pipe));
1281         } else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv)) {
1282                 u32 val = I915_READ(DVSCNTR(pipe));
1283                 I915_STATE_WARN(val & DVS_ENABLE,
1284                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1285                      plane_name(pipe), pipe_name(pipe));
1286         }
1287 }
1288
1289 static void assert_vblank_disabled(struct drm_crtc *crtc)
1290 {
1291         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1292                 drm_crtc_vblank_put(crtc);
1293 }
1294
1295 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1296                                     enum pipe pipe)
1297 {
1298         u32 val;
1299         bool enabled;
1300
1301         val = I915_READ(PCH_TRANSCONF(pipe));
1302         enabled = !!(val & TRANS_ENABLE);
1303         I915_STATE_WARN(enabled,
1304              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1305              pipe_name(pipe));
1306 }
1307
1308 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1309                             enum pipe pipe, u32 port_sel, u32 val)
1310 {
1311         if ((val & DP_PORT_EN) == 0)
1312                 return false;
1313
1314         if (HAS_PCH_CPT(dev_priv)) {
1315                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1316                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1317                         return false;
1318         } else if (IS_CHERRYVIEW(dev_priv)) {
1319                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1320                         return false;
1321         } else {
1322                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1323                         return false;
1324         }
1325         return true;
1326 }
1327
1328 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1329                               enum pipe pipe, u32 val)
1330 {
1331         if ((val & SDVO_ENABLE) == 0)
1332                 return false;
1333
1334         if (HAS_PCH_CPT(dev_priv)) {
1335                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1336                         return false;
1337         } else if (IS_CHERRYVIEW(dev_priv)) {
1338                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1339                         return false;
1340         } else {
1341                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1342                         return false;
1343         }
1344         return true;
1345 }
1346
1347 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1348                               enum pipe pipe, u32 val)
1349 {
1350         if ((val & LVDS_PORT_EN) == 0)
1351                 return false;
1352
1353         if (HAS_PCH_CPT(dev_priv)) {
1354                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1355                         return false;
1356         } else {
1357                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1358                         return false;
1359         }
1360         return true;
1361 }
1362
1363 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1364                               enum pipe pipe, u32 val)
1365 {
1366         if ((val & ADPA_DAC_ENABLE) == 0)
1367                 return false;
1368         if (HAS_PCH_CPT(dev_priv)) {
1369                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1370                         return false;
1371         } else {
1372                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1373                         return false;
1374         }
1375         return true;
1376 }
1377
1378 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1379                                    enum pipe pipe, i915_reg_t reg,
1380                                    u32 port_sel)
1381 {
1382         u32 val = I915_READ(reg);
1383         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1384              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1385              i915_mmio_reg_offset(reg), pipe_name(pipe));
1386
1387         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1388              && (val & DP_PIPEB_SELECT),
1389              "IBX PCH dp port still using transcoder B\n");
1390 }
1391
1392 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1393                                      enum pipe pipe, i915_reg_t reg)
1394 {
1395         u32 val = I915_READ(reg);
1396         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1397              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1398              i915_mmio_reg_offset(reg), pipe_name(pipe));
1399
1400         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1401              && (val & SDVO_PIPE_B_SELECT),
1402              "IBX PCH hdmi port still using transcoder B\n");
1403 }
1404
1405 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1406                                       enum pipe pipe)
1407 {
1408         u32 val;
1409
1410         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1411         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1412         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1413
1414         val = I915_READ(PCH_ADPA);
1415         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1416              "PCH VGA enabled on transcoder %c, should be disabled\n",
1417              pipe_name(pipe));
1418
1419         val = I915_READ(PCH_LVDS);
1420         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1421              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1422              pipe_name(pipe));
1423
1424         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1425         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1426         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1427 }
1428
1429 static void _vlv_enable_pll(struct intel_crtc *crtc,
1430                             const struct intel_crtc_state *pipe_config)
1431 {
1432         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1433         enum pipe pipe = crtc->pipe;
1434
1435         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1436         POSTING_READ(DPLL(pipe));
1437         udelay(150);
1438
1439         if (intel_wait_for_register(dev_priv,
1440                                     DPLL(pipe),
1441                                     DPLL_LOCK_VLV,
1442                                     DPLL_LOCK_VLV,
1443                                     1))
1444                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1445 }
1446
1447 static void vlv_enable_pll(struct intel_crtc *crtc,
1448                            const struct intel_crtc_state *pipe_config)
1449 {
1450         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1451         enum pipe pipe = crtc->pipe;
1452
1453         assert_pipe_disabled(dev_priv, pipe);
1454
1455         /* PLL is protected by panel, make sure we can write it */
1456         assert_panel_unlocked(dev_priv, pipe);
1457
1458         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1459                 _vlv_enable_pll(crtc, pipe_config);
1460
1461         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1462         POSTING_READ(DPLL_MD(pipe));
1463 }
1464
1465
1466 static void _chv_enable_pll(struct intel_crtc *crtc,
1467                             const struct intel_crtc_state *pipe_config)
1468 {
1469         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1470         enum pipe pipe = crtc->pipe;
1471         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1472         u32 tmp;
1473
1474         mutex_lock(&dev_priv->sb_lock);
1475
1476         /* Enable back the 10bit clock to display controller */
1477         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1478         tmp |= DPIO_DCLKP_EN;
1479         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1480
1481         mutex_unlock(&dev_priv->sb_lock);
1482
1483         /*
1484          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1485          */
1486         udelay(1);
1487
1488         /* Enable PLL */
1489         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1490
1491         /* Check PLL is locked */
1492         if (intel_wait_for_register(dev_priv,
1493                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1494                                     1))
1495                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1496 }
1497
1498 static void chv_enable_pll(struct intel_crtc *crtc,
1499                            const struct intel_crtc_state *pipe_config)
1500 {
1501         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1502         enum pipe pipe = crtc->pipe;
1503
1504         assert_pipe_disabled(dev_priv, pipe);
1505
1506         /* PLL is protected by panel, make sure we can write it */
1507         assert_panel_unlocked(dev_priv, pipe);
1508
1509         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1510                 _chv_enable_pll(crtc, pipe_config);
1511
1512         if (pipe != PIPE_A) {
1513                 /*
1514                  * WaPixelRepeatModeFixForC0:chv
1515                  *
1516                  * DPLLCMD is AWOL. Use chicken bits to propagate
1517                  * the value from DPLLBMD to either pipe B or C.
1518                  */
1519                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1520                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1521                 I915_WRITE(CBR4_VLV, 0);
1522                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1523
1524                 /*
1525                  * DPLLB VGA mode also seems to cause problems.
1526                  * We should always have it disabled.
1527                  */
1528                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1529         } else {
1530                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1531                 POSTING_READ(DPLL_MD(pipe));
1532         }
1533 }
1534
1535 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1536 {
1537         struct intel_crtc *crtc;
1538         int count = 0;
1539
1540         for_each_intel_crtc(&dev_priv->drm, crtc) {
1541                 count += crtc->base.state->active &&
1542                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1543         }
1544
1545         return count;
1546 }
1547
1548 static void i9xx_enable_pll(struct intel_crtc *crtc)
1549 {
1550         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1551         i915_reg_t reg = DPLL(crtc->pipe);
1552         u32 dpll = crtc->config->dpll_hw_state.dpll;
1553         int i;
1554
1555         assert_pipe_disabled(dev_priv, crtc->pipe);
1556
1557         /* PLL is protected by panel, make sure we can write it */
1558         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1559                 assert_panel_unlocked(dev_priv, crtc->pipe);
1560
1561         /* Enable DVO 2x clock on both PLLs if necessary */
1562         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1563                 /*
1564                  * It appears to be important that we don't enable this
1565                  * for the current pipe before otherwise configuring the
1566                  * PLL. No idea how this should be handled if multiple
1567                  * DVO outputs are enabled simultaneosly.
1568                  */
1569                 dpll |= DPLL_DVO_2X_MODE;
1570                 I915_WRITE(DPLL(!crtc->pipe),
1571                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1572         }
1573
1574         /*
1575          * Apparently we need to have VGA mode enabled prior to changing
1576          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1577          * dividers, even though the register value does change.
1578          */
1579         I915_WRITE(reg, 0);
1580
1581         I915_WRITE(reg, dpll);
1582
1583         /* Wait for the clocks to stabilize. */
1584         POSTING_READ(reg);
1585         udelay(150);
1586
1587         if (INTEL_GEN(dev_priv) >= 4) {
1588                 I915_WRITE(DPLL_MD(crtc->pipe),
1589                            crtc->config->dpll_hw_state.dpll_md);
1590         } else {
1591                 /* The pixel multiplier can only be updated once the
1592                  * DPLL is enabled and the clocks are stable.
1593                  *
1594                  * So write it again.
1595                  */
1596                 I915_WRITE(reg, dpll);
1597         }
1598
1599         /* We do this three times for luck */
1600         for (i = 0; i < 3; i++) {
1601                 I915_WRITE(reg, dpll);
1602                 POSTING_READ(reg);
1603                 udelay(150); /* wait for warmup */
1604         }
1605 }
1606
1607 /**
1608  * i9xx_disable_pll - disable a PLL
1609  * @dev_priv: i915 private structure
1610  * @pipe: pipe PLL to disable
1611  *
1612  * Disable the PLL for @pipe, making sure the pipe is off first.
1613  *
1614  * Note!  This is for pre-ILK only.
1615  */
1616 static void i9xx_disable_pll(struct intel_crtc *crtc)
1617 {
1618         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1619         enum pipe pipe = crtc->pipe;
1620
1621         /* Disable DVO 2x clock on both PLLs if necessary */
1622         if (IS_I830(dev_priv) &&
1623             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1624             !intel_num_dvo_pipes(dev_priv)) {
1625                 I915_WRITE(DPLL(PIPE_B),
1626                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1627                 I915_WRITE(DPLL(PIPE_A),
1628                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1629         }
1630
1631         /* Don't disable pipe or pipe PLLs if needed */
1632         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1633             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1634                 return;
1635
1636         /* Make sure the pipe isn't still relying on us */
1637         assert_pipe_disabled(dev_priv, pipe);
1638
1639         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1640         POSTING_READ(DPLL(pipe));
1641 }
1642
1643 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1644 {
1645         u32 val;
1646
1647         /* Make sure the pipe isn't still relying on us */
1648         assert_pipe_disabled(dev_priv, pipe);
1649
1650         val = DPLL_INTEGRATED_REF_CLK_VLV |
1651                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1652         if (pipe != PIPE_A)
1653                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1654
1655         I915_WRITE(DPLL(pipe), val);
1656         POSTING_READ(DPLL(pipe));
1657 }
1658
1659 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1660 {
1661         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1662         u32 val;
1663
1664         /* Make sure the pipe isn't still relying on us */
1665         assert_pipe_disabled(dev_priv, pipe);
1666
1667         val = DPLL_SSC_REF_CLK_CHV |
1668                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1669         if (pipe != PIPE_A)
1670                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1671
1672         I915_WRITE(DPLL(pipe), val);
1673         POSTING_READ(DPLL(pipe));
1674
1675         mutex_lock(&dev_priv->sb_lock);
1676
1677         /* Disable 10bit clock to display controller */
1678         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1679         val &= ~DPIO_DCLKP_EN;
1680         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1681
1682         mutex_unlock(&dev_priv->sb_lock);
1683 }
1684
1685 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1686                          struct intel_digital_port *dport,
1687                          unsigned int expected_mask)
1688 {
1689         u32 port_mask;
1690         i915_reg_t dpll_reg;
1691
1692         switch (dport->port) {
1693         case PORT_B:
1694                 port_mask = DPLL_PORTB_READY_MASK;
1695                 dpll_reg = DPLL(0);
1696                 break;
1697         case PORT_C:
1698                 port_mask = DPLL_PORTC_READY_MASK;
1699                 dpll_reg = DPLL(0);
1700                 expected_mask <<= 4;
1701                 break;
1702         case PORT_D:
1703                 port_mask = DPLL_PORTD_READY_MASK;
1704                 dpll_reg = DPIO_PHY_STATUS;
1705                 break;
1706         default:
1707                 BUG();
1708         }
1709
1710         if (intel_wait_for_register(dev_priv,
1711                                     dpll_reg, port_mask, expected_mask,
1712                                     1000))
1713                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1714                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1715 }
1716
1717 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1718                                            enum pipe pipe)
1719 {
1720         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1721                                                                 pipe);
1722         i915_reg_t reg;
1723         uint32_t val, pipeconf_val;
1724
1725         /* Make sure PCH DPLL is enabled */
1726         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1727
1728         /* FDI must be feeding us bits for PCH ports */
1729         assert_fdi_tx_enabled(dev_priv, pipe);
1730         assert_fdi_rx_enabled(dev_priv, pipe);
1731
1732         if (HAS_PCH_CPT(dev_priv)) {
1733                 /* Workaround: Set the timing override bit before enabling the
1734                  * pch transcoder. */
1735                 reg = TRANS_CHICKEN2(pipe);
1736                 val = I915_READ(reg);
1737                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1738                 I915_WRITE(reg, val);
1739         }
1740
1741         reg = PCH_TRANSCONF(pipe);
1742         val = I915_READ(reg);
1743         pipeconf_val = I915_READ(PIPECONF(pipe));
1744
1745         if (HAS_PCH_IBX(dev_priv)) {
1746                 /*
1747                  * Make the BPC in transcoder be consistent with
1748                  * that in pipeconf reg. For HDMI we must use 8bpc
1749                  * here for both 8bpc and 12bpc.
1750                  */
1751                 val &= ~PIPECONF_BPC_MASK;
1752                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1753                         val |= PIPECONF_8BPC;
1754                 else
1755                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1756         }
1757
1758         val &= ~TRANS_INTERLACE_MASK;
1759         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1760                 if (HAS_PCH_IBX(dev_priv) &&
1761                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1762                         val |= TRANS_LEGACY_INTERLACED_ILK;
1763                 else
1764                         val |= TRANS_INTERLACED;
1765         else
1766                 val |= TRANS_PROGRESSIVE;
1767
1768         I915_WRITE(reg, val | TRANS_ENABLE);
1769         if (intel_wait_for_register(dev_priv,
1770                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1771                                     100))
1772                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1773 }
1774
1775 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1776                                       enum transcoder cpu_transcoder)
1777 {
1778         u32 val, pipeconf_val;
1779
1780         /* FDI must be feeding us bits for PCH ports */
1781         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1782         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1783
1784         /* Workaround: set timing override bit. */
1785         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1786         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1787         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1788
1789         val = TRANS_ENABLE;
1790         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1791
1792         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1793             PIPECONF_INTERLACED_ILK)
1794                 val |= TRANS_INTERLACED;
1795         else
1796                 val |= TRANS_PROGRESSIVE;
1797
1798         I915_WRITE(LPT_TRANSCONF, val);
1799         if (intel_wait_for_register(dev_priv,
1800                                     LPT_TRANSCONF,
1801                                     TRANS_STATE_ENABLE,
1802                                     TRANS_STATE_ENABLE,
1803                                     100))
1804                 DRM_ERROR("Failed to enable PCH transcoder\n");
1805 }
1806
1807 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1808                                             enum pipe pipe)
1809 {
1810         i915_reg_t reg;
1811         uint32_t val;
1812
1813         /* FDI relies on the transcoder */
1814         assert_fdi_tx_disabled(dev_priv, pipe);
1815         assert_fdi_rx_disabled(dev_priv, pipe);
1816
1817         /* Ports must be off as well */
1818         assert_pch_ports_disabled(dev_priv, pipe);
1819
1820         reg = PCH_TRANSCONF(pipe);
1821         val = I915_READ(reg);
1822         val &= ~TRANS_ENABLE;
1823         I915_WRITE(reg, val);
1824         /* wait for PCH transcoder off, transcoder state */
1825         if (intel_wait_for_register(dev_priv,
1826                                     reg, TRANS_STATE_ENABLE, 0,
1827                                     50))
1828                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1829
1830         if (HAS_PCH_CPT(dev_priv)) {
1831                 /* Workaround: Clear the timing override chicken bit again. */
1832                 reg = TRANS_CHICKEN2(pipe);
1833                 val = I915_READ(reg);
1834                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1835                 I915_WRITE(reg, val);
1836         }
1837 }
1838
1839 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1840 {
1841         u32 val;
1842
1843         val = I915_READ(LPT_TRANSCONF);
1844         val &= ~TRANS_ENABLE;
1845         I915_WRITE(LPT_TRANSCONF, val);
1846         /* wait for PCH transcoder off, transcoder state */
1847         if (intel_wait_for_register(dev_priv,
1848                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1849                                     50))
1850                 DRM_ERROR("Failed to disable PCH transcoder\n");
1851
1852         /* Workaround: clear timing override bit. */
1853         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1854         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1855         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1856 }
1857
1858 enum transcoder intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1859 {
1860         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1861
1862         WARN_ON(!crtc->config->has_pch_encoder);
1863
1864         if (HAS_PCH_LPT(dev_priv))
1865                 return TRANSCODER_A;
1866         else
1867                 return (enum transcoder) crtc->pipe;
1868 }
1869
1870 /**
1871  * intel_enable_pipe - enable a pipe, asserting requirements
1872  * @crtc: crtc responsible for the pipe
1873  *
1874  * Enable @crtc's pipe, making sure that various hardware specific requirements
1875  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1876  */
1877 static void intel_enable_pipe(struct intel_crtc *crtc)
1878 {
1879         struct drm_device *dev = crtc->base.dev;
1880         struct drm_i915_private *dev_priv = to_i915(dev);
1881         enum pipe pipe = crtc->pipe;
1882         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1883         i915_reg_t reg;
1884         u32 val;
1885
1886         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1887
1888         assert_planes_disabled(dev_priv, pipe);
1889         assert_cursor_disabled(dev_priv, pipe);
1890         assert_sprites_disabled(dev_priv, pipe);
1891
1892         /*
1893          * A pipe without a PLL won't actually be able to drive bits from
1894          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1895          * need the check.
1896          */
1897         if (HAS_GMCH_DISPLAY(dev_priv)) {
1898                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1899                         assert_dsi_pll_enabled(dev_priv);
1900                 else
1901                         assert_pll_enabled(dev_priv, pipe);
1902         } else {
1903                 if (crtc->config->has_pch_encoder) {
1904                         /* if driving the PCH, we need FDI enabled */
1905                         assert_fdi_rx_pll_enabled(dev_priv,
1906                                                   (enum pipe) intel_crtc_pch_transcoder(crtc));
1907                         assert_fdi_tx_pll_enabled(dev_priv,
1908                                                   (enum pipe) cpu_transcoder);
1909                 }
1910                 /* FIXME: assert CPU port conditions for SNB+ */
1911         }
1912
1913         reg = PIPECONF(cpu_transcoder);
1914         val = I915_READ(reg);
1915         if (val & PIPECONF_ENABLE) {
1916                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1917                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1918                 return;
1919         }
1920
1921         I915_WRITE(reg, val | PIPECONF_ENABLE);
1922         POSTING_READ(reg);
1923
1924         /*
1925          * Until the pipe starts DSL will read as 0, which would cause
1926          * an apparent vblank timestamp jump, which messes up also the
1927          * frame count when it's derived from the timestamps. So let's
1928          * wait for the pipe to start properly before we call
1929          * drm_crtc_vblank_on()
1930          */
1931         if (dev->max_vblank_count == 0 &&
1932             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1933                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1934 }
1935
1936 /**
1937  * intel_disable_pipe - disable a pipe, asserting requirements
1938  * @crtc: crtc whose pipes is to be disabled
1939  *
1940  * Disable the pipe of @crtc, making sure that various hardware
1941  * specific requirements are met, if applicable, e.g. plane
1942  * disabled, panel fitter off, etc.
1943  *
1944  * Will wait until the pipe has shut down before returning.
1945  */
1946 static void intel_disable_pipe(struct intel_crtc *crtc)
1947 {
1948         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1949         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1950         enum pipe pipe = crtc->pipe;
1951         i915_reg_t reg;
1952         u32 val;
1953
1954         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1955
1956         /*
1957          * Make sure planes won't keep trying to pump pixels to us,
1958          * or we might hang the display.
1959          */
1960         assert_planes_disabled(dev_priv, pipe);
1961         assert_cursor_disabled(dev_priv, pipe);
1962         assert_sprites_disabled(dev_priv, pipe);
1963
1964         reg = PIPECONF(cpu_transcoder);
1965         val = I915_READ(reg);
1966         if ((val & PIPECONF_ENABLE) == 0)
1967                 return;
1968
1969         /*
1970          * Double wide has implications for planes
1971          * so best keep it disabled when not needed.
1972          */
1973         if (crtc->config->double_wide)
1974                 val &= ~PIPECONF_DOUBLE_WIDE;
1975
1976         /* Don't disable pipe or pipe PLLs if needed */
1977         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
1978             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1979                 val &= ~PIPECONF_ENABLE;
1980
1981         I915_WRITE(reg, val);
1982         if ((val & PIPECONF_ENABLE) == 0)
1983                 intel_wait_for_pipe_off(crtc);
1984 }
1985
1986 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1987 {
1988         return IS_GEN2(dev_priv) ? 2048 : 4096;
1989 }
1990
1991 static unsigned int
1992 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1993 {
1994         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1995         unsigned int cpp = fb->format->cpp[plane];
1996
1997         switch (fb->modifier) {
1998         case DRM_FORMAT_MOD_LINEAR:
1999                 return cpp;
2000         case I915_FORMAT_MOD_X_TILED:
2001                 if (IS_GEN2(dev_priv))
2002                         return 128;
2003                 else
2004                         return 512;
2005         case I915_FORMAT_MOD_Y_TILED:
2006                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2007                         return 128;
2008                 else
2009                         return 512;
2010         case I915_FORMAT_MOD_Yf_TILED:
2011                 switch (cpp) {
2012                 case 1:
2013                         return 64;
2014                 case 2:
2015                 case 4:
2016                         return 128;
2017                 case 8:
2018                 case 16:
2019                         return 256;
2020                 default:
2021                         MISSING_CASE(cpp);
2022                         return cpp;
2023                 }
2024                 break;
2025         default:
2026                 MISSING_CASE(fb->modifier);
2027                 return cpp;
2028         }
2029 }
2030
2031 static unsigned int
2032 intel_tile_height(const struct drm_framebuffer *fb, int plane)
2033 {
2034         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
2035                 return 1;
2036         else
2037                 return intel_tile_size(to_i915(fb->dev)) /
2038                         intel_tile_width_bytes(fb, plane);
2039 }
2040
2041 /* Return the tile dimensions in pixel units */
2042 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
2043                             unsigned int *tile_width,
2044                             unsigned int *tile_height)
2045 {
2046         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
2047         unsigned int cpp = fb->format->cpp[plane];
2048
2049         *tile_width = tile_width_bytes / cpp;
2050         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
2051 }
2052
2053 unsigned int
2054 intel_fb_align_height(const struct drm_framebuffer *fb,
2055                       int plane, unsigned int height)
2056 {
2057         unsigned int tile_height = intel_tile_height(fb, plane);
2058
2059         return ALIGN(height, tile_height);
2060 }
2061
2062 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2063 {
2064         unsigned int size = 0;
2065         int i;
2066
2067         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2068                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2069
2070         return size;
2071 }
2072
2073 static void
2074 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2075                         const struct drm_framebuffer *fb,
2076                         unsigned int rotation)
2077 {
2078         view->type = I915_GGTT_VIEW_NORMAL;
2079         if (drm_rotation_90_or_270(rotation)) {
2080                 view->type = I915_GGTT_VIEW_ROTATED;
2081                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2082         }
2083 }
2084
2085 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2086 {
2087         if (IS_I830(dev_priv))
2088                 return 16 * 1024;
2089         else if (IS_I85X(dev_priv))
2090                 return 256;
2091         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2092                 return 32;
2093         else
2094                 return 4 * 1024;
2095 }
2096
2097 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2098 {
2099         if (INTEL_INFO(dev_priv)->gen >= 9)
2100                 return 256 * 1024;
2101         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2102                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2103                 return 128 * 1024;
2104         else if (INTEL_INFO(dev_priv)->gen >= 4)
2105                 return 4 * 1024;
2106         else
2107                 return 0;
2108 }
2109
2110 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2111                                          int plane)
2112 {
2113         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2114
2115         /* AUX_DIST needs only 4K alignment */
2116         if (fb->format->format == DRM_FORMAT_NV12 && plane == 1)
2117                 return 4096;
2118
2119         switch (fb->modifier) {
2120         case DRM_FORMAT_MOD_LINEAR:
2121                 return intel_linear_alignment(dev_priv);
2122         case I915_FORMAT_MOD_X_TILED:
2123                 if (INTEL_GEN(dev_priv) >= 9)
2124                         return 256 * 1024;
2125                 return 0;
2126         case I915_FORMAT_MOD_Y_TILED:
2127         case I915_FORMAT_MOD_Yf_TILED:
2128                 return 1 * 1024 * 1024;
2129         default:
2130                 MISSING_CASE(fb->modifier);
2131                 return 0;
2132         }
2133 }
2134
2135 struct i915_vma *
2136 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2137 {
2138         struct drm_device *dev = fb->dev;
2139         struct drm_i915_private *dev_priv = to_i915(dev);
2140         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2141         struct i915_ggtt_view view;
2142         struct i915_vma *vma;
2143         u32 alignment;
2144
2145         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2146
2147         alignment = intel_surf_alignment(fb, 0);
2148
2149         intel_fill_fb_ggtt_view(&view, fb, rotation);
2150
2151         /* Note that the w/a also requires 64 PTE of padding following the
2152          * bo. We currently fill all unused PTE with the shadow page and so
2153          * we should always have valid PTE following the scanout preventing
2154          * the VT-d warning.
2155          */
2156         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2157                 alignment = 256 * 1024;
2158
2159         /*
2160          * Global gtt pte registers are special registers which actually forward
2161          * writes to a chunk of system memory. Which means that there is no risk
2162          * that the register values disappear as soon as we call
2163          * intel_runtime_pm_put(), so it is correct to wrap only the
2164          * pin/unpin/fence and not more.
2165          */
2166         intel_runtime_pm_get(dev_priv);
2167
2168         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2169         if (IS_ERR(vma))
2170                 goto err;
2171
2172         if (i915_vma_is_map_and_fenceable(vma)) {
2173                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2174                  * fence, whereas 965+ only requires a fence if using
2175                  * framebuffer compression.  For simplicity, we always, when
2176                  * possible, install a fence as the cost is not that onerous.
2177                  *
2178                  * If we fail to fence the tiled scanout, then either the
2179                  * modeset will reject the change (which is highly unlikely as
2180                  * the affected systems, all but one, do not have unmappable
2181                  * space) or we will not be able to enable full powersaving
2182                  * techniques (also likely not to apply due to various limits
2183                  * FBC and the like impose on the size of the buffer, which
2184                  * presumably we violated anyway with this unmappable buffer).
2185                  * Anyway, it is presumably better to stumble onwards with
2186                  * something and try to run the system in a "less than optimal"
2187                  * mode that matches the user configuration.
2188                  */
2189                 if (i915_vma_get_fence(vma) == 0)
2190                         i915_vma_pin_fence(vma);
2191         }
2192
2193         i915_vma_get(vma);
2194 err:
2195         intel_runtime_pm_put(dev_priv);
2196         return vma;
2197 }
2198
2199 void intel_unpin_fb_vma(struct i915_vma *vma)
2200 {
2201         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2202
2203         i915_vma_unpin_fence(vma);
2204         i915_gem_object_unpin_from_display_plane(vma);
2205         i915_vma_put(vma);
2206 }
2207
2208 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2209                           unsigned int rotation)
2210 {
2211         if (drm_rotation_90_or_270(rotation))
2212                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2213         else
2214                 return fb->pitches[plane];
2215 }
2216
2217 /*
2218  * Convert the x/y offsets into a linear offset.
2219  * Only valid with 0/180 degree rotation, which is fine since linear
2220  * offset is only used with linear buffers on pre-hsw and tiled buffers
2221  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2222  */
2223 u32 intel_fb_xy_to_linear(int x, int y,
2224                           const struct intel_plane_state *state,
2225                           int plane)
2226 {
2227         const struct drm_framebuffer *fb = state->base.fb;
2228         unsigned int cpp = fb->format->cpp[plane];
2229         unsigned int pitch = fb->pitches[plane];
2230
2231         return y * pitch + x * cpp;
2232 }
2233
2234 /*
2235  * Add the x/y offsets derived from fb->offsets[] to the user
2236  * specified plane src x/y offsets. The resulting x/y offsets
2237  * specify the start of scanout from the beginning of the gtt mapping.
2238  */
2239 void intel_add_fb_offsets(int *x, int *y,
2240                           const struct intel_plane_state *state,
2241                           int plane)
2242
2243 {
2244         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2245         unsigned int rotation = state->base.rotation;
2246
2247         if (drm_rotation_90_or_270(rotation)) {
2248                 *x += intel_fb->rotated[plane].x;
2249                 *y += intel_fb->rotated[plane].y;
2250         } else {
2251                 *x += intel_fb->normal[plane].x;
2252                 *y += intel_fb->normal[plane].y;
2253         }
2254 }
2255
2256 /*
2257  * Input tile dimensions and pitch must already be
2258  * rotated to match x and y, and in pixel units.
2259  */
2260 static u32 _intel_adjust_tile_offset(int *x, int *y,
2261                                      unsigned int tile_width,
2262                                      unsigned int tile_height,
2263                                      unsigned int tile_size,
2264                                      unsigned int pitch_tiles,
2265                                      u32 old_offset,
2266                                      u32 new_offset)
2267 {
2268         unsigned int pitch_pixels = pitch_tiles * tile_width;
2269         unsigned int tiles;
2270
2271         WARN_ON(old_offset & (tile_size - 1));
2272         WARN_ON(new_offset & (tile_size - 1));
2273         WARN_ON(new_offset > old_offset);
2274
2275         tiles = (old_offset - new_offset) / tile_size;
2276
2277         *y += tiles / pitch_tiles * tile_height;
2278         *x += tiles % pitch_tiles * tile_width;
2279
2280         /* minimize x in case it got needlessly big */
2281         *y += *x / pitch_pixels * tile_height;
2282         *x %= pitch_pixels;
2283
2284         return new_offset;
2285 }
2286
2287 /*
2288  * Adjust the tile offset by moving the difference into
2289  * the x/y offsets.
2290  */
2291 static u32 intel_adjust_tile_offset(int *x, int *y,
2292                                     const struct intel_plane_state *state, int plane,
2293                                     u32 old_offset, u32 new_offset)
2294 {
2295         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2296         const struct drm_framebuffer *fb = state->base.fb;
2297         unsigned int cpp = fb->format->cpp[plane];
2298         unsigned int rotation = state->base.rotation;
2299         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2300
2301         WARN_ON(new_offset > old_offset);
2302
2303         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2304                 unsigned int tile_size, tile_width, tile_height;
2305                 unsigned int pitch_tiles;
2306
2307                 tile_size = intel_tile_size(dev_priv);
2308                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2309
2310                 if (drm_rotation_90_or_270(rotation)) {
2311                         pitch_tiles = pitch / tile_height;
2312                         swap(tile_width, tile_height);
2313                 } else {
2314                         pitch_tiles = pitch / (tile_width * cpp);
2315                 }
2316
2317                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2318                                           tile_size, pitch_tiles,
2319                                           old_offset, new_offset);
2320         } else {
2321                 old_offset += *y * pitch + *x * cpp;
2322
2323                 *y = (old_offset - new_offset) / pitch;
2324                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2325         }
2326
2327         return new_offset;
2328 }
2329
2330 /*
2331  * Computes the linear offset to the base tile and adjusts
2332  * x, y. bytes per pixel is assumed to be a power-of-two.
2333  *
2334  * In the 90/270 rotated case, x and y are assumed
2335  * to be already rotated to match the rotated GTT view, and
2336  * pitch is the tile_height aligned framebuffer height.
2337  *
2338  * This function is used when computing the derived information
2339  * under intel_framebuffer, so using any of that information
2340  * here is not allowed. Anything under drm_framebuffer can be
2341  * used. This is why the user has to pass in the pitch since it
2342  * is specified in the rotated orientation.
2343  */
2344 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2345                                       int *x, int *y,
2346                                       const struct drm_framebuffer *fb, int plane,
2347                                       unsigned int pitch,
2348                                       unsigned int rotation,
2349                                       u32 alignment)
2350 {
2351         uint64_t fb_modifier = fb->modifier;
2352         unsigned int cpp = fb->format->cpp[plane];
2353         u32 offset, offset_aligned;
2354
2355         if (alignment)
2356                 alignment--;
2357
2358         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2359                 unsigned int tile_size, tile_width, tile_height;
2360                 unsigned int tile_rows, tiles, pitch_tiles;
2361
2362                 tile_size = intel_tile_size(dev_priv);
2363                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2364
2365                 if (drm_rotation_90_or_270(rotation)) {
2366                         pitch_tiles = pitch / tile_height;
2367                         swap(tile_width, tile_height);
2368                 } else {
2369                         pitch_tiles = pitch / (tile_width * cpp);
2370                 }
2371
2372                 tile_rows = *y / tile_height;
2373                 *y %= tile_height;
2374
2375                 tiles = *x / tile_width;
2376                 *x %= tile_width;
2377
2378                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2379                 offset_aligned = offset & ~alignment;
2380
2381                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2382                                           tile_size, pitch_tiles,
2383                                           offset, offset_aligned);
2384         } else {
2385                 offset = *y * pitch + *x * cpp;
2386                 offset_aligned = offset & ~alignment;
2387
2388                 *y = (offset & alignment) / pitch;
2389                 *x = ((offset & alignment) - *y * pitch) / cpp;
2390         }
2391
2392         return offset_aligned;
2393 }
2394
2395 u32 intel_compute_tile_offset(int *x, int *y,
2396                               const struct intel_plane_state *state,
2397                               int plane)
2398 {
2399         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2400         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2401         const struct drm_framebuffer *fb = state->base.fb;
2402         unsigned int rotation = state->base.rotation;
2403         int pitch = intel_fb_pitch(fb, plane, rotation);
2404         u32 alignment;
2405
2406         if (intel_plane->id == PLANE_CURSOR)
2407                 alignment = intel_cursor_alignment(dev_priv);
2408         else
2409                 alignment = intel_surf_alignment(fb, plane);
2410
2411         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2412                                           rotation, alignment);
2413 }
2414
2415 /* Convert the fb->offset[] linear offset into x/y offsets */
2416 static void intel_fb_offset_to_xy(int *x, int *y,
2417                                   const struct drm_framebuffer *fb, int plane)
2418 {
2419         unsigned int cpp = fb->format->cpp[plane];
2420         unsigned int pitch = fb->pitches[plane];
2421         u32 linear_offset = fb->offsets[plane];
2422
2423         *y = linear_offset / pitch;
2424         *x = linear_offset % pitch / cpp;
2425 }
2426
2427 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2428 {
2429         switch (fb_modifier) {
2430         case I915_FORMAT_MOD_X_TILED:
2431                 return I915_TILING_X;
2432         case I915_FORMAT_MOD_Y_TILED:
2433                 return I915_TILING_Y;
2434         default:
2435                 return I915_TILING_NONE;
2436         }
2437 }
2438
2439 static int
2440 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2441                    struct drm_framebuffer *fb)
2442 {
2443         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2444         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2445         u32 gtt_offset_rotated = 0;
2446         unsigned int max_size = 0;
2447         int i, num_planes = fb->format->num_planes;
2448         unsigned int tile_size = intel_tile_size(dev_priv);
2449
2450         for (i = 0; i < num_planes; i++) {
2451                 unsigned int width, height;
2452                 unsigned int cpp, size;
2453                 u32 offset;
2454                 int x, y;
2455
2456                 cpp = fb->format->cpp[i];
2457                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2458                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2459
2460                 intel_fb_offset_to_xy(&x, &y, fb, i);
2461
2462                 /*
2463                  * The fence (if used) is aligned to the start of the object
2464                  * so having the framebuffer wrap around across the edge of the
2465                  * fenced region doesn't really work. We have no API to configure
2466                  * the fence start offset within the object (nor could we probably
2467                  * on gen2/3). So it's just easier if we just require that the
2468                  * fb layout agrees with the fence layout. We already check that the
2469                  * fb stride matches the fence stride elsewhere.
2470                  */
2471                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2472                     (x + width) * cpp > fb->pitches[i]) {
2473                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2474                                       i, fb->offsets[i]);
2475                         return -EINVAL;
2476                 }
2477
2478                 /*
2479                  * First pixel of the framebuffer from
2480                  * the start of the normal gtt mapping.
2481                  */
2482                 intel_fb->normal[i].x = x;
2483                 intel_fb->normal[i].y = y;
2484
2485                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2486                                                     fb, i, fb->pitches[i],
2487                                                     DRM_MODE_ROTATE_0, tile_size);
2488                 offset /= tile_size;
2489
2490                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2491                         unsigned int tile_width, tile_height;
2492                         unsigned int pitch_tiles;
2493                         struct drm_rect r;
2494
2495                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2496
2497                         rot_info->plane[i].offset = offset;
2498                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2499                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2500                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2501
2502                         intel_fb->rotated[i].pitch =
2503                                 rot_info->plane[i].height * tile_height;
2504
2505                         /* how many tiles does this plane need */
2506                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2507                         /*
2508                          * If the plane isn't horizontally tile aligned,
2509                          * we need one more tile.
2510                          */
2511                         if (x != 0)
2512                                 size++;
2513
2514                         /* rotate the x/y offsets to match the GTT view */
2515                         r.x1 = x;
2516                         r.y1 = y;
2517                         r.x2 = x + width;
2518                         r.y2 = y + height;
2519                         drm_rect_rotate(&r,
2520                                         rot_info->plane[i].width * tile_width,
2521                                         rot_info->plane[i].height * tile_height,
2522                                         DRM_MODE_ROTATE_270);
2523                         x = r.x1;
2524                         y = r.y1;
2525
2526                         /* rotate the tile dimensions to match the GTT view */
2527                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2528                         swap(tile_width, tile_height);
2529
2530                         /*
2531                          * We only keep the x/y offsets, so push all of the
2532                          * gtt offset into the x/y offsets.
2533                          */
2534                         _intel_adjust_tile_offset(&x, &y,
2535                                                   tile_width, tile_height,
2536                                                   tile_size, pitch_tiles,
2537                                                   gtt_offset_rotated * tile_size, 0);
2538
2539                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2540
2541                         /*
2542                          * First pixel of the framebuffer from
2543                          * the start of the rotated gtt mapping.
2544                          */
2545                         intel_fb->rotated[i].x = x;
2546                         intel_fb->rotated[i].y = y;
2547                 } else {
2548                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2549                                             x * cpp, tile_size);
2550                 }
2551
2552                 /* how many tiles in total needed in the bo */
2553                 max_size = max(max_size, offset + size);
2554         }
2555
2556         if (max_size * tile_size > intel_fb->obj->base.size) {
2557                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2558                               max_size * tile_size, intel_fb->obj->base.size);
2559                 return -EINVAL;
2560         }
2561
2562         return 0;
2563 }
2564
2565 static int i9xx_format_to_fourcc(int format)
2566 {
2567         switch (format) {
2568         case DISPPLANE_8BPP:
2569                 return DRM_FORMAT_C8;
2570         case DISPPLANE_BGRX555:
2571                 return DRM_FORMAT_XRGB1555;
2572         case DISPPLANE_BGRX565:
2573                 return DRM_FORMAT_RGB565;
2574         default:
2575         case DISPPLANE_BGRX888:
2576                 return DRM_FORMAT_XRGB8888;
2577         case DISPPLANE_RGBX888:
2578                 return DRM_FORMAT_XBGR8888;
2579         case DISPPLANE_BGRX101010:
2580                 return DRM_FORMAT_XRGB2101010;
2581         case DISPPLANE_RGBX101010:
2582                 return DRM_FORMAT_XBGR2101010;
2583         }
2584 }
2585
2586 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2587 {
2588         switch (format) {
2589         case PLANE_CTL_FORMAT_RGB_565:
2590                 return DRM_FORMAT_RGB565;
2591         default:
2592         case PLANE_CTL_FORMAT_XRGB_8888:
2593                 if (rgb_order) {
2594                         if (alpha)
2595                                 return DRM_FORMAT_ABGR8888;
2596                         else
2597                                 return DRM_FORMAT_XBGR8888;
2598                 } else {
2599                         if (alpha)
2600                                 return DRM_FORMAT_ARGB8888;
2601                         else
2602                                 return DRM_FORMAT_XRGB8888;
2603                 }
2604         case PLANE_CTL_FORMAT_XRGB_2101010:
2605                 if (rgb_order)
2606                         return DRM_FORMAT_XBGR2101010;
2607                 else
2608                         return DRM_FORMAT_XRGB2101010;
2609         }
2610 }
2611
2612 static bool
2613 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2614                               struct intel_initial_plane_config *plane_config)
2615 {
2616         struct drm_device *dev = crtc->base.dev;
2617         struct drm_i915_private *dev_priv = to_i915(dev);
2618         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2619         struct drm_i915_gem_object *obj = NULL;
2620         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2621         struct drm_framebuffer *fb = &plane_config->fb->base;
2622         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2623         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2624                                     PAGE_SIZE);
2625
2626         size_aligned -= base_aligned;
2627
2628         if (plane_config->size == 0)
2629                 return false;
2630
2631         /* If the FB is too big, just don't use it since fbdev is not very
2632          * important and we should probably use that space with FBC or other
2633          * features. */
2634         if (size_aligned * 2 > ggtt->stolen_usable_size)
2635                 return false;
2636
2637         mutex_lock(&dev->struct_mutex);
2638         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2639                                                              base_aligned,
2640                                                              base_aligned,
2641                                                              size_aligned);
2642         mutex_unlock(&dev->struct_mutex);
2643         if (!obj)
2644                 return false;
2645
2646         if (plane_config->tiling == I915_TILING_X)
2647                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2648
2649         mode_cmd.pixel_format = fb->format->format;
2650         mode_cmd.width = fb->width;
2651         mode_cmd.height = fb->height;
2652         mode_cmd.pitches[0] = fb->pitches[0];
2653         mode_cmd.modifier[0] = fb->modifier;
2654         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2655
2656         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2657                 DRM_DEBUG_KMS("intel fb init failed\n");
2658                 goto out_unref_obj;
2659         }
2660
2661
2662         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2663         return true;
2664
2665 out_unref_obj:
2666         i915_gem_object_put(obj);
2667         return false;
2668 }
2669
2670 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2671 static void
2672 update_state_fb(struct drm_plane *plane)
2673 {
2674         if (plane->fb == plane->state->fb)
2675                 return;
2676
2677         if (plane->state->fb)
2678                 drm_framebuffer_unreference(plane->state->fb);
2679         plane->state->fb = plane->fb;
2680         if (plane->state->fb)
2681                 drm_framebuffer_reference(plane->state->fb);
2682 }
2683
2684 static void
2685 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2686                         struct intel_plane_state *plane_state,
2687                         bool visible)
2688 {
2689         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2690
2691         plane_state->base.visible = visible;
2692
2693         /* FIXME pre-g4x don't work like this */
2694         if (visible) {
2695                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2696                 crtc_state->active_planes |= BIT(plane->id);
2697         } else {
2698                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2699                 crtc_state->active_planes &= ~BIT(plane->id);
2700         }
2701
2702         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2703                       crtc_state->base.crtc->name,
2704                       crtc_state->active_planes);
2705 }
2706
2707 static void
2708 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2709                              struct intel_initial_plane_config *plane_config)
2710 {
2711         struct drm_device *dev = intel_crtc->base.dev;
2712         struct drm_i915_private *dev_priv = to_i915(dev);
2713         struct drm_crtc *c;
2714         struct drm_i915_gem_object *obj;
2715         struct drm_plane *primary = intel_crtc->base.primary;
2716         struct drm_plane_state *plane_state = primary->state;
2717         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2718         struct intel_plane *intel_plane = to_intel_plane(primary);
2719         struct intel_plane_state *intel_state =
2720                 to_intel_plane_state(plane_state);
2721         struct drm_framebuffer *fb;
2722
2723         if (!plane_config->fb)
2724                 return;
2725
2726         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2727                 fb = &plane_config->fb->base;
2728                 goto valid_fb;
2729         }
2730
2731         kfree(plane_config->fb);
2732
2733         /*
2734          * Failed to alloc the obj, check to see if we should share
2735          * an fb with another CRTC instead
2736          */
2737         for_each_crtc(dev, c) {
2738                 struct intel_plane_state *state;
2739
2740                 if (c == &intel_crtc->base)
2741                         continue;
2742
2743                 if (!to_intel_crtc(c)->active)
2744                         continue;
2745
2746                 state = to_intel_plane_state(c->primary->state);
2747                 if (!state->vma)
2748                         continue;
2749
2750                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2751                         fb = c->primary->fb;
2752                         drm_framebuffer_reference(fb);
2753                         goto valid_fb;
2754                 }
2755         }
2756
2757         /*
2758          * We've failed to reconstruct the BIOS FB.  Current display state
2759          * indicates that the primary plane is visible, but has a NULL FB,
2760          * which will lead to problems later if we don't fix it up.  The
2761          * simplest solution is to just disable the primary plane now and
2762          * pretend the BIOS never had it enabled.
2763          */
2764         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2765                                 to_intel_plane_state(plane_state),
2766                                 false);
2767         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2768         trace_intel_disable_plane(primary, intel_crtc);
2769         intel_plane->disable_plane(intel_plane, intel_crtc);
2770
2771         return;
2772
2773 valid_fb:
2774         mutex_lock(&dev->struct_mutex);
2775         intel_state->vma =
2776                 intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
2777         mutex_unlock(&dev->struct_mutex);
2778         if (IS_ERR(intel_state->vma)) {
2779                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2780                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2781
2782                 intel_state->vma = NULL;
2783                 drm_framebuffer_unreference(fb);
2784                 return;
2785         }
2786
2787         plane_state->src_x = 0;
2788         plane_state->src_y = 0;
2789         plane_state->src_w = fb->width << 16;
2790         plane_state->src_h = fb->height << 16;
2791
2792         plane_state->crtc_x = 0;
2793         plane_state->crtc_y = 0;
2794         plane_state->crtc_w = fb->width;
2795         plane_state->crtc_h = fb->height;
2796
2797         intel_state->base.src = drm_plane_state_src(plane_state);
2798         intel_state->base.dst = drm_plane_state_dest(plane_state);
2799
2800         obj = intel_fb_obj(fb);
2801         if (i915_gem_object_is_tiled(obj))
2802                 dev_priv->preserve_bios_swizzle = true;
2803
2804         drm_framebuffer_reference(fb);
2805         primary->fb = primary->state->fb = fb;
2806         primary->crtc = primary->state->crtc = &intel_crtc->base;
2807
2808         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2809                                 to_intel_plane_state(plane_state),
2810                                 true);
2811
2812         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2813                   &obj->frontbuffer_bits);
2814 }
2815
2816 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2817                                unsigned int rotation)
2818 {
2819         int cpp = fb->format->cpp[plane];
2820
2821         switch (fb->modifier) {
2822         case DRM_FORMAT_MOD_LINEAR:
2823         case I915_FORMAT_MOD_X_TILED:
2824                 switch (cpp) {
2825                 case 8:
2826                         return 4096;
2827                 case 4:
2828                 case 2:
2829                 case 1:
2830                         return 8192;
2831                 default:
2832                         MISSING_CASE(cpp);
2833                         break;
2834                 }
2835                 break;
2836         case I915_FORMAT_MOD_Y_TILED:
2837         case I915_FORMAT_MOD_Yf_TILED:
2838                 switch (cpp) {
2839                 case 8:
2840                         return 2048;
2841                 case 4:
2842                         return 4096;
2843                 case 2:
2844                 case 1:
2845                         return 8192;
2846                 default:
2847                         MISSING_CASE(cpp);
2848                         break;
2849                 }
2850                 break;
2851         default:
2852                 MISSING_CASE(fb->modifier);
2853         }
2854
2855         return 2048;
2856 }
2857
2858 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2859 {
2860         const struct drm_framebuffer *fb = plane_state->base.fb;
2861         unsigned int rotation = plane_state->base.rotation;
2862         int x = plane_state->base.src.x1 >> 16;
2863         int y = plane_state->base.src.y1 >> 16;
2864         int w = drm_rect_width(&plane_state->base.src) >> 16;
2865         int h = drm_rect_height(&plane_state->base.src) >> 16;
2866         int max_width = skl_max_plane_width(fb, 0, rotation);
2867         int max_height = 4096;
2868         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2869
2870         if (w > max_width || h > max_height) {
2871                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2872                               w, h, max_width, max_height);
2873                 return -EINVAL;
2874         }
2875
2876         intel_add_fb_offsets(&x, &y, plane_state, 0);
2877         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2878         alignment = intel_surf_alignment(fb, 0);
2879
2880         /*
2881          * AUX surface offset is specified as the distance from the
2882          * main surface offset, and it must be non-negative. Make
2883          * sure that is what we will get.
2884          */
2885         if (offset > aux_offset)
2886                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2887                                                   offset, aux_offset & ~(alignment - 1));
2888
2889         /*
2890          * When using an X-tiled surface, the plane blows up
2891          * if the x offset + width exceed the stride.
2892          *
2893          * TODO: linear and Y-tiled seem fine, Yf untested,
2894          */
2895         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
2896                 int cpp = fb->format->cpp[0];
2897
2898                 while ((x + w) * cpp > fb->pitches[0]) {
2899                         if (offset == 0) {
2900                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2901                                 return -EINVAL;
2902                         }
2903
2904                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2905                                                           offset, offset - alignment);
2906                 }
2907         }
2908
2909         plane_state->main.offset = offset;
2910         plane_state->main.x = x;
2911         plane_state->main.y = y;
2912
2913         return 0;
2914 }
2915
2916 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2917 {
2918         const struct drm_framebuffer *fb = plane_state->base.fb;
2919         unsigned int rotation = plane_state->base.rotation;
2920         int max_width = skl_max_plane_width(fb, 1, rotation);
2921         int max_height = 4096;
2922         int x = plane_state->base.src.x1 >> 17;
2923         int y = plane_state->base.src.y1 >> 17;
2924         int w = drm_rect_width(&plane_state->base.src) >> 17;
2925         int h = drm_rect_height(&plane_state->base.src) >> 17;
2926         u32 offset;
2927
2928         intel_add_fb_offsets(&x, &y, plane_state, 1);
2929         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
2930
2931         /* FIXME not quite sure how/if these apply to the chroma plane */
2932         if (w > max_width || h > max_height) {
2933                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
2934                               w, h, max_width, max_height);
2935                 return -EINVAL;
2936         }
2937
2938         plane_state->aux.offset = offset;
2939         plane_state->aux.x = x;
2940         plane_state->aux.y = y;
2941
2942         return 0;
2943 }
2944
2945 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2946 {
2947         const struct drm_framebuffer *fb = plane_state->base.fb;
2948         unsigned int rotation = plane_state->base.rotation;
2949         int ret;
2950
2951         if (!plane_state->base.visible)
2952                 return 0;
2953
2954         /* Rotate src coordinates to match rotated GTT view */
2955         if (drm_rotation_90_or_270(rotation))
2956                 drm_rect_rotate(&plane_state->base.src,
2957                                 fb->width << 16, fb->height << 16,
2958                                 DRM_MODE_ROTATE_270);
2959
2960         /*
2961          * Handle the AUX surface first since
2962          * the main surface setup depends on it.
2963          */
2964         if (fb->format->format == DRM_FORMAT_NV12) {
2965                 ret = skl_check_nv12_aux_surface(plane_state);
2966                 if (ret)
2967                         return ret;
2968         } else {
2969                 plane_state->aux.offset = ~0xfff;
2970                 plane_state->aux.x = 0;
2971                 plane_state->aux.y = 0;
2972         }
2973
2974         ret = skl_check_main_surface(plane_state);
2975         if (ret)
2976                 return ret;
2977
2978         return 0;
2979 }
2980
2981 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
2982                           const struct intel_plane_state *plane_state)
2983 {
2984         struct drm_i915_private *dev_priv =
2985                 to_i915(plane_state->base.plane->dev);
2986         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
2987         const struct drm_framebuffer *fb = plane_state->base.fb;
2988         unsigned int rotation = plane_state->base.rotation;
2989         u32 dspcntr;
2990
2991         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
2992
2993         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
2994             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
2995                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2996
2997         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
2998                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2999
3000         if (INTEL_GEN(dev_priv) < 4)
3001                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3002
3003         switch (fb->format->format) {
3004         case DRM_FORMAT_C8:
3005                 dspcntr |= DISPPLANE_8BPP;
3006                 break;
3007         case DRM_FORMAT_XRGB1555:
3008                 dspcntr |= DISPPLANE_BGRX555;
3009                 break;
3010         case DRM_FORMAT_RGB565:
3011                 dspcntr |= DISPPLANE_BGRX565;
3012                 break;
3013         case DRM_FORMAT_XRGB8888:
3014                 dspcntr |= DISPPLANE_BGRX888;
3015                 break;
3016         case DRM_FORMAT_XBGR8888:
3017                 dspcntr |= DISPPLANE_RGBX888;
3018                 break;
3019         case DRM_FORMAT_XRGB2101010:
3020                 dspcntr |= DISPPLANE_BGRX101010;
3021                 break;
3022         case DRM_FORMAT_XBGR2101010:
3023                 dspcntr |= DISPPLANE_RGBX101010;
3024                 break;
3025         default:
3026                 MISSING_CASE(fb->format->format);
3027                 return 0;
3028         }
3029
3030         if (INTEL_GEN(dev_priv) >= 4 &&
3031             fb->modifier == I915_FORMAT_MOD_X_TILED)
3032                 dspcntr |= DISPPLANE_TILED;
3033
3034         if (rotation & DRM_MODE_ROTATE_180)
3035                 dspcntr |= DISPPLANE_ROTATE_180;
3036
3037         if (rotation & DRM_MODE_REFLECT_X)
3038                 dspcntr |= DISPPLANE_MIRROR;
3039
3040         return dspcntr;
3041 }
3042
3043 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3044 {
3045         struct drm_i915_private *dev_priv =
3046                 to_i915(plane_state->base.plane->dev);
3047         int src_x = plane_state->base.src.x1 >> 16;
3048         int src_y = plane_state->base.src.y1 >> 16;
3049         u32 offset;
3050
3051         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3052
3053         if (INTEL_GEN(dev_priv) >= 4)
3054                 offset = intel_compute_tile_offset(&src_x, &src_y,
3055                                                    plane_state, 0);
3056         else
3057                 offset = 0;
3058
3059         /* HSW/BDW do this automagically in hardware */
3060         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3061                 unsigned int rotation = plane_state->base.rotation;
3062                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3063                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3064
3065                 if (rotation & DRM_MODE_ROTATE_180) {
3066                         src_x += src_w - 1;
3067                         src_y += src_h - 1;
3068                 } else if (rotation & DRM_MODE_REFLECT_X) {
3069                         src_x += src_w - 1;
3070                 }
3071         }
3072
3073         plane_state->main.offset = offset;
3074         plane_state->main.x = src_x;
3075         plane_state->main.y = src_y;
3076
3077         return 0;
3078 }
3079
3080 static void i9xx_update_primary_plane(struct intel_plane *primary,
3081                                       const struct intel_crtc_state *crtc_state,
3082                                       const struct intel_plane_state *plane_state)
3083 {
3084         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3085         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3086         const struct drm_framebuffer *fb = plane_state->base.fb;
3087         enum plane plane = primary->plane;
3088         u32 linear_offset;
3089         u32 dspcntr = plane_state->ctl;
3090         i915_reg_t reg = DSPCNTR(plane);
3091         int x = plane_state->main.x;
3092         int y = plane_state->main.y;
3093         unsigned long irqflags;
3094
3095         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3096
3097         if (INTEL_GEN(dev_priv) >= 4)
3098                 crtc->dspaddr_offset = plane_state->main.offset;
3099         else
3100                 crtc->dspaddr_offset = linear_offset;
3101
3102         crtc->adjusted_x = x;
3103         crtc->adjusted_y = y;
3104
3105         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3106
3107         if (INTEL_GEN(dev_priv) < 4) {
3108                 /* pipesrc and dspsize control the size that is scaled from,
3109                  * which should always be the user's requested size.
3110                  */
3111                 I915_WRITE_FW(DSPSIZE(plane),
3112                               ((crtc_state->pipe_src_h - 1) << 16) |
3113                               (crtc_state->pipe_src_w - 1));
3114                 I915_WRITE_FW(DSPPOS(plane), 0);
3115         } else if (IS_CHERRYVIEW(dev_priv) && plane == PLANE_B) {
3116                 I915_WRITE_FW(PRIMSIZE(plane),
3117                               ((crtc_state->pipe_src_h - 1) << 16) |
3118                               (crtc_state->pipe_src_w - 1));
3119                 I915_WRITE_FW(PRIMPOS(plane), 0);
3120                 I915_WRITE_FW(PRIMCNSTALPHA(plane), 0);
3121         }
3122
3123         I915_WRITE_FW(reg, dspcntr);
3124
3125         I915_WRITE_FW(DSPSTRIDE(plane), fb->pitches[0]);
3126         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3127                 I915_WRITE_FW(DSPSURF(plane),
3128                               intel_plane_ggtt_offset(plane_state) +
3129                               crtc->dspaddr_offset);
3130                 I915_WRITE_FW(DSPOFFSET(plane), (y << 16) | x);
3131         } else if (INTEL_GEN(dev_priv) >= 4) {
3132                 I915_WRITE_FW(DSPSURF(plane),
3133                               intel_plane_ggtt_offset(plane_state) +
3134                               crtc->dspaddr_offset);
3135                 I915_WRITE_FW(DSPTILEOFF(plane), (y << 16) | x);
3136                 I915_WRITE_FW(DSPLINOFF(plane), linear_offset);
3137         } else {
3138                 I915_WRITE_FW(DSPADDR(plane),
3139                               intel_plane_ggtt_offset(plane_state) +
3140                               crtc->dspaddr_offset);
3141         }
3142         POSTING_READ_FW(reg);
3143
3144         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3145 }
3146
3147 static void i9xx_disable_primary_plane(struct intel_plane *primary,
3148                                        struct intel_crtc *crtc)
3149 {
3150         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3151         enum plane plane = primary->plane;
3152         unsigned long irqflags;
3153
3154         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3155
3156         I915_WRITE_FW(DSPCNTR(plane), 0);
3157         if (INTEL_INFO(dev_priv)->gen >= 4)
3158                 I915_WRITE_FW(DSPSURF(plane), 0);
3159         else
3160                 I915_WRITE_FW(DSPADDR(plane), 0);
3161         POSTING_READ_FW(DSPCNTR(plane));
3162
3163         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3164 }
3165
3166 static u32
3167 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3168 {
3169         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3170                 return 64;
3171         else
3172                 return intel_tile_width_bytes(fb, plane);
3173 }
3174
3175 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3176 {
3177         struct drm_device *dev = intel_crtc->base.dev;
3178         struct drm_i915_private *dev_priv = to_i915(dev);
3179
3180         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3181         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3182         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3183 }
3184
3185 /*
3186  * This function detaches (aka. unbinds) unused scalers in hardware
3187  */
3188 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3189 {
3190         struct intel_crtc_scaler_state *scaler_state;
3191         int i;
3192
3193         scaler_state = &intel_crtc->config->scaler_state;
3194
3195         /* loop through and disable scalers that aren't in use */
3196         for (i = 0; i < intel_crtc->num_scalers; i++) {
3197                 if (!scaler_state->scalers[i].in_use)
3198                         skl_detach_scaler(intel_crtc, i);
3199         }
3200 }
3201
3202 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3203                      unsigned int rotation)
3204 {
3205         u32 stride;
3206
3207         if (plane >= fb->format->num_planes)
3208                 return 0;
3209
3210         stride = intel_fb_pitch(fb, plane, rotation);
3211
3212         /*
3213          * The stride is either expressed as a multiple of 64 bytes chunks for
3214          * linear buffers or in number of tiles for tiled buffers.
3215          */
3216         if (drm_rotation_90_or_270(rotation))
3217                 stride /= intel_tile_height(fb, plane);
3218         else
3219                 stride /= intel_fb_stride_alignment(fb, plane);
3220
3221         return stride;
3222 }
3223
3224 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3225 {
3226         switch (pixel_format) {
3227         case DRM_FORMAT_C8:
3228                 return PLANE_CTL_FORMAT_INDEXED;
3229         case DRM_FORMAT_RGB565:
3230                 return PLANE_CTL_FORMAT_RGB_565;
3231         case DRM_FORMAT_XBGR8888:
3232                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3233         case DRM_FORMAT_XRGB8888:
3234                 return PLANE_CTL_FORMAT_XRGB_8888;
3235         /*
3236          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3237          * to be already pre-multiplied. We need to add a knob (or a different
3238          * DRM_FORMAT) for user-space to configure that.
3239          */
3240         case DRM_FORMAT_ABGR8888:
3241                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3242                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3243         case DRM_FORMAT_ARGB8888:
3244                 return PLANE_CTL_FORMAT_XRGB_8888 |
3245                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3246         case DRM_FORMAT_XRGB2101010:
3247                 return PLANE_CTL_FORMAT_XRGB_2101010;
3248         case DRM_FORMAT_XBGR2101010:
3249                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3250         case DRM_FORMAT_YUYV:
3251                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3252         case DRM_FORMAT_YVYU:
3253                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3254         case DRM_FORMAT_UYVY:
3255                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3256         case DRM_FORMAT_VYUY:
3257                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3258         default:
3259                 MISSING_CASE(pixel_format);
3260         }
3261
3262         return 0;
3263 }
3264
3265 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3266 {
3267         switch (fb_modifier) {
3268         case DRM_FORMAT_MOD_LINEAR:
3269                 break;
3270         case I915_FORMAT_MOD_X_TILED:
3271                 return PLANE_CTL_TILED_X;
3272         case I915_FORMAT_MOD_Y_TILED:
3273                 return PLANE_CTL_TILED_Y;
3274         case I915_FORMAT_MOD_Yf_TILED:
3275                 return PLANE_CTL_TILED_YF;
3276         default:
3277                 MISSING_CASE(fb_modifier);
3278         }
3279
3280         return 0;
3281 }
3282
3283 static u32 skl_plane_ctl_rotation(unsigned int rotation)
3284 {
3285         switch (rotation) {
3286         case DRM_MODE_ROTATE_0:
3287                 break;
3288         /*
3289          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3290          * while i915 HW rotation is clockwise, thats why this swapping.
3291          */
3292         case DRM_MODE_ROTATE_90:
3293                 return PLANE_CTL_ROTATE_270;
3294         case DRM_MODE_ROTATE_180:
3295                 return PLANE_CTL_ROTATE_180;
3296         case DRM_MODE_ROTATE_270:
3297                 return PLANE_CTL_ROTATE_90;
3298         default:
3299                 MISSING_CASE(rotation);
3300         }
3301
3302         return 0;
3303 }
3304
3305 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3306                   const struct intel_plane_state *plane_state)
3307 {
3308         struct drm_i915_private *dev_priv =
3309                 to_i915(plane_state->base.plane->dev);
3310         const struct drm_framebuffer *fb = plane_state->base.fb;
3311         unsigned int rotation = plane_state->base.rotation;
3312         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3313         u32 plane_ctl;
3314
3315         plane_ctl = PLANE_CTL_ENABLE;
3316
3317         if (!IS_GEMINILAKE(dev_priv)) {
3318                 plane_ctl |=
3319                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3320                         PLANE_CTL_PIPE_CSC_ENABLE |
3321                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3322         }
3323
3324         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3325         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3326         plane_ctl |= skl_plane_ctl_rotation(rotation);
3327
3328         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3329                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3330         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3331                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3332
3333         return plane_ctl;
3334 }
3335
3336 static void skylake_update_primary_plane(struct intel_plane *plane,
3337                                          const struct intel_crtc_state *crtc_state,
3338                                          const struct intel_plane_state *plane_state)
3339 {
3340         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3341         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3342         const struct drm_framebuffer *fb = plane_state->base.fb;
3343         enum plane_id plane_id = plane->id;
3344         enum pipe pipe = plane->pipe;
3345         u32 plane_ctl = plane_state->ctl;
3346         unsigned int rotation = plane_state->base.rotation;
3347         u32 stride = skl_plane_stride(fb, 0, rotation);
3348         u32 surf_addr = plane_state->main.offset;
3349         int scaler_id = plane_state->scaler_id;
3350         int src_x = plane_state->main.x;
3351         int src_y = plane_state->main.y;
3352         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3353         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3354         int dst_x = plane_state->base.dst.x1;
3355         int dst_y = plane_state->base.dst.y1;
3356         int dst_w = drm_rect_width(&plane_state->base.dst);
3357         int dst_h = drm_rect_height(&plane_state->base.dst);
3358         unsigned long irqflags;
3359
3360         /* Sizes are 0 based */
3361         src_w--;
3362         src_h--;
3363         dst_w--;
3364         dst_h--;
3365
3366         crtc->dspaddr_offset = surf_addr;
3367
3368         crtc->adjusted_x = src_x;
3369         crtc->adjusted_y = src_y;
3370
3371         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3372
3373         if (IS_GEMINILAKE(dev_priv)) {
3374                 I915_WRITE_FW(PLANE_COLOR_CTL(pipe, plane_id),
3375                               PLANE_COLOR_PIPE_GAMMA_ENABLE |
3376                               PLANE_COLOR_PIPE_CSC_ENABLE |
3377                               PLANE_COLOR_PLANE_GAMMA_DISABLE);
3378         }
3379
3380         I915_WRITE_FW(PLANE_CTL(pipe, plane_id), plane_ctl);
3381         I915_WRITE_FW(PLANE_OFFSET(pipe, plane_id), (src_y << 16) | src_x);
3382         I915_WRITE_FW(PLANE_STRIDE(pipe, plane_id), stride);
3383         I915_WRITE_FW(PLANE_SIZE(pipe, plane_id), (src_h << 16) | src_w);
3384
3385         if (scaler_id >= 0) {
3386                 uint32_t ps_ctrl = 0;
3387
3388                 WARN_ON(!dst_w || !dst_h);
3389                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(plane_id) |
3390                         crtc_state->scaler_state.scalers[scaler_id].mode;
3391                 I915_WRITE_FW(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3392                 I915_WRITE_FW(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3393                 I915_WRITE_FW(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3394                 I915_WRITE_FW(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3395                 I915_WRITE_FW(PLANE_POS(pipe, plane_id), 0);
3396         } else {
3397                 I915_WRITE_FW(PLANE_POS(pipe, plane_id), (dst_y << 16) | dst_x);
3398         }
3399
3400         I915_WRITE_FW(PLANE_SURF(pipe, plane_id),
3401                       intel_plane_ggtt_offset(plane_state) + surf_addr);
3402
3403         POSTING_READ_FW(PLANE_SURF(pipe, plane_id));
3404
3405         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3406 }
3407
3408 static void skylake_disable_primary_plane(struct intel_plane *primary,
3409                                           struct intel_crtc *crtc)
3410 {
3411         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3412         enum plane_id plane_id = primary->id;
3413         enum pipe pipe = primary->pipe;
3414         unsigned long irqflags;
3415
3416         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3417
3418         I915_WRITE_FW(PLANE_CTL(pipe, plane_id), 0);
3419         I915_WRITE_FW(PLANE_SURF(pipe, plane_id), 0);
3420         POSTING_READ_FW(PLANE_SURF(pipe, plane_id));
3421
3422         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3423 }
3424
3425 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3426 {
3427         struct intel_crtc *crtc;
3428
3429         for_each_intel_crtc(&dev_priv->drm, crtc)
3430                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3431 }
3432
3433 static void intel_update_primary_planes(struct drm_device *dev)
3434 {
3435         struct drm_crtc *crtc;
3436
3437         for_each_crtc(dev, crtc) {
3438                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3439                 struct intel_plane_state *plane_state =
3440                         to_intel_plane_state(plane->base.state);
3441
3442                 if (plane_state->base.visible) {
3443                         trace_intel_update_plane(&plane->base,
3444                                                  to_intel_crtc(crtc));
3445
3446                         plane->update_plane(plane,
3447                                             to_intel_crtc_state(crtc->state),
3448                                             plane_state);
3449                 }
3450         }
3451 }
3452
3453 static int
3454 __intel_display_resume(struct drm_device *dev,
3455                        struct drm_atomic_state *state,
3456                        struct drm_modeset_acquire_ctx *ctx)
3457 {
3458         struct drm_crtc_state *crtc_state;
3459         struct drm_crtc *crtc;
3460         int i, ret;
3461
3462         intel_modeset_setup_hw_state(dev, ctx);
3463         i915_redisable_vga(to_i915(dev));
3464
3465         if (!state)
3466                 return 0;
3467
3468         /*
3469          * We've duplicated the state, pointers to the old state are invalid.
3470          *
3471          * Don't attempt to use the old state until we commit the duplicated state.
3472          */
3473         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3474                 /*
3475                  * Force recalculation even if we restore
3476                  * current state. With fast modeset this may not result
3477                  * in a modeset when the state is compatible.
3478                  */
3479                 crtc_state->mode_changed = true;
3480         }
3481
3482         /* ignore any reset values/BIOS leftovers in the WM registers */
3483         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3484                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3485
3486         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3487
3488         WARN_ON(ret == -EDEADLK);
3489         return ret;
3490 }
3491
3492 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3493 {
3494         return intel_has_gpu_reset(dev_priv) &&
3495                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3496 }
3497
3498 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3499 {
3500         struct drm_device *dev = &dev_priv->drm;
3501         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3502         struct drm_atomic_state *state;
3503         int ret;
3504
3505         /*
3506          * Need mode_config.mutex so that we don't
3507          * trample ongoing ->detect() and whatnot.
3508          */
3509         mutex_lock(&dev->mode_config.mutex);
3510         drm_modeset_acquire_init(ctx, 0);
3511         while (1) {
3512                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3513                 if (ret != -EDEADLK)
3514                         break;
3515
3516                 drm_modeset_backoff(ctx);
3517         }
3518
3519         /* reset doesn't touch the display, but flips might get nuked anyway, */
3520         if (!i915.force_reset_modeset_test &&
3521             !gpu_reset_clobbers_display(dev_priv))
3522                 return;
3523
3524         /*
3525          * Disabling the crtcs gracefully seems nicer. Also the
3526          * g33 docs say we should at least disable all the planes.
3527          */
3528         state = drm_atomic_helper_duplicate_state(dev, ctx);
3529         if (IS_ERR(state)) {
3530                 ret = PTR_ERR(state);
3531                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3532                 return;
3533         }
3534
3535         ret = drm_atomic_helper_disable_all(dev, ctx);
3536         if (ret) {
3537                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3538                 drm_atomic_state_put(state);
3539                 return;
3540         }
3541
3542         dev_priv->modeset_restore_state = state;
3543         state->acquire_ctx = ctx;
3544 }
3545
3546 void intel_finish_reset(struct drm_i915_private *dev_priv)
3547 {
3548         struct drm_device *dev = &dev_priv->drm;
3549         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3550         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3551         int ret;
3552
3553         /*
3554          * Flips in the rings will be nuked by the reset,
3555          * so complete all pending flips so that user space
3556          * will get its events and not get stuck.
3557          */
3558         intel_complete_page_flips(dev_priv);
3559
3560         dev_priv->modeset_restore_state = NULL;
3561
3562         /* reset doesn't touch the display */
3563         if (!gpu_reset_clobbers_display(dev_priv)) {
3564                 if (!state) {
3565                         /*
3566                          * Flips in the rings have been nuked by the reset,
3567                          * so update the base address of all primary
3568                          * planes to the the last fb to make sure we're
3569                          * showing the correct fb after a reset.
3570                          *
3571                          * FIXME: Atomic will make this obsolete since we won't schedule
3572                          * CS-based flips (which might get lost in gpu resets) any more.
3573                          */
3574                         intel_update_primary_planes(dev);
3575                 } else {
3576                         ret = __intel_display_resume(dev, state, ctx);
3577                         if (ret)
3578                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3579                 }
3580         } else {
3581                 /*
3582                  * The display has been reset as well,
3583                  * so need a full re-initialization.
3584                  */
3585                 intel_runtime_pm_disable_interrupts(dev_priv);
3586                 intel_runtime_pm_enable_interrupts(dev_priv);
3587
3588                 intel_pps_unlock_regs_wa(dev_priv);
3589                 intel_modeset_init_hw(dev);
3590
3591                 spin_lock_irq(&dev_priv->irq_lock);
3592                 if (dev_priv->display.hpd_irq_setup)
3593                         dev_priv->display.hpd_irq_setup(dev_priv);
3594                 spin_unlock_irq(&dev_priv->irq_lock);
3595
3596                 ret = __intel_display_resume(dev, state, ctx);
3597                 if (ret)
3598                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3599
3600                 intel_hpd_init(dev_priv);
3601         }
3602
3603         if (state)
3604                 drm_atomic_state_put(state);
3605         drm_modeset_drop_locks(ctx);
3606         drm_modeset_acquire_fini(ctx);
3607         mutex_unlock(&dev->mode_config.mutex);
3608 }
3609
3610 static bool abort_flip_on_reset(struct intel_crtc *crtc)
3611 {
3612         struct i915_gpu_error *error = &to_i915(crtc->base.dev)->gpu_error;
3613
3614         if (i915_reset_backoff(error))
3615                 return true;
3616
3617         if (crtc->reset_count != i915_reset_count(error))
3618                 return true;
3619
3620         return false;
3621 }
3622
3623 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3624 {
3625         struct drm_device *dev = crtc->dev;
3626         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3627         bool pending;
3628
3629         if (abort_flip_on_reset(intel_crtc))
3630                 return false;
3631
3632         spin_lock_irq(&dev->event_lock);
3633         pending = to_intel_crtc(crtc)->flip_work != NULL;
3634         spin_unlock_irq(&dev->event_lock);
3635
3636         return pending;
3637 }
3638
3639 static void intel_update_pipe_config(struct intel_crtc *crtc,
3640                                      struct intel_crtc_state *old_crtc_state)
3641 {
3642         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3643         struct intel_crtc_state *pipe_config =
3644                 to_intel_crtc_state(crtc->base.state);
3645
3646         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3647         crtc->base.mode = crtc->base.state->mode;
3648
3649         /*
3650          * Update pipe size and adjust fitter if needed: the reason for this is
3651          * that in compute_mode_changes we check the native mode (not the pfit
3652          * mode) to see if we can flip rather than do a full mode set. In the
3653          * fastboot case, we'll flip, but if we don't update the pipesrc and
3654          * pfit state, we'll end up with a big fb scanned out into the wrong
3655          * sized surface.
3656          */
3657
3658         I915_WRITE(PIPESRC(crtc->pipe),
3659                    ((pipe_config->pipe_src_w - 1) << 16) |
3660                    (pipe_config->pipe_src_h - 1));
3661
3662         /* on skylake this is done by detaching scalers */
3663         if (INTEL_GEN(dev_priv) >= 9) {
3664                 skl_detach_scalers(crtc);
3665
3666                 if (pipe_config->pch_pfit.enabled)
3667                         skylake_pfit_enable(crtc);
3668         } else if (HAS_PCH_SPLIT(dev_priv)) {
3669                 if (pipe_config->pch_pfit.enabled)
3670                         ironlake_pfit_enable(crtc);
3671                 else if (old_crtc_state->pch_pfit.enabled)
3672                         ironlake_pfit_disable(crtc, true);
3673         }
3674 }
3675
3676 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3677 {
3678         struct drm_device *dev = crtc->base.dev;
3679         struct drm_i915_private *dev_priv = to_i915(dev);
3680         int pipe = crtc->pipe;
3681         i915_reg_t reg;
3682         u32 temp;
3683
3684         /* enable normal train */
3685         reg = FDI_TX_CTL(pipe);
3686         temp = I915_READ(reg);
3687         if (IS_IVYBRIDGE(dev_priv)) {
3688                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3689                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3690         } else {
3691                 temp &= ~FDI_LINK_TRAIN_NONE;
3692                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3693         }
3694         I915_WRITE(reg, temp);
3695
3696         reg = FDI_RX_CTL(pipe);
3697         temp = I915_READ(reg);
3698         if (HAS_PCH_CPT(dev_priv)) {
3699                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3700                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3701         } else {
3702                 temp &= ~FDI_LINK_TRAIN_NONE;
3703                 temp |= FDI_LINK_TRAIN_NONE;
3704         }
3705         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3706
3707         /* wait one idle pattern time */
3708         POSTING_READ(reg);
3709         udelay(1000);
3710
3711         /* IVB wants error correction enabled */
3712         if (IS_IVYBRIDGE(dev_priv))
3713                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3714                            FDI_FE_ERRC_ENABLE);
3715 }
3716
3717 /* The FDI link training functions for ILK/Ibexpeak. */
3718 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3719                                     const struct intel_crtc_state *crtc_state)
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, tries;
3726
3727         /* FDI needs bits from pipe first */
3728         assert_pipe_enabled(dev_priv, pipe);
3729
3730         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3731            for train result */
3732         reg = FDI_RX_IMR(pipe);
3733         temp = I915_READ(reg);
3734         temp &= ~FDI_RX_SYMBOL_LOCK;
3735         temp &= ~FDI_RX_BIT_LOCK;
3736         I915_WRITE(reg, temp);
3737         I915_READ(reg);
3738         udelay(150);
3739
3740         /* enable CPU FDI TX and PCH FDI RX */
3741         reg = FDI_TX_CTL(pipe);
3742         temp = I915_READ(reg);
3743         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3744         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3745         temp &= ~FDI_LINK_TRAIN_NONE;
3746         temp |= FDI_LINK_TRAIN_PATTERN_1;
3747         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3748
3749         reg = FDI_RX_CTL(pipe);
3750         temp = I915_READ(reg);
3751         temp &= ~FDI_LINK_TRAIN_NONE;
3752         temp |= FDI_LINK_TRAIN_PATTERN_1;
3753         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3754
3755         POSTING_READ(reg);
3756         udelay(150);
3757
3758         /* Ironlake workaround, enable clock pointer after FDI enable*/
3759         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3760         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3761                    FDI_RX_PHASE_SYNC_POINTER_EN);
3762
3763         reg = FDI_RX_IIR(pipe);
3764         for (tries = 0; tries < 5; tries++) {
3765                 temp = I915_READ(reg);
3766                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3767
3768                 if ((temp & FDI_RX_BIT_LOCK)) {
3769                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3770                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3771                         break;
3772                 }
3773         }
3774         if (tries == 5)
3775                 DRM_ERROR("FDI train 1 fail!\n");
3776
3777         /* Train 2 */
3778         reg = FDI_TX_CTL(pipe);
3779         temp = I915_READ(reg);
3780         temp &= ~FDI_LINK_TRAIN_NONE;
3781         temp |= FDI_LINK_TRAIN_PATTERN_2;
3782         I915_WRITE(reg, temp);
3783
3784         reg = FDI_RX_CTL(pipe);
3785         temp = I915_READ(reg);
3786         temp &= ~FDI_LINK_TRAIN_NONE;
3787         temp |= FDI_LINK_TRAIN_PATTERN_2;
3788         I915_WRITE(reg, temp);
3789
3790         POSTING_READ(reg);
3791         udelay(150);
3792
3793         reg = FDI_RX_IIR(pipe);
3794         for (tries = 0; tries < 5; tries++) {
3795                 temp = I915_READ(reg);
3796                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3797
3798                 if (temp & FDI_RX_SYMBOL_LOCK) {
3799                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3800                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3801                         break;
3802                 }
3803         }
3804         if (tries == 5)
3805                 DRM_ERROR("FDI train 2 fail!\n");
3806
3807         DRM_DEBUG_KMS("FDI train done\n");
3808
3809 }
3810
3811 static const int snb_b_fdi_train_param[] = {
3812         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3813         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3814         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3815         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3816 };
3817
3818 /* The FDI link training functions for SNB/Cougarpoint. */
3819 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3820                                 const struct intel_crtc_state *crtc_state)
3821 {
3822         struct drm_device *dev = crtc->base.dev;
3823         struct drm_i915_private *dev_priv = to_i915(dev);
3824         int pipe = crtc->pipe;
3825         i915_reg_t reg;
3826         u32 temp, i, retry;
3827
3828         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3829            for train result */
3830         reg = FDI_RX_IMR(pipe);
3831         temp = I915_READ(reg);
3832         temp &= ~FDI_RX_SYMBOL_LOCK;
3833         temp &= ~FDI_RX_BIT_LOCK;
3834         I915_WRITE(reg, temp);
3835
3836         POSTING_READ(reg);
3837         udelay(150);
3838
3839         /* enable CPU FDI TX and PCH FDI RX */
3840         reg = FDI_TX_CTL(pipe);
3841         temp = I915_READ(reg);
3842         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3843         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3844         temp &= ~FDI_LINK_TRAIN_NONE;
3845         temp |= FDI_LINK_TRAIN_PATTERN_1;
3846         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3847         /* SNB-B */
3848         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3849         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3850
3851         I915_WRITE(FDI_RX_MISC(pipe),
3852                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3853
3854         reg = FDI_RX_CTL(pipe);
3855         temp = I915_READ(reg);
3856         if (HAS_PCH_CPT(dev_priv)) {
3857                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3858                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3859         } else {
3860                 temp &= ~FDI_LINK_TRAIN_NONE;
3861                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3862         }
3863         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3864
3865         POSTING_READ(reg);
3866         udelay(150);
3867
3868         for (i = 0; i < 4; i++) {
3869                 reg = FDI_TX_CTL(pipe);
3870                 temp = I915_READ(reg);
3871                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3872                 temp |= snb_b_fdi_train_param[i];
3873                 I915_WRITE(reg, temp);
3874
3875                 POSTING_READ(reg);
3876                 udelay(500);
3877
3878                 for (retry = 0; retry < 5; retry++) {
3879                         reg = FDI_RX_IIR(pipe);
3880                         temp = I915_READ(reg);
3881                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3882                         if (temp & FDI_RX_BIT_LOCK) {
3883                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3884                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3885                                 break;
3886                         }
3887                         udelay(50);
3888                 }
3889                 if (retry < 5)
3890                         break;
3891         }
3892         if (i == 4)
3893                 DRM_ERROR("FDI train 1 fail!\n");
3894
3895         /* Train 2 */
3896         reg = FDI_TX_CTL(pipe);
3897         temp = I915_READ(reg);
3898         temp &= ~FDI_LINK_TRAIN_NONE;
3899         temp |= FDI_LINK_TRAIN_PATTERN_2;
3900         if (IS_GEN6(dev_priv)) {
3901                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3902                 /* SNB-B */
3903                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3904         }
3905         I915_WRITE(reg, temp);
3906
3907         reg = FDI_RX_CTL(pipe);
3908         temp = I915_READ(reg);
3909         if (HAS_PCH_CPT(dev_priv)) {
3910                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3911                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3912         } else {
3913                 temp &= ~FDI_LINK_TRAIN_NONE;
3914                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3915         }
3916         I915_WRITE(reg, temp);
3917
3918         POSTING_READ(reg);
3919         udelay(150);
3920
3921         for (i = 0; i < 4; i++) {
3922                 reg = FDI_TX_CTL(pipe);
3923                 temp = I915_READ(reg);
3924                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3925                 temp |= snb_b_fdi_train_param[i];
3926                 I915_WRITE(reg, temp);
3927
3928                 POSTING_READ(reg);
3929                 udelay(500);
3930
3931                 for (retry = 0; retry < 5; retry++) {
3932                         reg = FDI_RX_IIR(pipe);
3933                         temp = I915_READ(reg);
3934                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3935                         if (temp & FDI_RX_SYMBOL_LOCK) {
3936                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3937                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3938                                 break;
3939                         }
3940                         udelay(50);
3941                 }
3942                 if (retry < 5)
3943                         break;
3944         }
3945         if (i == 4)
3946                 DRM_ERROR("FDI train 2 fail!\n");
3947
3948         DRM_DEBUG_KMS("FDI train done.\n");
3949 }
3950
3951 /* Manual link training for Ivy Bridge A0 parts */
3952 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
3953                                       const struct intel_crtc_state *crtc_state)
3954 {
3955         struct drm_device *dev = crtc->base.dev;
3956         struct drm_i915_private *dev_priv = to_i915(dev);
3957         int pipe = crtc->pipe;
3958         i915_reg_t reg;
3959         u32 temp, i, j;
3960
3961         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3962            for train result */
3963         reg = FDI_RX_IMR(pipe);
3964         temp = I915_READ(reg);
3965         temp &= ~FDI_RX_SYMBOL_LOCK;
3966         temp &= ~FDI_RX_BIT_LOCK;
3967         I915_WRITE(reg, temp);
3968
3969         POSTING_READ(reg);
3970         udelay(150);
3971
3972         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3973                       I915_READ(FDI_RX_IIR(pipe)));
3974
3975         /* Try each vswing and preemphasis setting twice before moving on */
3976         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3977                 /* disable first in case we need to retry */
3978                 reg = FDI_TX_CTL(pipe);
3979                 temp = I915_READ(reg);
3980                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3981                 temp &= ~FDI_TX_ENABLE;
3982                 I915_WRITE(reg, temp);
3983
3984                 reg = FDI_RX_CTL(pipe);
3985                 temp = I915_READ(reg);
3986                 temp &= ~FDI_LINK_TRAIN_AUTO;
3987                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3988                 temp &= ~FDI_RX_ENABLE;
3989                 I915_WRITE(reg, temp);
3990
3991                 /* enable CPU FDI TX and PCH FDI RX */
3992                 reg = FDI_TX_CTL(pipe);
3993                 temp = I915_READ(reg);
3994                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3995                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3996                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3997                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3998                 temp |= snb_b_fdi_train_param[j/2];
3999                 temp |= FDI_COMPOSITE_SYNC;
4000                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4001
4002                 I915_WRITE(FDI_RX_MISC(pipe),
4003                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4004
4005                 reg = FDI_RX_CTL(pipe);
4006                 temp = I915_READ(reg);
4007                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4008                 temp |= FDI_COMPOSITE_SYNC;
4009                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4010
4011                 POSTING_READ(reg);
4012                 udelay(1); /* should be 0.5us */
4013
4014                 for (i = 0; i < 4; i++) {
4015                         reg = FDI_RX_IIR(pipe);
4016                         temp = I915_READ(reg);
4017                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4018
4019                         if (temp & FDI_RX_BIT_LOCK ||
4020                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4021                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4022                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4023                                               i);
4024                                 break;
4025                         }
4026                         udelay(1); /* should be 0.5us */
4027                 }
4028                 if (i == 4) {
4029                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4030                         continue;
4031                 }
4032
4033                 /* Train 2 */
4034                 reg = FDI_TX_CTL(pipe);
4035                 temp = I915_READ(reg);
4036                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4037                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4038                 I915_WRITE(reg, temp);
4039
4040                 reg = FDI_RX_CTL(pipe);
4041                 temp = I915_READ(reg);
4042                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4043                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4044                 I915_WRITE(reg, temp);
4045
4046                 POSTING_READ(reg);
4047                 udelay(2); /* should be 1.5us */
4048
4049                 for (i = 0; i < 4; i++) {
4050                         reg = FDI_RX_IIR(pipe);
4051                         temp = I915_READ(reg);
4052                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4053
4054                         if (temp & FDI_RX_SYMBOL_LOCK ||
4055                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4056                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4057                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4058                                               i);
4059                                 goto train_done;
4060                         }
4061                         udelay(2); /* should be 1.5us */
4062                 }
4063                 if (i == 4)
4064                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4065         }
4066
4067 train_done:
4068         DRM_DEBUG_KMS("FDI train done.\n");
4069 }
4070
4071 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4072 {
4073         struct drm_device *dev = intel_crtc->base.dev;
4074         struct drm_i915_private *dev_priv = to_i915(dev);
4075         int pipe = intel_crtc->pipe;
4076         i915_reg_t reg;
4077         u32 temp;
4078
4079         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4080         reg = FDI_RX_CTL(pipe);
4081         temp = I915_READ(reg);
4082         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4083         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4084         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4085         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4086
4087         POSTING_READ(reg);
4088         udelay(200);
4089
4090         /* Switch from Rawclk to PCDclk */
4091         temp = I915_READ(reg);
4092         I915_WRITE(reg, temp | FDI_PCDCLK);
4093
4094         POSTING_READ(reg);
4095         udelay(200);
4096
4097         /* Enable CPU FDI TX PLL, always on for Ironlake */
4098         reg = FDI_TX_CTL(pipe);
4099         temp = I915_READ(reg);
4100         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4101                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4102
4103                 POSTING_READ(reg);
4104                 udelay(100);
4105         }
4106 }
4107
4108 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4109 {
4110         struct drm_device *dev = intel_crtc->base.dev;
4111         struct drm_i915_private *dev_priv = to_i915(dev);
4112         int pipe = intel_crtc->pipe;
4113         i915_reg_t reg;
4114         u32 temp;
4115
4116         /* Switch from PCDclk to Rawclk */
4117         reg = FDI_RX_CTL(pipe);
4118         temp = I915_READ(reg);
4119         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4120
4121         /* Disable CPU FDI TX PLL */
4122         reg = FDI_TX_CTL(pipe);
4123         temp = I915_READ(reg);
4124         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4125
4126         POSTING_READ(reg);
4127         udelay(100);
4128
4129         reg = FDI_RX_CTL(pipe);
4130         temp = I915_READ(reg);
4131         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4132
4133         /* Wait for the clocks to turn off. */
4134         POSTING_READ(reg);
4135         udelay(100);
4136 }
4137
4138 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4139 {
4140         struct drm_device *dev = crtc->dev;
4141         struct drm_i915_private *dev_priv = to_i915(dev);
4142         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4143         int pipe = intel_crtc->pipe;
4144         i915_reg_t reg;
4145         u32 temp;
4146
4147         /* disable CPU FDI tx and PCH FDI rx */
4148         reg = FDI_TX_CTL(pipe);
4149         temp = I915_READ(reg);
4150         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4151         POSTING_READ(reg);
4152
4153         reg = FDI_RX_CTL(pipe);
4154         temp = I915_READ(reg);
4155         temp &= ~(0x7 << 16);
4156         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4157         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4158
4159         POSTING_READ(reg);
4160         udelay(100);
4161
4162         /* Ironlake workaround, disable clock pointer after downing FDI */
4163         if (HAS_PCH_IBX(dev_priv))
4164                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4165
4166         /* still set train pattern 1 */
4167         reg = FDI_TX_CTL(pipe);
4168         temp = I915_READ(reg);
4169         temp &= ~FDI_LINK_TRAIN_NONE;
4170         temp |= FDI_LINK_TRAIN_PATTERN_1;
4171         I915_WRITE(reg, temp);
4172
4173         reg = FDI_RX_CTL(pipe);
4174         temp = I915_READ(reg);
4175         if (HAS_PCH_CPT(dev_priv)) {
4176                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4177                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4178         } else {
4179                 temp &= ~FDI_LINK_TRAIN_NONE;
4180                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4181         }
4182         /* BPC in FDI rx is consistent with that in PIPECONF */
4183         temp &= ~(0x07 << 16);
4184         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4185         I915_WRITE(reg, temp);
4186
4187         POSTING_READ(reg);
4188         udelay(100);
4189 }
4190
4191 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4192 {
4193         struct intel_crtc *crtc;
4194
4195         /* Note that we don't need to be called with mode_config.lock here
4196          * as our list of CRTC objects is static for the lifetime of the
4197          * device and so cannot disappear as we iterate. Similarly, we can
4198          * happily treat the predicates as racy, atomic checks as userspace
4199          * cannot claim and pin a new fb without at least acquring the
4200          * struct_mutex and so serialising with us.
4201          */
4202         for_each_intel_crtc(&dev_priv->drm, crtc) {
4203                 if (atomic_read(&crtc->unpin_work_count) == 0)
4204                         continue;
4205
4206                 if (crtc->flip_work)
4207                         intel_wait_for_vblank(dev_priv, crtc->pipe);
4208
4209                 return true;
4210         }
4211
4212         return false;
4213 }
4214
4215 static void page_flip_completed(struct intel_crtc *intel_crtc)
4216 {
4217         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4218         struct intel_flip_work *work = intel_crtc->flip_work;
4219
4220         intel_crtc->flip_work = NULL;
4221
4222         if (work->event)
4223                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4224
4225         drm_crtc_vblank_put(&intel_crtc->base);
4226
4227         wake_up_all(&dev_priv->pending_flip_queue);
4228         trace_i915_flip_complete(intel_crtc->plane,
4229                                  work->pending_flip_obj);
4230
4231         queue_work(dev_priv->wq, &work->unpin_work);
4232 }
4233
4234 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4235 {
4236         struct drm_device *dev = crtc->dev;
4237         struct drm_i915_private *dev_priv = to_i915(dev);
4238         long ret;
4239
4240         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4241
4242         ret = wait_event_interruptible_timeout(
4243                                         dev_priv->pending_flip_queue,
4244                                         !intel_crtc_has_pending_flip(crtc),
4245                                         60*HZ);
4246
4247         if (ret < 0)
4248                 return ret;
4249
4250         if (ret == 0) {
4251                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4252                 struct intel_flip_work *work;
4253
4254                 spin_lock_irq(&dev->event_lock);
4255                 work = intel_crtc->flip_work;
4256                 if (work && !is_mmio_work(work)) {
4257                         WARN_ONCE(1, "Removing stuck page flip\n");
4258                         page_flip_completed(intel_crtc);
4259                 }
4260                 spin_unlock_irq(&dev->event_lock);
4261         }
4262
4263         return 0;
4264 }
4265
4266 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4267 {
4268         u32 temp;
4269
4270         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4271
4272         mutex_lock(&dev_priv->sb_lock);
4273
4274         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4275         temp |= SBI_SSCCTL_DISABLE;
4276         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4277
4278         mutex_unlock(&dev_priv->sb_lock);
4279 }
4280
4281 /* Program iCLKIP clock to the desired frequency */
4282 static void lpt_program_iclkip(struct intel_crtc *crtc)
4283 {
4284         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4285         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4286         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4287         u32 temp;
4288
4289         lpt_disable_iclkip(dev_priv);
4290
4291         /* The iCLK virtual clock root frequency is in MHz,
4292          * but the adjusted_mode->crtc_clock in in KHz. To get the
4293          * divisors, it is necessary to divide one by another, so we
4294          * convert the virtual clock precision to KHz here for higher
4295          * precision.
4296          */
4297         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4298                 u32 iclk_virtual_root_freq = 172800 * 1000;
4299                 u32 iclk_pi_range = 64;
4300                 u32 desired_divisor;
4301
4302                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4303                                                     clock << auxdiv);
4304                 divsel = (desired_divisor / iclk_pi_range) - 2;
4305                 phaseinc = desired_divisor % iclk_pi_range;
4306
4307                 /*
4308                  * Near 20MHz is a corner case which is
4309                  * out of range for the 7-bit divisor
4310                  */
4311                 if (divsel <= 0x7f)
4312                         break;
4313         }
4314
4315         /* This should not happen with any sane values */
4316         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4317                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4318         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4319                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4320
4321         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4322                         clock,
4323                         auxdiv,
4324                         divsel,
4325                         phasedir,
4326                         phaseinc);
4327
4328         mutex_lock(&dev_priv->sb_lock);
4329
4330         /* Program SSCDIVINTPHASE6 */
4331         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4332         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4333         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4334         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4335         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4336         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4337         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4338         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4339
4340         /* Program SSCAUXDIV */
4341         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4342         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4343         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4344         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4345
4346         /* Enable modulator and associated divider */
4347         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4348         temp &= ~SBI_SSCCTL_DISABLE;
4349         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4350
4351         mutex_unlock(&dev_priv->sb_lock);
4352
4353         /* Wait for initialization time */
4354         udelay(24);
4355
4356         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4357 }
4358
4359 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4360 {
4361         u32 divsel, phaseinc, auxdiv;
4362         u32 iclk_virtual_root_freq = 172800 * 1000;
4363         u32 iclk_pi_range = 64;
4364         u32 desired_divisor;
4365         u32 temp;
4366
4367         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4368                 return 0;
4369
4370         mutex_lock(&dev_priv->sb_lock);
4371
4372         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4373         if (temp & SBI_SSCCTL_DISABLE) {
4374                 mutex_unlock(&dev_priv->sb_lock);
4375                 return 0;
4376         }
4377
4378         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4379         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4380                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4381         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4382                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4383
4384         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4385         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4386                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4387
4388         mutex_unlock(&dev_priv->sb_lock);
4389
4390         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4391
4392         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4393                                  desired_divisor << auxdiv);
4394 }
4395
4396 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4397                                                 enum pipe pch_transcoder)
4398 {
4399         struct drm_device *dev = crtc->base.dev;
4400         struct drm_i915_private *dev_priv = to_i915(dev);
4401         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4402
4403         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4404                    I915_READ(HTOTAL(cpu_transcoder)));
4405         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4406                    I915_READ(HBLANK(cpu_transcoder)));
4407         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4408                    I915_READ(HSYNC(cpu_transcoder)));
4409
4410         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4411                    I915_READ(VTOTAL(cpu_transcoder)));
4412         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4413                    I915_READ(VBLANK(cpu_transcoder)));
4414         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4415                    I915_READ(VSYNC(cpu_transcoder)));
4416         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4417                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4418 }
4419
4420 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4421 {
4422         struct drm_i915_private *dev_priv = to_i915(dev);
4423         uint32_t temp;
4424
4425         temp = I915_READ(SOUTH_CHICKEN1);
4426         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4427                 return;
4428
4429         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4430         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4431
4432         temp &= ~FDI_BC_BIFURCATION_SELECT;
4433         if (enable)
4434                 temp |= FDI_BC_BIFURCATION_SELECT;
4435
4436         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4437         I915_WRITE(SOUTH_CHICKEN1, temp);
4438         POSTING_READ(SOUTH_CHICKEN1);
4439 }
4440
4441 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4442 {
4443         struct drm_device *dev = intel_crtc->base.dev;
4444
4445         switch (intel_crtc->pipe) {
4446         case PIPE_A:
4447                 break;
4448         case PIPE_B:
4449                 if (intel_crtc->config->fdi_lanes > 2)
4450                         cpt_set_fdi_bc_bifurcation(dev, false);
4451                 else
4452                         cpt_set_fdi_bc_bifurcation(dev, true);
4453
4454                 break;
4455         case PIPE_C:
4456                 cpt_set_fdi_bc_bifurcation(dev, true);
4457
4458                 break;
4459         default:
4460                 BUG();
4461         }
4462 }
4463
4464 /* Return which DP Port should be selected for Transcoder DP control */
4465 static enum port
4466 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4467 {
4468         struct drm_device *dev = crtc->base.dev;
4469         struct intel_encoder *encoder;
4470
4471         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4472                 if (encoder->type == INTEL_OUTPUT_DP ||
4473                     encoder->type == INTEL_OUTPUT_EDP)
4474                         return enc_to_dig_port(&encoder->base)->port;
4475         }
4476
4477         return -1;
4478 }
4479
4480 /*
4481  * Enable PCH resources required for PCH ports:
4482  *   - PCH PLLs
4483  *   - FDI training & RX/TX
4484  *   - update transcoder timings
4485  *   - DP transcoding bits
4486  *   - transcoder
4487  */
4488 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4489 {
4490         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4491         struct drm_device *dev = crtc->base.dev;
4492         struct drm_i915_private *dev_priv = to_i915(dev);
4493         int pipe = crtc->pipe;
4494         u32 temp;
4495
4496         assert_pch_transcoder_disabled(dev_priv, pipe);
4497
4498         if (IS_IVYBRIDGE(dev_priv))
4499                 ivybridge_update_fdi_bc_bifurcation(crtc);
4500
4501         /* Write the TU size bits before fdi link training, so that error
4502          * detection works. */
4503         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4504                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4505
4506         /* For PCH output, training FDI link */
4507         dev_priv->display.fdi_link_train(crtc, crtc_state);
4508
4509         /* We need to program the right clock selection before writing the pixel
4510          * mutliplier into the DPLL. */
4511         if (HAS_PCH_CPT(dev_priv)) {
4512                 u32 sel;
4513
4514                 temp = I915_READ(PCH_DPLL_SEL);
4515                 temp |= TRANS_DPLL_ENABLE(pipe);
4516                 sel = TRANS_DPLLB_SEL(pipe);
4517                 if (crtc_state->shared_dpll ==
4518                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4519                         temp |= sel;
4520                 else
4521                         temp &= ~sel;
4522                 I915_WRITE(PCH_DPLL_SEL, temp);
4523         }
4524
4525         /* XXX: pch pll's can be enabled any time before we enable the PCH
4526          * transcoder, and we actually should do this to not upset any PCH
4527          * transcoder that already use the clock when we share it.
4528          *
4529          * Note that enable_shared_dpll tries to do the right thing, but
4530          * get_shared_dpll unconditionally resets the pll - we need that to have
4531          * the right LVDS enable sequence. */
4532         intel_enable_shared_dpll(crtc);
4533
4534         /* set transcoder timing, panel must allow it */
4535         assert_panel_unlocked(dev_priv, pipe);
4536         ironlake_pch_transcoder_set_timings(crtc, pipe);
4537
4538         intel_fdi_normal_train(crtc);
4539
4540         /* For PCH DP, enable TRANS_DP_CTL */
4541         if (HAS_PCH_CPT(dev_priv) &&
4542             intel_crtc_has_dp_encoder(crtc_state)) {
4543                 const struct drm_display_mode *adjusted_mode =
4544                         &crtc_state->base.adjusted_mode;
4545                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4546                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4547                 temp = I915_READ(reg);
4548                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4549                           TRANS_DP_SYNC_MASK |
4550                           TRANS_DP_BPC_MASK);
4551                 temp |= TRANS_DP_OUTPUT_ENABLE;
4552                 temp |= bpc << 9; /* same format but at 11:9 */
4553
4554                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4555                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4556                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4557                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4558
4559                 switch (intel_trans_dp_port_sel(crtc)) {
4560                 case PORT_B:
4561                         temp |= TRANS_DP_PORT_SEL_B;
4562                         break;
4563                 case PORT_C:
4564                         temp |= TRANS_DP_PORT_SEL_C;
4565                         break;
4566                 case PORT_D:
4567                         temp |= TRANS_DP_PORT_SEL_D;
4568                         break;
4569                 default:
4570                         BUG();
4571                 }
4572
4573                 I915_WRITE(reg, temp);
4574         }
4575
4576         ironlake_enable_pch_transcoder(dev_priv, pipe);
4577 }
4578
4579 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4580 {
4581         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4582         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4583         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4584
4585         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4586
4587         lpt_program_iclkip(crtc);
4588
4589         /* Set transcoder timing. */
4590         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4591
4592         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4593 }
4594
4595 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4596 {
4597         struct drm_i915_private *dev_priv = to_i915(dev);
4598         i915_reg_t dslreg = PIPEDSL(pipe);
4599         u32 temp;
4600
4601         temp = I915_READ(dslreg);
4602         udelay(500);
4603         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4604                 if (wait_for(I915_READ(dslreg) != temp, 5))
4605                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4606         }
4607 }
4608
4609 static int
4610 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4611                   unsigned int scaler_user, int *scaler_id,
4612                   int src_w, int src_h, int dst_w, int dst_h)
4613 {
4614         struct intel_crtc_scaler_state *scaler_state =
4615                 &crtc_state->scaler_state;
4616         struct intel_crtc *intel_crtc =
4617                 to_intel_crtc(crtc_state->base.crtc);
4618         int need_scaling;
4619
4620         /*
4621          * Src coordinates are already rotated by 270 degrees for
4622          * the 90/270 degree plane rotation cases (to match the
4623          * GTT mapping), hence no need to account for rotation here.
4624          */
4625         need_scaling = src_w != dst_w || src_h != dst_h;
4626
4627         /*
4628          * if plane is being disabled or scaler is no more required or force detach
4629          *  - free scaler binded to this plane/crtc
4630          *  - in order to do this, update crtc->scaler_usage
4631          *
4632          * Here scaler state in crtc_state is set free so that
4633          * scaler can be assigned to other user. Actual register
4634          * update to free the scaler is done in plane/panel-fit programming.
4635          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4636          */
4637         if (force_detach || !need_scaling) {
4638                 if (*scaler_id >= 0) {
4639                         scaler_state->scaler_users &= ~(1 << scaler_user);
4640                         scaler_state->scalers[*scaler_id].in_use = 0;
4641
4642                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4643                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4644                                 intel_crtc->pipe, scaler_user, *scaler_id,
4645                                 scaler_state->scaler_users);
4646                         *scaler_id = -1;
4647                 }
4648                 return 0;
4649         }
4650
4651         /* range checks */
4652         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4653                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4654
4655                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4656                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4657                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4658                         "size is out of scaler range\n",
4659                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4660                 return -EINVAL;
4661         }
4662
4663         /* mark this plane as a scaler user in crtc_state */
4664         scaler_state->scaler_users |= (1 << scaler_user);
4665         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4666                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4667                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4668                 scaler_state->scaler_users);
4669
4670         return 0;
4671 }
4672
4673 /**
4674  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4675  *
4676  * @state: crtc's scaler state
4677  *
4678  * Return
4679  *     0 - scaler_usage updated successfully
4680  *    error - requested scaling cannot be supported or other error condition
4681  */
4682 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4683 {
4684         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4685
4686         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4687                 &state->scaler_state.scaler_id,
4688                 state->pipe_src_w, state->pipe_src_h,
4689                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4690 }
4691
4692 /**
4693  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4694  *
4695  * @state: crtc's scaler state
4696  * @plane_state: atomic plane state to update
4697  *
4698  * Return
4699  *     0 - scaler_usage updated successfully
4700  *    error - requested scaling cannot be supported or other error condition
4701  */
4702 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4703                                    struct intel_plane_state *plane_state)
4704 {
4705
4706         struct intel_plane *intel_plane =
4707                 to_intel_plane(plane_state->base.plane);
4708         struct drm_framebuffer *fb = plane_state->base.fb;
4709         int ret;
4710
4711         bool force_detach = !fb || !plane_state->base.visible;
4712
4713         ret = skl_update_scaler(crtc_state, force_detach,
4714                                 drm_plane_index(&intel_plane->base),
4715                                 &plane_state->scaler_id,
4716                                 drm_rect_width(&plane_state->base.src) >> 16,
4717                                 drm_rect_height(&plane_state->base.src) >> 16,
4718                                 drm_rect_width(&plane_state->base.dst),
4719                                 drm_rect_height(&plane_state->base.dst));
4720
4721         if (ret || plane_state->scaler_id < 0)
4722                 return ret;
4723
4724         /* check colorkey */
4725         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4726                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4727                               intel_plane->base.base.id,
4728                               intel_plane->base.name);
4729                 return -EINVAL;
4730         }
4731
4732         /* Check src format */
4733         switch (fb->format->format) {
4734         case DRM_FORMAT_RGB565:
4735         case DRM_FORMAT_XBGR8888:
4736         case DRM_FORMAT_XRGB8888:
4737         case DRM_FORMAT_ABGR8888:
4738         case DRM_FORMAT_ARGB8888:
4739         case DRM_FORMAT_XRGB2101010:
4740         case DRM_FORMAT_XBGR2101010:
4741         case DRM_FORMAT_YUYV:
4742         case DRM_FORMAT_YVYU:
4743         case DRM_FORMAT_UYVY:
4744         case DRM_FORMAT_VYUY:
4745                 break;
4746         default:
4747                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4748                               intel_plane->base.base.id, intel_plane->base.name,
4749                               fb->base.id, fb->format->format);
4750                 return -EINVAL;
4751         }
4752
4753         return 0;
4754 }
4755
4756 static void skylake_scaler_disable(struct intel_crtc *crtc)
4757 {
4758         int i;
4759
4760         for (i = 0; i < crtc->num_scalers; i++)
4761                 skl_detach_scaler(crtc, i);
4762 }
4763
4764 static void skylake_pfit_enable(struct intel_crtc *crtc)
4765 {
4766         struct drm_device *dev = crtc->base.dev;
4767         struct drm_i915_private *dev_priv = to_i915(dev);
4768         int pipe = crtc->pipe;
4769         struct intel_crtc_scaler_state *scaler_state =
4770                 &crtc->config->scaler_state;
4771
4772         if (crtc->config->pch_pfit.enabled) {
4773                 int id;
4774
4775                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4776                         return;
4777
4778                 id = scaler_state->scaler_id;
4779                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4780                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4781                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4782                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4783         }
4784 }
4785
4786 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4787 {
4788         struct drm_device *dev = crtc->base.dev;
4789         struct drm_i915_private *dev_priv = to_i915(dev);
4790         int pipe = crtc->pipe;
4791
4792         if (crtc->config->pch_pfit.enabled) {
4793                 /* Force use of hard-coded filter coefficients
4794                  * as some pre-programmed values are broken,
4795                  * e.g. x201.
4796                  */
4797                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4798                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4799                                                  PF_PIPE_SEL_IVB(pipe));
4800                 else
4801                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4802                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4803                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4804         }
4805 }
4806
4807 void hsw_enable_ips(struct intel_crtc *crtc)
4808 {
4809         struct drm_device *dev = crtc->base.dev;
4810         struct drm_i915_private *dev_priv = to_i915(dev);
4811
4812         if (!crtc->config->ips_enabled)
4813                 return;
4814
4815         /*
4816          * We can only enable IPS after we enable a plane and wait for a vblank
4817          * This function is called from post_plane_update, which is run after
4818          * a vblank wait.
4819          */
4820
4821         assert_plane_enabled(dev_priv, crtc->plane);
4822         if (IS_BROADWELL(dev_priv)) {
4823                 mutex_lock(&dev_priv->rps.hw_lock);
4824                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4825                 mutex_unlock(&dev_priv->rps.hw_lock);
4826                 /* Quoting Art Runyan: "its not safe to expect any particular
4827                  * value in IPS_CTL bit 31 after enabling IPS through the
4828                  * mailbox." Moreover, the mailbox may return a bogus state,
4829                  * so we need to just enable it and continue on.
4830                  */
4831         } else {
4832                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4833                 /* The bit only becomes 1 in the next vblank, so this wait here
4834                  * is essentially intel_wait_for_vblank. If we don't have this
4835                  * and don't wait for vblanks until the end of crtc_enable, then
4836                  * the HW state readout code will complain that the expected
4837                  * IPS_CTL value is not the one we read. */
4838                 if (intel_wait_for_register(dev_priv,
4839                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4840                                             50))
4841                         DRM_ERROR("Timed out waiting for IPS enable\n");
4842         }
4843 }
4844
4845 void hsw_disable_ips(struct intel_crtc *crtc)
4846 {
4847         struct drm_device *dev = crtc->base.dev;
4848         struct drm_i915_private *dev_priv = to_i915(dev);
4849
4850         if (!crtc->config->ips_enabled)
4851                 return;
4852
4853         assert_plane_enabled(dev_priv, crtc->plane);
4854         if (IS_BROADWELL(dev_priv)) {
4855                 mutex_lock(&dev_priv->rps.hw_lock);
4856                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4857                 mutex_unlock(&dev_priv->rps.hw_lock);
4858                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4859                 if (intel_wait_for_register(dev_priv,
4860                                             IPS_CTL, IPS_ENABLE, 0,
4861                                             42))
4862                         DRM_ERROR("Timed out waiting for IPS disable\n");
4863         } else {
4864                 I915_WRITE(IPS_CTL, 0);
4865                 POSTING_READ(IPS_CTL);
4866         }
4867
4868         /* We need to wait for a vblank before we can disable the plane. */
4869         intel_wait_for_vblank(dev_priv, crtc->pipe);
4870 }
4871
4872 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4873 {
4874         if (intel_crtc->overlay) {
4875                 struct drm_device *dev = intel_crtc->base.dev;
4876
4877                 mutex_lock(&dev->struct_mutex);
4878                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4879                 mutex_unlock(&dev->struct_mutex);
4880         }
4881
4882         /* Let userspace switch the overlay on again. In most cases userspace
4883          * has to recompute where to put it anyway.
4884          */
4885 }
4886
4887 /**
4888  * intel_post_enable_primary - Perform operations after enabling primary plane
4889  * @crtc: the CRTC whose primary plane was just enabled
4890  *
4891  * Performs potentially sleeping operations that must be done after the primary
4892  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4893  * called due to an explicit primary plane update, or due to an implicit
4894  * re-enable that is caused when a sprite plane is updated to no longer
4895  * completely hide the primary plane.
4896  */
4897 static void
4898 intel_post_enable_primary(struct drm_crtc *crtc)
4899 {
4900         struct drm_device *dev = crtc->dev;
4901         struct drm_i915_private *dev_priv = to_i915(dev);
4902         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4903         int pipe = intel_crtc->pipe;
4904
4905         /*
4906          * FIXME IPS should be fine as long as one plane is
4907          * enabled, but in practice it seems to have problems
4908          * when going from primary only to sprite only and vice
4909          * versa.
4910          */
4911         hsw_enable_ips(intel_crtc);
4912
4913         /*
4914          * Gen2 reports pipe underruns whenever all planes are disabled.
4915          * So don't enable underrun reporting before at least some planes
4916          * are enabled.
4917          * FIXME: Need to fix the logic to work when we turn off all planes
4918          * but leave the pipe running.
4919          */
4920         if (IS_GEN2(dev_priv))
4921                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4922
4923         /* Underruns don't always raise interrupts, so check manually. */
4924         intel_check_cpu_fifo_underruns(dev_priv);
4925         intel_check_pch_fifo_underruns(dev_priv);
4926 }
4927
4928 /* FIXME move all this to pre_plane_update() with proper state tracking */
4929 static void
4930 intel_pre_disable_primary(struct drm_crtc *crtc)
4931 {
4932         struct drm_device *dev = crtc->dev;
4933         struct drm_i915_private *dev_priv = to_i915(dev);
4934         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4935         int pipe = intel_crtc->pipe;
4936
4937         /*
4938          * Gen2 reports pipe underruns whenever all planes are disabled.
4939          * So diasble underrun reporting before all the planes get disabled.
4940          * FIXME: Need to fix the logic to work when we turn off all planes
4941          * but leave the pipe running.
4942          */
4943         if (IS_GEN2(dev_priv))
4944                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4945
4946         /*
4947          * FIXME IPS should be fine as long as one plane is
4948          * enabled, but in practice it seems to have problems
4949          * when going from primary only to sprite only and vice
4950          * versa.
4951          */
4952         hsw_disable_ips(intel_crtc);
4953 }
4954
4955 /* FIXME get rid of this and use pre_plane_update */
4956 static void
4957 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4958 {
4959         struct drm_device *dev = crtc->dev;
4960         struct drm_i915_private *dev_priv = to_i915(dev);
4961         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4962         int pipe = intel_crtc->pipe;
4963
4964         intel_pre_disable_primary(crtc);
4965
4966         /*
4967          * Vblank time updates from the shadow to live plane control register
4968          * are blocked if the memory self-refresh mode is active at that
4969          * moment. So to make sure the plane gets truly disabled, disable
4970          * first the self-refresh mode. The self-refresh enable bit in turn
4971          * will be checked/applied by the HW only at the next frame start
4972          * event which is after the vblank start event, so we need to have a
4973          * wait-for-vblank between disabling the plane and the pipe.
4974          */
4975         if (HAS_GMCH_DISPLAY(dev_priv) &&
4976             intel_set_memory_cxsr(dev_priv, false))
4977                 intel_wait_for_vblank(dev_priv, pipe);
4978 }
4979
4980 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4981 {
4982         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4983         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4984         struct intel_crtc_state *pipe_config =
4985                 to_intel_crtc_state(crtc->base.state);
4986         struct drm_plane *primary = crtc->base.primary;
4987         struct drm_plane_state *old_pri_state =
4988                 drm_atomic_get_existing_plane_state(old_state, primary);
4989
4990         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
4991
4992         if (pipe_config->update_wm_post && pipe_config->base.active)
4993                 intel_update_watermarks(crtc);
4994
4995         if (old_pri_state) {
4996                 struct intel_plane_state *primary_state =
4997                         to_intel_plane_state(primary->state);
4998                 struct intel_plane_state *old_primary_state =
4999                         to_intel_plane_state(old_pri_state);
5000
5001                 intel_fbc_post_update(crtc);
5002
5003                 if (primary_state->base.visible &&
5004                     (needs_modeset(&pipe_config->base) ||
5005                      !old_primary_state->base.visible))
5006                         intel_post_enable_primary(&crtc->base);
5007         }
5008 }
5009
5010 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5011                                    struct intel_crtc_state *pipe_config)
5012 {
5013         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5014         struct drm_device *dev = crtc->base.dev;
5015         struct drm_i915_private *dev_priv = to_i915(dev);
5016         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5017         struct drm_plane *primary = crtc->base.primary;
5018         struct drm_plane_state *old_pri_state =
5019                 drm_atomic_get_existing_plane_state(old_state, primary);
5020         bool modeset = needs_modeset(&pipe_config->base);
5021         struct intel_atomic_state *old_intel_state =
5022                 to_intel_atomic_state(old_state);
5023
5024         if (old_pri_state) {
5025                 struct intel_plane_state *primary_state =
5026                         to_intel_plane_state(primary->state);
5027                 struct intel_plane_state *old_primary_state =
5028                         to_intel_plane_state(old_pri_state);
5029
5030                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5031
5032                 if (old_primary_state->base.visible &&
5033                     (modeset || !primary_state->base.visible))
5034                         intel_pre_disable_primary(&crtc->base);
5035         }
5036
5037         /*
5038          * Vblank time updates from the shadow to live plane control register
5039          * are blocked if the memory self-refresh mode is active at that
5040          * moment. So to make sure the plane gets truly disabled, disable
5041          * first the self-refresh mode. The self-refresh enable bit in turn
5042          * will be checked/applied by the HW only at the next frame start
5043          * event which is after the vblank start event, so we need to have a
5044          * wait-for-vblank between disabling the plane and the pipe.
5045          */
5046         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5047             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5048                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5049
5050         /*
5051          * IVB workaround: must disable low power watermarks for at least
5052          * one frame before enabling scaling.  LP watermarks can be re-enabled
5053          * when scaling is disabled.
5054          *
5055          * WaCxSRDisabledForSpriteScaling:ivb
5056          */
5057         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5058                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5059
5060         /*
5061          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5062          * watermark programming here.
5063          */
5064         if (needs_modeset(&pipe_config->base))
5065                 return;
5066
5067         /*
5068          * For platforms that support atomic watermarks, program the
5069          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5070          * will be the intermediate values that are safe for both pre- and
5071          * post- vblank; when vblank happens, the 'active' values will be set
5072          * to the final 'target' values and we'll do this again to get the
5073          * optimal watermarks.  For gen9+ platforms, the values we program here
5074          * will be the final target values which will get automatically latched
5075          * at vblank time; no further programming will be necessary.
5076          *
5077          * If a platform hasn't been transitioned to atomic watermarks yet,
5078          * we'll continue to update watermarks the old way, if flags tell
5079          * us to.
5080          */
5081         if (dev_priv->display.initial_watermarks != NULL)
5082                 dev_priv->display.initial_watermarks(old_intel_state,
5083                                                      pipe_config);
5084         else if (pipe_config->update_wm_pre)
5085                 intel_update_watermarks(crtc);
5086 }
5087
5088 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5089 {
5090         struct drm_device *dev = crtc->dev;
5091         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5092         struct drm_plane *p;
5093         int pipe = intel_crtc->pipe;
5094
5095         intel_crtc_dpms_overlay_disable(intel_crtc);
5096
5097         drm_for_each_plane_mask(p, dev, plane_mask)
5098                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5099
5100         /*
5101          * FIXME: Once we grow proper nuclear flip support out of this we need
5102          * to compute the mask of flip planes precisely. For the time being
5103          * consider this a flip to a NULL plane.
5104          */
5105         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5106 }
5107
5108 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5109                                           struct intel_crtc_state *crtc_state,
5110                                           struct drm_atomic_state *old_state)
5111 {
5112         struct drm_connector_state *conn_state;
5113         struct drm_connector *conn;
5114         int i;
5115
5116         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5117                 struct intel_encoder *encoder =
5118                         to_intel_encoder(conn_state->best_encoder);
5119
5120                 if (conn_state->crtc != crtc)
5121                         continue;
5122
5123                 if (encoder->pre_pll_enable)
5124                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5125         }
5126 }
5127
5128 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5129                                       struct intel_crtc_state *crtc_state,
5130                                       struct drm_atomic_state *old_state)
5131 {
5132         struct drm_connector_state *conn_state;
5133         struct drm_connector *conn;
5134         int i;
5135
5136         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5137                 struct intel_encoder *encoder =
5138                         to_intel_encoder(conn_state->best_encoder);
5139
5140                 if (conn_state->crtc != crtc)
5141                         continue;
5142
5143                 if (encoder->pre_enable)
5144                         encoder->pre_enable(encoder, crtc_state, conn_state);
5145         }
5146 }
5147
5148 static void intel_encoders_enable(struct drm_crtc *crtc,
5149                                   struct intel_crtc_state *crtc_state,
5150                                   struct drm_atomic_state *old_state)
5151 {
5152         struct drm_connector_state *conn_state;
5153         struct drm_connector *conn;
5154         int i;
5155
5156         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5157                 struct intel_encoder *encoder =
5158                         to_intel_encoder(conn_state->best_encoder);
5159
5160                 if (conn_state->crtc != crtc)
5161                         continue;
5162
5163                 encoder->enable(encoder, crtc_state, conn_state);
5164                 intel_opregion_notify_encoder(encoder, true);
5165         }
5166 }
5167
5168 static void intel_encoders_disable(struct drm_crtc *crtc,
5169                                    struct intel_crtc_state *old_crtc_state,
5170                                    struct drm_atomic_state *old_state)
5171 {
5172         struct drm_connector_state *old_conn_state;
5173         struct drm_connector *conn;
5174         int i;
5175
5176         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5177                 struct intel_encoder *encoder =
5178                         to_intel_encoder(old_conn_state->best_encoder);
5179
5180                 if (old_conn_state->crtc != crtc)
5181                         continue;
5182
5183                 intel_opregion_notify_encoder(encoder, false);
5184                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5185         }
5186 }
5187
5188 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5189                                         struct intel_crtc_state *old_crtc_state,
5190                                         struct drm_atomic_state *old_state)
5191 {
5192         struct drm_connector_state *old_conn_state;
5193         struct drm_connector *conn;
5194         int i;
5195
5196         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5197                 struct intel_encoder *encoder =
5198                         to_intel_encoder(old_conn_state->best_encoder);
5199
5200                 if (old_conn_state->crtc != crtc)
5201                         continue;
5202
5203                 if (encoder->post_disable)
5204                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5205         }
5206 }
5207
5208 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5209                                             struct intel_crtc_state *old_crtc_state,
5210                                             struct drm_atomic_state *old_state)
5211 {
5212         struct drm_connector_state *old_conn_state;
5213         struct drm_connector *conn;
5214         int i;
5215
5216         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5217                 struct intel_encoder *encoder =
5218                         to_intel_encoder(old_conn_state->best_encoder);
5219
5220                 if (old_conn_state->crtc != crtc)
5221                         continue;
5222
5223                 if (encoder->post_pll_disable)
5224                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5225         }
5226 }
5227
5228 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5229                                  struct drm_atomic_state *old_state)
5230 {
5231         struct drm_crtc *crtc = pipe_config->base.crtc;
5232         struct drm_device *dev = crtc->dev;
5233         struct drm_i915_private *dev_priv = to_i915(dev);
5234         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5235         int pipe = intel_crtc->pipe;
5236         struct intel_atomic_state *old_intel_state =
5237                 to_intel_atomic_state(old_state);
5238
5239         if (WARN_ON(intel_crtc->active))
5240                 return;
5241
5242         /*
5243          * Sometimes spurious CPU pipe underruns happen during FDI
5244          * training, at least with VGA+HDMI cloning. Suppress them.
5245          *
5246          * On ILK we get an occasional spurious CPU pipe underruns
5247          * between eDP port A enable and vdd enable. Also PCH port
5248          * enable seems to result in the occasional CPU pipe underrun.
5249          *
5250          * Spurious PCH underruns also occur during PCH enabling.
5251          */
5252         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5253                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5254         if (intel_crtc->config->has_pch_encoder)
5255                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5256
5257         if (intel_crtc->config->has_pch_encoder)
5258                 intel_prepare_shared_dpll(intel_crtc);
5259
5260         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5261                 intel_dp_set_m_n(intel_crtc, M1_N1);
5262
5263         intel_set_pipe_timings(intel_crtc);
5264         intel_set_pipe_src_size(intel_crtc);
5265
5266         if (intel_crtc->config->has_pch_encoder) {
5267                 intel_cpu_transcoder_set_m_n(intel_crtc,
5268                                      &intel_crtc->config->fdi_m_n, NULL);
5269         }
5270
5271         ironlake_set_pipeconf(crtc);
5272
5273         intel_crtc->active = true;
5274
5275         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5276
5277         if (intel_crtc->config->has_pch_encoder) {
5278                 /* Note: FDI PLL enabling _must_ be done before we enable the
5279                  * cpu pipes, hence this is separate from all the other fdi/pch
5280                  * enabling. */
5281                 ironlake_fdi_pll_enable(intel_crtc);
5282         } else {
5283                 assert_fdi_tx_disabled(dev_priv, pipe);
5284                 assert_fdi_rx_disabled(dev_priv, pipe);
5285         }
5286
5287         ironlake_pfit_enable(intel_crtc);
5288
5289         /*
5290          * On ILK+ LUT must be loaded before the pipe is running but with
5291          * clocks enabled
5292          */
5293         intel_color_load_luts(&pipe_config->base);
5294
5295         if (dev_priv->display.initial_watermarks != NULL)
5296                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5297         intel_enable_pipe(intel_crtc);
5298
5299         if (intel_crtc->config->has_pch_encoder)
5300                 ironlake_pch_enable(pipe_config);
5301
5302         assert_vblank_disabled(crtc);
5303         drm_crtc_vblank_on(crtc);
5304
5305         intel_encoders_enable(crtc, pipe_config, old_state);
5306
5307         if (HAS_PCH_CPT(dev_priv))
5308                 cpt_verify_modeset(dev, intel_crtc->pipe);
5309
5310         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5311         if (intel_crtc->config->has_pch_encoder)
5312                 intel_wait_for_vblank(dev_priv, pipe);
5313         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5314         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5315 }
5316
5317 /* IPS only exists on ULT machines and is tied to pipe A. */
5318 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5319 {
5320         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5321 }
5322
5323 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5324                                 struct drm_atomic_state *old_state)
5325 {
5326         struct drm_crtc *crtc = pipe_config->base.crtc;
5327         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5328         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5329         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5330         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5331         struct intel_atomic_state *old_intel_state =
5332                 to_intel_atomic_state(old_state);
5333
5334         if (WARN_ON(intel_crtc->active))
5335                 return;
5336
5337         if (intel_crtc->config->has_pch_encoder)
5338                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5339                                                       false);
5340
5341         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5342
5343         if (intel_crtc->config->shared_dpll)
5344                 intel_enable_shared_dpll(intel_crtc);
5345
5346         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5347                 intel_dp_set_m_n(intel_crtc, M1_N1);
5348
5349         if (!transcoder_is_dsi(cpu_transcoder))
5350                 intel_set_pipe_timings(intel_crtc);
5351
5352         intel_set_pipe_src_size(intel_crtc);
5353
5354         if (cpu_transcoder != TRANSCODER_EDP &&
5355             !transcoder_is_dsi(cpu_transcoder)) {
5356                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5357                            intel_crtc->config->pixel_multiplier - 1);
5358         }
5359
5360         if (intel_crtc->config->has_pch_encoder) {
5361                 intel_cpu_transcoder_set_m_n(intel_crtc,
5362                                      &intel_crtc->config->fdi_m_n, NULL);
5363         }
5364
5365         if (!transcoder_is_dsi(cpu_transcoder))
5366                 haswell_set_pipeconf(crtc);
5367
5368         haswell_set_pipemisc(crtc);
5369
5370         intel_color_set_csc(&pipe_config->base);
5371
5372         intel_crtc->active = true;
5373
5374         if (intel_crtc->config->has_pch_encoder)
5375                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5376         else
5377                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5378
5379         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5380
5381         if (intel_crtc->config->has_pch_encoder)
5382                 dev_priv->display.fdi_link_train(intel_crtc, pipe_config);
5383
5384         if (!transcoder_is_dsi(cpu_transcoder))
5385                 intel_ddi_enable_pipe_clock(pipe_config);
5386
5387         if (INTEL_GEN(dev_priv) >= 9)
5388                 skylake_pfit_enable(intel_crtc);
5389         else
5390                 ironlake_pfit_enable(intel_crtc);
5391
5392         /*
5393          * On ILK+ LUT must be loaded before the pipe is running but with
5394          * clocks enabled
5395          */
5396         intel_color_load_luts(&pipe_config->base);
5397
5398         intel_ddi_set_pipe_settings(pipe_config);
5399         if (!transcoder_is_dsi(cpu_transcoder))
5400                 intel_ddi_enable_transcoder_func(pipe_config);
5401
5402         if (dev_priv->display.initial_watermarks != NULL)
5403                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5404
5405         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5406         if (!transcoder_is_dsi(cpu_transcoder))
5407                 intel_enable_pipe(intel_crtc);
5408
5409         if (intel_crtc->config->has_pch_encoder)
5410                 lpt_pch_enable(pipe_config);
5411
5412         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5413                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5414
5415         assert_vblank_disabled(crtc);
5416         drm_crtc_vblank_on(crtc);
5417
5418         intel_encoders_enable(crtc, pipe_config, old_state);
5419
5420         if (intel_crtc->config->has_pch_encoder) {
5421                 intel_wait_for_vblank(dev_priv, pipe);
5422                 intel_wait_for_vblank(dev_priv, pipe);
5423                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5424                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5425                                                       true);
5426         }
5427
5428         /* If we change the relative order between pipe/planes enabling, we need
5429          * to change the workaround. */
5430         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5431         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5432                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5433                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5434         }
5435 }
5436
5437 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5438 {
5439         struct drm_device *dev = crtc->base.dev;
5440         struct drm_i915_private *dev_priv = to_i915(dev);
5441         int pipe = crtc->pipe;
5442
5443         /* To avoid upsetting the power well on haswell only disable the pfit if
5444          * it's in use. The hw state code will make sure we get this right. */
5445         if (force || crtc->config->pch_pfit.enabled) {
5446                 I915_WRITE(PF_CTL(pipe), 0);
5447                 I915_WRITE(PF_WIN_POS(pipe), 0);
5448                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5449         }
5450 }
5451
5452 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5453                                   struct drm_atomic_state *old_state)
5454 {
5455         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5456         struct drm_device *dev = crtc->dev;
5457         struct drm_i915_private *dev_priv = to_i915(dev);
5458         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5459         int pipe = intel_crtc->pipe;
5460
5461         /*
5462          * Sometimes spurious CPU pipe underruns happen when the
5463          * pipe is already disabled, but FDI RX/TX is still enabled.
5464          * Happens at least with VGA+HDMI cloning. Suppress them.
5465          */
5466         if (intel_crtc->config->has_pch_encoder) {
5467                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5468                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5469         }
5470
5471         intel_encoders_disable(crtc, old_crtc_state, old_state);
5472
5473         drm_crtc_vblank_off(crtc);
5474         assert_vblank_disabled(crtc);
5475
5476         intel_disable_pipe(intel_crtc);
5477
5478         ironlake_pfit_disable(intel_crtc, false);
5479
5480         if (intel_crtc->config->has_pch_encoder)
5481                 ironlake_fdi_disable(crtc);
5482
5483         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5484
5485         if (intel_crtc->config->has_pch_encoder) {
5486                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5487
5488                 if (HAS_PCH_CPT(dev_priv)) {
5489                         i915_reg_t reg;
5490                         u32 temp;
5491
5492                         /* disable TRANS_DP_CTL */
5493                         reg = TRANS_DP_CTL(pipe);
5494                         temp = I915_READ(reg);
5495                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5496                                   TRANS_DP_PORT_SEL_MASK);
5497                         temp |= TRANS_DP_PORT_SEL_NONE;
5498                         I915_WRITE(reg, temp);
5499
5500                         /* disable DPLL_SEL */
5501                         temp = I915_READ(PCH_DPLL_SEL);
5502                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5503                         I915_WRITE(PCH_DPLL_SEL, temp);
5504                 }
5505
5506                 ironlake_fdi_pll_disable(intel_crtc);
5507         }
5508
5509         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5510         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5511 }
5512
5513 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5514                                  struct drm_atomic_state *old_state)
5515 {
5516         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5517         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5518         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5519         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5520
5521         if (intel_crtc->config->has_pch_encoder)
5522                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5523                                                       false);
5524
5525         intel_encoders_disable(crtc, old_crtc_state, old_state);
5526
5527         drm_crtc_vblank_off(crtc);
5528         assert_vblank_disabled(crtc);
5529
5530         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5531         if (!transcoder_is_dsi(cpu_transcoder))
5532                 intel_disable_pipe(intel_crtc);
5533
5534         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5535                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5536
5537         if (!transcoder_is_dsi(cpu_transcoder))
5538                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5539
5540         if (INTEL_GEN(dev_priv) >= 9)
5541                 skylake_scaler_disable(intel_crtc);
5542         else
5543                 ironlake_pfit_disable(intel_crtc, false);
5544
5545         if (!transcoder_is_dsi(cpu_transcoder))
5546                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5547
5548         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5549
5550         if (old_crtc_state->has_pch_encoder)
5551                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5552                                                       true);
5553 }
5554
5555 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5556 {
5557         struct drm_device *dev = crtc->base.dev;
5558         struct drm_i915_private *dev_priv = to_i915(dev);
5559         struct intel_crtc_state *pipe_config = crtc->config;
5560
5561         if (!pipe_config->gmch_pfit.control)
5562                 return;
5563
5564         /*
5565          * The panel fitter should only be adjusted whilst the pipe is disabled,
5566          * according to register description and PRM.
5567          */
5568         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5569         assert_pipe_disabled(dev_priv, crtc->pipe);
5570
5571         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5572         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5573
5574         /* Border color in case we don't scale up to the full screen. Black by
5575          * default, change to something else for debugging. */
5576         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5577 }
5578
5579 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5580 {
5581         switch (port) {
5582         case PORT_A:
5583                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5584         case PORT_B:
5585                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5586         case PORT_C:
5587                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5588         case PORT_D:
5589                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5590         case PORT_E:
5591                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5592         default:
5593                 MISSING_CASE(port);
5594                 return POWER_DOMAIN_PORT_OTHER;
5595         }
5596 }
5597
5598 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5599                                   struct intel_crtc_state *crtc_state)
5600 {
5601         struct drm_device *dev = crtc->dev;
5602         struct drm_i915_private *dev_priv = to_i915(dev);
5603         struct drm_encoder *encoder;
5604         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5605         enum pipe pipe = intel_crtc->pipe;
5606         u64 mask;
5607         enum transcoder transcoder = crtc_state->cpu_transcoder;
5608
5609         if (!crtc_state->base.active)
5610                 return 0;
5611
5612         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5613         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5614         if (crtc_state->pch_pfit.enabled ||
5615             crtc_state->pch_pfit.force_thru)
5616                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5617
5618         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5619                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5620
5621                 mask |= BIT_ULL(intel_encoder->power_domain);
5622         }
5623
5624         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5625                 mask |= BIT(POWER_DOMAIN_AUDIO);
5626
5627         if (crtc_state->shared_dpll)
5628                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5629
5630         return mask;
5631 }
5632
5633 static u64
5634 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5635                                struct intel_crtc_state *crtc_state)
5636 {
5637         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5638         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5639         enum intel_display_power_domain domain;
5640         u64 domains, new_domains, old_domains;
5641
5642         old_domains = intel_crtc->enabled_power_domains;
5643         intel_crtc->enabled_power_domains = new_domains =
5644                 get_crtc_power_domains(crtc, crtc_state);
5645
5646         domains = new_domains & ~old_domains;
5647
5648         for_each_power_domain(domain, domains)
5649                 intel_display_power_get(dev_priv, domain);
5650
5651         return old_domains & ~new_domains;
5652 }
5653
5654 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5655                                       u64 domains)
5656 {
5657         enum intel_display_power_domain domain;
5658
5659         for_each_power_domain(domain, domains)
5660                 intel_display_power_put(dev_priv, domain);
5661 }
5662
5663 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5664                                    struct drm_atomic_state *old_state)
5665 {
5666         struct intel_atomic_state *old_intel_state =
5667                 to_intel_atomic_state(old_state);
5668         struct drm_crtc *crtc = pipe_config->base.crtc;
5669         struct drm_device *dev = crtc->dev;
5670         struct drm_i915_private *dev_priv = to_i915(dev);
5671         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5672         int pipe = intel_crtc->pipe;
5673
5674         if (WARN_ON(intel_crtc->active))
5675                 return;
5676
5677         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5678                 intel_dp_set_m_n(intel_crtc, M1_N1);
5679
5680         intel_set_pipe_timings(intel_crtc);
5681         intel_set_pipe_src_size(intel_crtc);
5682
5683         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5684                 struct drm_i915_private *dev_priv = to_i915(dev);
5685
5686                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5687                 I915_WRITE(CHV_CANVAS(pipe), 0);
5688         }
5689
5690         i9xx_set_pipeconf(intel_crtc);
5691
5692         intel_crtc->active = true;
5693
5694         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5695
5696         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5697
5698         if (IS_CHERRYVIEW(dev_priv)) {
5699                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5700                 chv_enable_pll(intel_crtc, intel_crtc->config);
5701         } else {
5702                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5703                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5704         }
5705
5706         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5707
5708         i9xx_pfit_enable(intel_crtc);
5709
5710         intel_color_load_luts(&pipe_config->base);
5711
5712         dev_priv->display.initial_watermarks(old_intel_state,
5713                                              pipe_config);
5714         intel_enable_pipe(intel_crtc);
5715
5716         assert_vblank_disabled(crtc);
5717         drm_crtc_vblank_on(crtc);
5718
5719         intel_encoders_enable(crtc, pipe_config, old_state);
5720 }
5721
5722 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5723 {
5724         struct drm_device *dev = crtc->base.dev;
5725         struct drm_i915_private *dev_priv = to_i915(dev);
5726
5727         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5728         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5729 }
5730
5731 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5732                              struct drm_atomic_state *old_state)
5733 {
5734         struct intel_atomic_state *old_intel_state =
5735                 to_intel_atomic_state(old_state);
5736         struct drm_crtc *crtc = pipe_config->base.crtc;
5737         struct drm_device *dev = crtc->dev;
5738         struct drm_i915_private *dev_priv = to_i915(dev);
5739         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5740         enum pipe pipe = intel_crtc->pipe;
5741
5742         if (WARN_ON(intel_crtc->active))
5743                 return;
5744
5745         i9xx_set_pll_dividers(intel_crtc);
5746
5747         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5748                 intel_dp_set_m_n(intel_crtc, M1_N1);
5749
5750         intel_set_pipe_timings(intel_crtc);
5751         intel_set_pipe_src_size(intel_crtc);
5752
5753         i9xx_set_pipeconf(intel_crtc);
5754
5755         intel_crtc->active = true;
5756
5757         if (!IS_GEN2(dev_priv))
5758                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5759
5760         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5761
5762         i9xx_enable_pll(intel_crtc);
5763
5764         i9xx_pfit_enable(intel_crtc);
5765
5766         intel_color_load_luts(&pipe_config->base);
5767
5768         if (dev_priv->display.initial_watermarks != NULL)
5769                 dev_priv->display.initial_watermarks(old_intel_state,
5770                                                      intel_crtc->config);
5771         else
5772                 intel_update_watermarks(intel_crtc);
5773         intel_enable_pipe(intel_crtc);
5774
5775         assert_vblank_disabled(crtc);
5776         drm_crtc_vblank_on(crtc);
5777
5778         intel_encoders_enable(crtc, pipe_config, old_state);
5779 }
5780
5781 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5782 {
5783         struct drm_device *dev = crtc->base.dev;
5784         struct drm_i915_private *dev_priv = to_i915(dev);
5785
5786         if (!crtc->config->gmch_pfit.control)
5787                 return;
5788
5789         assert_pipe_disabled(dev_priv, crtc->pipe);
5790
5791         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5792                          I915_READ(PFIT_CONTROL));
5793         I915_WRITE(PFIT_CONTROL, 0);
5794 }
5795
5796 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5797                               struct drm_atomic_state *old_state)
5798 {
5799         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5800         struct drm_device *dev = crtc->dev;
5801         struct drm_i915_private *dev_priv = to_i915(dev);
5802         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5803         int pipe = intel_crtc->pipe;
5804
5805         /*
5806          * On gen2 planes are double buffered but the pipe isn't, so we must
5807          * wait for planes to fully turn off before disabling the pipe.
5808          */
5809         if (IS_GEN2(dev_priv))
5810                 intel_wait_for_vblank(dev_priv, pipe);
5811
5812         intel_encoders_disable(crtc, old_crtc_state, old_state);
5813
5814         drm_crtc_vblank_off(crtc);
5815         assert_vblank_disabled(crtc);
5816
5817         intel_disable_pipe(intel_crtc);
5818
5819         i9xx_pfit_disable(intel_crtc);
5820
5821         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5822
5823         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
5824                 if (IS_CHERRYVIEW(dev_priv))
5825                         chv_disable_pll(dev_priv, pipe);
5826                 else if (IS_VALLEYVIEW(dev_priv))
5827                         vlv_disable_pll(dev_priv, pipe);
5828                 else
5829                         i9xx_disable_pll(intel_crtc);
5830         }
5831
5832         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5833
5834         if (!IS_GEN2(dev_priv))
5835                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5836
5837         if (!dev_priv->display.initial_watermarks)
5838                 intel_update_watermarks(intel_crtc);
5839 }
5840
5841 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
5842                                         struct drm_modeset_acquire_ctx *ctx)
5843 {
5844         struct intel_encoder *encoder;
5845         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5846         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5847         enum intel_display_power_domain domain;
5848         u64 domains;
5849         struct drm_atomic_state *state;
5850         struct intel_crtc_state *crtc_state;
5851         int ret;
5852
5853         if (!intel_crtc->active)
5854                 return;
5855
5856         if (crtc->primary->state->visible) {
5857                 WARN_ON(intel_crtc->flip_work);
5858
5859                 intel_pre_disable_primary_noatomic(crtc);
5860
5861                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
5862                 crtc->primary->state->visible = false;
5863         }
5864
5865         state = drm_atomic_state_alloc(crtc->dev);
5866         if (!state) {
5867                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
5868                               crtc->base.id, crtc->name);
5869                 return;
5870         }
5871
5872         state->acquire_ctx = ctx;
5873
5874         /* Everything's already locked, -EDEADLK can't happen. */
5875         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5876         ret = drm_atomic_add_affected_connectors(state, crtc);
5877
5878         WARN_ON(IS_ERR(crtc_state) || ret);
5879
5880         dev_priv->display.crtc_disable(crtc_state, state);
5881
5882         drm_atomic_state_put(state);
5883
5884         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
5885                       crtc->base.id, crtc->name);
5886
5887         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
5888         crtc->state->active = false;
5889         intel_crtc->active = false;
5890         crtc->enabled = false;
5891         crtc->state->connector_mask = 0;
5892         crtc->state->encoder_mask = 0;
5893
5894         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
5895                 encoder->base.crtc = NULL;
5896
5897         intel_fbc_disable(intel_crtc);
5898         intel_update_watermarks(intel_crtc);
5899         intel_disable_shared_dpll(intel_crtc);
5900
5901         domains = intel_crtc->enabled_power_domains;
5902         for_each_power_domain(domain, domains)
5903                 intel_display_power_put(dev_priv, domain);
5904         intel_crtc->enabled_power_domains = 0;
5905
5906         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
5907         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
5908 }
5909
5910 /*
5911  * turn all crtc's off, but do not adjust state
5912  * This has to be paired with a call to intel_modeset_setup_hw_state.
5913  */
5914 int intel_display_suspend(struct drm_device *dev)
5915 {
5916         struct drm_i915_private *dev_priv = to_i915(dev);
5917         struct drm_atomic_state *state;
5918         int ret;
5919
5920         state = drm_atomic_helper_suspend(dev);
5921         ret = PTR_ERR_OR_ZERO(state);
5922         if (ret)
5923                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
5924         else
5925                 dev_priv->modeset_restore_state = state;
5926         return ret;
5927 }
5928
5929 void intel_encoder_destroy(struct drm_encoder *encoder)
5930 {
5931         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5932
5933         drm_encoder_cleanup(encoder);
5934         kfree(intel_encoder);
5935 }
5936
5937 /* Cross check the actual hw state with our own modeset state tracking (and it's
5938  * internal consistency). */
5939 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
5940                                          struct drm_connector_state *conn_state)
5941 {
5942         struct intel_connector *connector = to_intel_connector(conn_state->connector);
5943
5944         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
5945                       connector->base.base.id,
5946                       connector->base.name);
5947
5948         if (connector->get_hw_state(connector)) {
5949                 struct intel_encoder *encoder = connector->encoder;
5950
5951                 I915_STATE_WARN(!crtc_state,
5952                          "connector enabled without attached crtc\n");
5953
5954                 if (!crtc_state)
5955                         return;
5956
5957                 I915_STATE_WARN(!crtc_state->active,
5958                       "connector is active, but attached crtc isn't\n");
5959
5960                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
5961                         return;
5962
5963                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
5964                         "atomic encoder doesn't match attached encoder\n");
5965
5966                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
5967                         "attached encoder crtc differs from connector crtc\n");
5968         } else {
5969                 I915_STATE_WARN(crtc_state && crtc_state->active,
5970                         "attached crtc is active, but connector isn't\n");
5971                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
5972                         "best encoder set without crtc!\n");
5973         }
5974 }
5975
5976 int intel_connector_init(struct intel_connector *connector)
5977 {
5978         struct intel_digital_connector_state *conn_state;
5979
5980         /*
5981          * Allocate enough memory to hold intel_digital_connector_state,
5982          * This might be a few bytes too many, but for connectors that don't
5983          * need it we'll free the state and allocate a smaller one on the first
5984          * succesful commit anyway.
5985          */
5986         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
5987         if (!conn_state)
5988                 return -ENOMEM;
5989
5990         __drm_atomic_helper_connector_reset(&connector->base,
5991                                             &conn_state->base);
5992
5993         return 0;
5994 }
5995
5996 struct intel_connector *intel_connector_alloc(void)
5997 {
5998         struct intel_connector *connector;
5999
6000         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6001         if (!connector)
6002                 return NULL;
6003
6004         if (intel_connector_init(connector) < 0) {
6005                 kfree(connector);
6006                 return NULL;
6007         }
6008
6009         return connector;
6010 }
6011
6012 /* Simple connector->get_hw_state implementation for encoders that support only
6013  * one connector and no cloning and hence the encoder state determines the state
6014  * of the connector. */
6015 bool intel_connector_get_hw_state(struct intel_connector *connector)
6016 {
6017         enum pipe pipe = 0;
6018         struct intel_encoder *encoder = connector->encoder;
6019
6020         return encoder->get_hw_state(encoder, &pipe);
6021 }
6022
6023 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6024 {
6025         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6026                 return crtc_state->fdi_lanes;
6027
6028         return 0;
6029 }
6030
6031 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6032                                      struct intel_crtc_state *pipe_config)
6033 {
6034         struct drm_i915_private *dev_priv = to_i915(dev);
6035         struct drm_atomic_state *state = pipe_config->base.state;
6036         struct intel_crtc *other_crtc;
6037         struct intel_crtc_state *other_crtc_state;
6038
6039         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6040                       pipe_name(pipe), pipe_config->fdi_lanes);
6041         if (pipe_config->fdi_lanes > 4) {
6042                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6043                               pipe_name(pipe), pipe_config->fdi_lanes);
6044                 return -EINVAL;
6045         }
6046
6047         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6048                 if (pipe_config->fdi_lanes > 2) {
6049                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6050                                       pipe_config->fdi_lanes);
6051                         return -EINVAL;
6052                 } else {
6053                         return 0;
6054                 }
6055         }
6056
6057         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6058                 return 0;
6059
6060         /* Ivybridge 3 pipe is really complicated */
6061         switch (pipe) {
6062         case PIPE_A:
6063                 return 0;
6064         case PIPE_B:
6065                 if (pipe_config->fdi_lanes <= 2)
6066                         return 0;
6067
6068                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6069                 other_crtc_state =
6070                         intel_atomic_get_crtc_state(state, other_crtc);
6071                 if (IS_ERR(other_crtc_state))
6072                         return PTR_ERR(other_crtc_state);
6073
6074                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6075                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6076                                       pipe_name(pipe), pipe_config->fdi_lanes);
6077                         return -EINVAL;
6078                 }
6079                 return 0;
6080         case PIPE_C:
6081                 if (pipe_config->fdi_lanes > 2) {
6082                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6083                                       pipe_name(pipe), pipe_config->fdi_lanes);
6084                         return -EINVAL;
6085                 }
6086
6087                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6088                 other_crtc_state =
6089                         intel_atomic_get_crtc_state(state, other_crtc);
6090                 if (IS_ERR(other_crtc_state))
6091                         return PTR_ERR(other_crtc_state);
6092
6093                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6094                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6095                         return -EINVAL;
6096                 }
6097                 return 0;
6098         default:
6099                 BUG();
6100         }
6101 }
6102
6103 #define RETRY 1
6104 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6105                                        struct intel_crtc_state *pipe_config)
6106 {
6107         struct drm_device *dev = intel_crtc->base.dev;
6108         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6109         int lane, link_bw, fdi_dotclock, ret;
6110         bool needs_recompute = false;
6111
6112 retry:
6113         /* FDI is a binary signal running at ~2.7GHz, encoding
6114          * each output octet as 10 bits. The actual frequency
6115          * is stored as a divider into a 100MHz clock, and the
6116          * mode pixel clock is stored in units of 1KHz.
6117          * Hence the bw of each lane in terms of the mode signal
6118          * is:
6119          */
6120         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6121
6122         fdi_dotclock = adjusted_mode->crtc_clock;
6123
6124         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6125                                            pipe_config->pipe_bpp);
6126
6127         pipe_config->fdi_lanes = lane;
6128
6129         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6130                                link_bw, &pipe_config->fdi_m_n);
6131
6132         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6133         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6134                 pipe_config->pipe_bpp -= 2*3;
6135                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6136                               pipe_config->pipe_bpp);
6137                 needs_recompute = true;
6138                 pipe_config->bw_constrained = true;
6139
6140                 goto retry;
6141         }
6142
6143         if (needs_recompute)
6144                 return RETRY;
6145
6146         return ret;
6147 }
6148
6149 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6150                                      struct intel_crtc_state *pipe_config)
6151 {
6152         if (pipe_config->pipe_bpp > 24)
6153                 return false;
6154
6155         /* HSW can handle pixel rate up to cdclk? */
6156         if (IS_HASWELL(dev_priv))
6157                 return true;
6158
6159         /*
6160          * We compare against max which means we must take
6161          * the increased cdclk requirement into account when
6162          * calculating the new cdclk.
6163          *
6164          * Should measure whether using a lower cdclk w/o IPS
6165          */
6166         return pipe_config->pixel_rate <=
6167                 dev_priv->max_cdclk_freq * 95 / 100;
6168 }
6169
6170 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6171                                    struct intel_crtc_state *pipe_config)
6172 {
6173         struct drm_device *dev = crtc->base.dev;
6174         struct drm_i915_private *dev_priv = to_i915(dev);
6175
6176         pipe_config->ips_enabled = i915.enable_ips &&
6177                 hsw_crtc_supports_ips(crtc) &&
6178                 pipe_config_supports_ips(dev_priv, pipe_config);
6179 }
6180
6181 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6182 {
6183         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6184
6185         /* GDG double wide on either pipe, otherwise pipe A only */
6186         return INTEL_INFO(dev_priv)->gen < 4 &&
6187                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6188 }
6189
6190 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6191 {
6192         uint32_t pixel_rate;
6193
6194         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6195
6196         /*
6197          * We only use IF-ID interlacing. If we ever use
6198          * PF-ID we'll need to adjust the pixel_rate here.
6199          */
6200
6201         if (pipe_config->pch_pfit.enabled) {
6202                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6203                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6204
6205                 pipe_w = pipe_config->pipe_src_w;
6206                 pipe_h = pipe_config->pipe_src_h;
6207
6208                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6209                 pfit_h = pfit_size & 0xFFFF;
6210                 if (pipe_w < pfit_w)
6211                         pipe_w = pfit_w;
6212                 if (pipe_h < pfit_h)
6213                         pipe_h = pfit_h;
6214
6215                 if (WARN_ON(!pfit_w || !pfit_h))
6216                         return pixel_rate;
6217
6218                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6219                                      pfit_w * pfit_h);
6220         }
6221
6222         return pixel_rate;
6223 }
6224
6225 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6226 {
6227         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6228
6229         if (HAS_GMCH_DISPLAY(dev_priv))
6230                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6231                 crtc_state->pixel_rate =
6232                         crtc_state->base.adjusted_mode.crtc_clock;
6233         else
6234                 crtc_state->pixel_rate =
6235                         ilk_pipe_pixel_rate(crtc_state);
6236 }
6237
6238 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6239                                      struct intel_crtc_state *pipe_config)
6240 {
6241         struct drm_device *dev = crtc->base.dev;
6242         struct drm_i915_private *dev_priv = to_i915(dev);
6243         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6244         int clock_limit = dev_priv->max_dotclk_freq;
6245
6246         if (INTEL_GEN(dev_priv) < 4) {
6247                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6248
6249                 /*
6250                  * Enable double wide mode when the dot clock
6251                  * is > 90% of the (display) core speed.
6252                  */
6253                 if (intel_crtc_supports_double_wide(crtc) &&
6254                     adjusted_mode->crtc_clock > clock_limit) {
6255                         clock_limit = dev_priv->max_dotclk_freq;
6256                         pipe_config->double_wide = true;
6257                 }
6258         }
6259
6260         if (adjusted_mode->crtc_clock > clock_limit) {
6261                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6262                               adjusted_mode->crtc_clock, clock_limit,
6263                               yesno(pipe_config->double_wide));
6264                 return -EINVAL;
6265         }
6266
6267         /*
6268          * Pipe horizontal size must be even in:
6269          * - DVO ganged mode
6270          * - LVDS dual channel mode
6271          * - Double wide pipe
6272          */
6273         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6274              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6275                 pipe_config->pipe_src_w &= ~1;
6276
6277         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6278          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6279          */
6280         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6281                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6282                 return -EINVAL;
6283
6284         intel_crtc_compute_pixel_rate(pipe_config);
6285
6286         if (HAS_IPS(dev_priv))
6287                 hsw_compute_ips_config(crtc, pipe_config);
6288
6289         if (pipe_config->has_pch_encoder)
6290                 return ironlake_fdi_compute_config(crtc, pipe_config);
6291
6292         return 0;
6293 }
6294
6295 static void
6296 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6297 {
6298         while (*num > DATA_LINK_M_N_MASK ||
6299                *den > DATA_LINK_M_N_MASK) {
6300                 *num >>= 1;
6301                 *den >>= 1;
6302         }
6303 }
6304
6305 static void compute_m_n(unsigned int m, unsigned int n,
6306                         uint32_t *ret_m, uint32_t *ret_n)
6307 {
6308         /*
6309          * Reduce M/N as much as possible without loss in precision. Several DP
6310          * dongles in particular seem to be fussy about too large *link* M/N
6311          * values. The passed in values are more likely to have the least
6312          * significant bits zero than M after rounding below, so do this first.
6313          */
6314         while ((m & 1) == 0 && (n & 1) == 0) {
6315                 m >>= 1;
6316                 n >>= 1;
6317         }
6318
6319         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6320         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6321         intel_reduce_m_n_ratio(ret_m, ret_n);
6322 }
6323
6324 void
6325 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6326                        int pixel_clock, int link_clock,
6327                        struct intel_link_m_n *m_n)
6328 {
6329         m_n->tu = 64;
6330
6331         compute_m_n(bits_per_pixel * pixel_clock,
6332                     link_clock * nlanes * 8,
6333                     &m_n->gmch_m, &m_n->gmch_n);
6334
6335         compute_m_n(pixel_clock, link_clock,
6336                     &m_n->link_m, &m_n->link_n);
6337 }
6338
6339 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6340 {
6341         if (i915.panel_use_ssc >= 0)
6342                 return i915.panel_use_ssc != 0;
6343         return dev_priv->vbt.lvds_use_ssc
6344                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6345 }
6346
6347 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6348 {
6349         return (1 << dpll->n) << 16 | dpll->m2;
6350 }
6351
6352 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6353 {
6354         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6355 }
6356
6357 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6358                                      struct intel_crtc_state *crtc_state,
6359                                      struct dpll *reduced_clock)
6360 {
6361         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6362         u32 fp, fp2 = 0;
6363
6364         if (IS_PINEVIEW(dev_priv)) {
6365                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6366                 if (reduced_clock)
6367                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6368         } else {
6369                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6370                 if (reduced_clock)
6371                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6372         }
6373
6374         crtc_state->dpll_hw_state.fp0 = fp;
6375
6376         crtc->lowfreq_avail = false;
6377         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6378             reduced_clock) {
6379                 crtc_state->dpll_hw_state.fp1 = fp2;
6380                 crtc->lowfreq_avail = true;
6381         } else {
6382                 crtc_state->dpll_hw_state.fp1 = fp;
6383         }
6384 }
6385
6386 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6387                 pipe)
6388 {
6389         u32 reg_val;
6390
6391         /*
6392          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6393          * and set it to a reasonable value instead.
6394          */
6395         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6396         reg_val &= 0xffffff00;
6397         reg_val |= 0x00000030;
6398         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6399
6400         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6401         reg_val &= 0x00ffffff;
6402         reg_val |= 0x8c000000;
6403         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6404
6405         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6406         reg_val &= 0xffffff00;
6407         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6408
6409         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6410         reg_val &= 0x00ffffff;
6411         reg_val |= 0xb0000000;
6412         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6413 }
6414
6415 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6416                                          struct intel_link_m_n *m_n)
6417 {
6418         struct drm_device *dev = crtc->base.dev;
6419         struct drm_i915_private *dev_priv = to_i915(dev);
6420         int pipe = crtc->pipe;
6421
6422         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6423         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6424         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6425         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6426 }
6427
6428 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6429                                          struct intel_link_m_n *m_n,
6430                                          struct intel_link_m_n *m2_n2)
6431 {
6432         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6433         int pipe = crtc->pipe;
6434         enum transcoder transcoder = crtc->config->cpu_transcoder;
6435
6436         if (INTEL_GEN(dev_priv) >= 5) {
6437                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6438                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6439                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6440                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6441                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6442                  * for gen < 8) and if DRRS is supported (to make sure the
6443                  * registers are not unnecessarily accessed).
6444                  */
6445                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6446                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6447                         I915_WRITE(PIPE_DATA_M2(transcoder),
6448                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6449                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6450                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6451                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6452                 }
6453         } else {
6454                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6455                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6456                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6457                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6458         }
6459 }
6460
6461 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6462 {
6463         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6464
6465         if (m_n == M1_N1) {
6466                 dp_m_n = &crtc->config->dp_m_n;
6467                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6468         } else if (m_n == M2_N2) {
6469
6470                 /*
6471                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6472                  * needs to be programmed into M1_N1.
6473                  */
6474                 dp_m_n = &crtc->config->dp_m2_n2;
6475         } else {
6476                 DRM_ERROR("Unsupported divider value\n");
6477                 return;
6478         }
6479
6480         if (crtc->config->has_pch_encoder)
6481                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6482         else
6483                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6484 }
6485
6486 static void vlv_compute_dpll(struct intel_crtc *crtc,
6487                              struct intel_crtc_state *pipe_config)
6488 {
6489         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6490                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6491         if (crtc->pipe != PIPE_A)
6492                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6493
6494         /* DPLL not used with DSI, but still need the rest set up */
6495         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6496                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6497                         DPLL_EXT_BUFFER_ENABLE_VLV;
6498
6499         pipe_config->dpll_hw_state.dpll_md =
6500                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6501 }
6502
6503 static void chv_compute_dpll(struct intel_crtc *crtc,
6504                              struct intel_crtc_state *pipe_config)
6505 {
6506         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6507                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6508         if (crtc->pipe != PIPE_A)
6509                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6510
6511         /* DPLL not used with DSI, but still need the rest set up */
6512         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6513                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6514
6515         pipe_config->dpll_hw_state.dpll_md =
6516                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6517 }
6518
6519 static void vlv_prepare_pll(struct intel_crtc *crtc,
6520                             const struct intel_crtc_state *pipe_config)
6521 {
6522         struct drm_device *dev = crtc->base.dev;
6523         struct drm_i915_private *dev_priv = to_i915(dev);
6524         enum pipe pipe = crtc->pipe;
6525         u32 mdiv;
6526         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6527         u32 coreclk, reg_val;
6528
6529         /* Enable Refclk */
6530         I915_WRITE(DPLL(pipe),
6531                    pipe_config->dpll_hw_state.dpll &
6532                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6533
6534         /* No need to actually set up the DPLL with DSI */
6535         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6536                 return;
6537
6538         mutex_lock(&dev_priv->sb_lock);
6539
6540         bestn = pipe_config->dpll.n;
6541         bestm1 = pipe_config->dpll.m1;
6542         bestm2 = pipe_config->dpll.m2;
6543         bestp1 = pipe_config->dpll.p1;
6544         bestp2 = pipe_config->dpll.p2;
6545
6546         /* See eDP HDMI DPIO driver vbios notes doc */
6547
6548         /* PLL B needs special handling */
6549         if (pipe == PIPE_B)
6550                 vlv_pllb_recal_opamp(dev_priv, pipe);
6551
6552         /* Set up Tx target for periodic Rcomp update */
6553         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6554
6555         /* Disable target IRef on PLL */
6556         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6557         reg_val &= 0x00ffffff;
6558         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6559
6560         /* Disable fast lock */
6561         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6562
6563         /* Set idtafcrecal before PLL is enabled */
6564         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6565         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6566         mdiv |= ((bestn << DPIO_N_SHIFT));
6567         mdiv |= (1 << DPIO_K_SHIFT);
6568
6569         /*
6570          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6571          * but we don't support that).
6572          * Note: don't use the DAC post divider as it seems unstable.
6573          */
6574         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6575         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6576
6577         mdiv |= DPIO_ENABLE_CALIBRATION;
6578         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6579
6580         /* Set HBR and RBR LPF coefficients */
6581         if (pipe_config->port_clock == 162000 ||
6582             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6583             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6584                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6585                                  0x009f0003);
6586         else
6587                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6588                                  0x00d0000f);
6589
6590         if (intel_crtc_has_dp_encoder(pipe_config)) {
6591                 /* Use SSC source */
6592                 if (pipe == PIPE_A)
6593                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6594                                          0x0df40000);
6595                 else
6596                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6597                                          0x0df70000);
6598         } else { /* HDMI or VGA */
6599                 /* Use bend source */
6600                 if (pipe == PIPE_A)
6601                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6602                                          0x0df70000);
6603                 else
6604                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6605                                          0x0df40000);
6606         }
6607
6608         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6609         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6610         if (intel_crtc_has_dp_encoder(crtc->config))
6611                 coreclk |= 0x01000000;
6612         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6613
6614         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6615         mutex_unlock(&dev_priv->sb_lock);
6616 }
6617
6618 static void chv_prepare_pll(struct intel_crtc *crtc,
6619                             const struct intel_crtc_state *pipe_config)
6620 {
6621         struct drm_device *dev = crtc->base.dev;
6622         struct drm_i915_private *dev_priv = to_i915(dev);
6623         enum pipe pipe = crtc->pipe;
6624         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6625         u32 loopfilter, tribuf_calcntr;
6626         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6627         u32 dpio_val;
6628         int vco;
6629
6630         /* Enable Refclk and SSC */
6631         I915_WRITE(DPLL(pipe),
6632                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6633
6634         /* No need to actually set up the DPLL with DSI */
6635         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6636                 return;
6637
6638         bestn = pipe_config->dpll.n;
6639         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6640         bestm1 = pipe_config->dpll.m1;
6641         bestm2 = pipe_config->dpll.m2 >> 22;
6642         bestp1 = pipe_config->dpll.p1;
6643         bestp2 = pipe_config->dpll.p2;
6644         vco = pipe_config->dpll.vco;
6645         dpio_val = 0;
6646         loopfilter = 0;
6647
6648         mutex_lock(&dev_priv->sb_lock);
6649
6650         /* p1 and p2 divider */
6651         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6652                         5 << DPIO_CHV_S1_DIV_SHIFT |
6653                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6654                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6655                         1 << DPIO_CHV_K_DIV_SHIFT);
6656
6657         /* Feedback post-divider - m2 */
6658         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6659
6660         /* Feedback refclk divider - n and m1 */
6661         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6662                         DPIO_CHV_M1_DIV_BY_2 |
6663                         1 << DPIO_CHV_N_DIV_SHIFT);
6664
6665         /* M2 fraction division */
6666         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6667
6668         /* M2 fraction division enable */
6669         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6670         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6671         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6672         if (bestm2_frac)
6673                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6674         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6675
6676         /* Program digital lock detect threshold */
6677         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6678         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6679                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6680         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6681         if (!bestm2_frac)
6682                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6683         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6684
6685         /* Loop filter */
6686         if (vco == 5400000) {
6687                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6688                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6689                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6690                 tribuf_calcntr = 0x9;
6691         } else if (vco <= 6200000) {
6692                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6693                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6694                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6695                 tribuf_calcntr = 0x9;
6696         } else if (vco <= 6480000) {
6697                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6698                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6699                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6700                 tribuf_calcntr = 0x8;
6701         } else {
6702                 /* Not supported. Apply the same limits as in the max case */
6703                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6704                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6705                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6706                 tribuf_calcntr = 0;
6707         }
6708         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6709
6710         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6711         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6712         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6713         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6714
6715         /* AFC Recal */
6716         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6717                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6718                         DPIO_AFC_RECAL);
6719
6720         mutex_unlock(&dev_priv->sb_lock);
6721 }
6722
6723 /**
6724  * vlv_force_pll_on - forcibly enable just the PLL
6725  * @dev_priv: i915 private structure
6726  * @pipe: pipe PLL to enable
6727  * @dpll: PLL configuration
6728  *
6729  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6730  * in cases where we need the PLL enabled even when @pipe is not going to
6731  * be enabled.
6732  */
6733 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6734                      const struct dpll *dpll)
6735 {
6736         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6737         struct intel_crtc_state *pipe_config;
6738
6739         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6740         if (!pipe_config)
6741                 return -ENOMEM;
6742
6743         pipe_config->base.crtc = &crtc->base;
6744         pipe_config->pixel_multiplier = 1;
6745         pipe_config->dpll = *dpll;
6746
6747         if (IS_CHERRYVIEW(dev_priv)) {
6748                 chv_compute_dpll(crtc, pipe_config);
6749                 chv_prepare_pll(crtc, pipe_config);
6750                 chv_enable_pll(crtc, pipe_config);
6751         } else {
6752                 vlv_compute_dpll(crtc, pipe_config);
6753                 vlv_prepare_pll(crtc, pipe_config);
6754                 vlv_enable_pll(crtc, pipe_config);
6755         }
6756
6757         kfree(pipe_config);
6758
6759         return 0;
6760 }
6761
6762 /**
6763  * vlv_force_pll_off - forcibly disable just the PLL
6764  * @dev_priv: i915 private structure
6765  * @pipe: pipe PLL to disable
6766  *
6767  * Disable the PLL for @pipe. To be used in cases where we need
6768  * the PLL enabled even when @pipe is not going to be enabled.
6769  */
6770 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
6771 {
6772         if (IS_CHERRYVIEW(dev_priv))
6773                 chv_disable_pll(dev_priv, pipe);
6774         else
6775                 vlv_disable_pll(dev_priv, pipe);
6776 }
6777
6778 static void i9xx_compute_dpll(struct intel_crtc *crtc,
6779                               struct intel_crtc_state *crtc_state,
6780                               struct dpll *reduced_clock)
6781 {
6782         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6783         u32 dpll;
6784         struct dpll *clock = &crtc_state->dpll;
6785
6786         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6787
6788         dpll = DPLL_VGA_MODE_DIS;
6789
6790         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
6791                 dpll |= DPLLB_MODE_LVDS;
6792         else
6793                 dpll |= DPLLB_MODE_DAC_SERIAL;
6794
6795         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
6796             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
6797                 dpll |= (crtc_state->pixel_multiplier - 1)
6798                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6799         }
6800
6801         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
6802             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
6803                 dpll |= DPLL_SDVO_HIGH_SPEED;
6804
6805         if (intel_crtc_has_dp_encoder(crtc_state))
6806                 dpll |= DPLL_SDVO_HIGH_SPEED;
6807
6808         /* compute bitmask from p1 value */
6809         if (IS_PINEVIEW(dev_priv))
6810                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6811         else {
6812                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6813                 if (IS_G4X(dev_priv) && reduced_clock)
6814                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6815         }
6816         switch (clock->p2) {
6817         case 5:
6818                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6819                 break;
6820         case 7:
6821                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6822                 break;
6823         case 10:
6824                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6825                 break;
6826         case 14:
6827                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6828                 break;
6829         }
6830         if (INTEL_GEN(dev_priv) >= 4)
6831                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6832
6833         if (crtc_state->sdvo_tv_clock)
6834                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6835         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6836                  intel_panel_use_ssc(dev_priv))
6837                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6838         else
6839                 dpll |= PLL_REF_INPUT_DREFCLK;
6840
6841         dpll |= DPLL_VCO_ENABLE;
6842         crtc_state->dpll_hw_state.dpll = dpll;
6843
6844         if (INTEL_GEN(dev_priv) >= 4) {
6845                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6846                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6847                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
6848         }
6849 }
6850
6851 static void i8xx_compute_dpll(struct intel_crtc *crtc,
6852                               struct intel_crtc_state *crtc_state,
6853                               struct dpll *reduced_clock)
6854 {
6855         struct drm_device *dev = crtc->base.dev;
6856         struct drm_i915_private *dev_priv = to_i915(dev);
6857         u32 dpll;
6858         struct dpll *clock = &crtc_state->dpll;
6859
6860         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6861
6862         dpll = DPLL_VGA_MODE_DIS;
6863
6864         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
6865                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6866         } else {
6867                 if (clock->p1 == 2)
6868                         dpll |= PLL_P1_DIVIDE_BY_TWO;
6869                 else
6870                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6871                 if (clock->p2 == 4)
6872                         dpll |= PLL_P2_DIVIDE_BY_4;
6873         }
6874
6875         if (!IS_I830(dev_priv) &&
6876             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
6877                 dpll |= DPLL_DVO_2X_MODE;
6878
6879         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6880             intel_panel_use_ssc(dev_priv))
6881                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6882         else
6883                 dpll |= PLL_REF_INPUT_DREFCLK;
6884
6885         dpll |= DPLL_VCO_ENABLE;
6886         crtc_state->dpll_hw_state.dpll = dpll;
6887 }
6888
6889 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
6890 {
6891         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
6892         enum pipe pipe = intel_crtc->pipe;
6893         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
6894         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
6895         uint32_t crtc_vtotal, crtc_vblank_end;
6896         int vsyncshift = 0;
6897
6898         /* We need to be careful not to changed the adjusted mode, for otherwise
6899          * the hw state checker will get angry at the mismatch. */
6900         crtc_vtotal = adjusted_mode->crtc_vtotal;
6901         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
6902
6903         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
6904                 /* the chip adds 2 halflines automatically */
6905                 crtc_vtotal -= 1;
6906                 crtc_vblank_end -= 1;
6907
6908                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
6909                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
6910                 else
6911                         vsyncshift = adjusted_mode->crtc_hsync_start -
6912                                 adjusted_mode->crtc_htotal / 2;
6913                 if (vsyncshift < 0)
6914                         vsyncshift += adjusted_mode->crtc_htotal;
6915         }
6916
6917         if (INTEL_GEN(dev_priv) > 3)
6918                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
6919
6920         I915_WRITE(HTOTAL(cpu_transcoder),
6921                    (adjusted_mode->crtc_hdisplay - 1) |
6922                    ((adjusted_mode->crtc_htotal - 1) << 16));
6923         I915_WRITE(HBLANK(cpu_transcoder),
6924                    (adjusted_mode->crtc_hblank_start - 1) |
6925                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
6926         I915_WRITE(HSYNC(cpu_transcoder),
6927                    (adjusted_mode->crtc_hsync_start - 1) |
6928                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
6929
6930         I915_WRITE(VTOTAL(cpu_transcoder),
6931                    (adjusted_mode->crtc_vdisplay - 1) |
6932                    ((crtc_vtotal - 1) << 16));
6933         I915_WRITE(VBLANK(cpu_transcoder),
6934                    (adjusted_mode->crtc_vblank_start - 1) |
6935                    ((crtc_vblank_end - 1) << 16));
6936         I915_WRITE(VSYNC(cpu_transcoder),
6937                    (adjusted_mode->crtc_vsync_start - 1) |
6938                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
6939
6940         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
6941          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
6942          * documented on the DDI_FUNC_CTL register description, EDP Input Select
6943          * bits. */
6944         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
6945             (pipe == PIPE_B || pipe == PIPE_C))
6946                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
6947
6948 }
6949
6950 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
6951 {
6952         struct drm_device *dev = intel_crtc->base.dev;
6953         struct drm_i915_private *dev_priv = to_i915(dev);
6954         enum pipe pipe = intel_crtc->pipe;
6955
6956         /* pipesrc controls the size that is scaled from, which should
6957          * always be the user's requested size.
6958          */
6959         I915_WRITE(PIPESRC(pipe),
6960                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
6961                    (intel_crtc->config->pipe_src_h - 1));
6962 }
6963
6964 static void intel_get_pipe_timings(struct intel_crtc *crtc,
6965                                    struct intel_crtc_state *pipe_config)
6966 {
6967         struct drm_device *dev = crtc->base.dev;
6968         struct drm_i915_private *dev_priv = to_i915(dev);
6969         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6970         uint32_t tmp;
6971
6972         tmp = I915_READ(HTOTAL(cpu_transcoder));
6973         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
6974         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
6975         tmp = I915_READ(HBLANK(cpu_transcoder));
6976         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
6977         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
6978         tmp = I915_READ(HSYNC(cpu_transcoder));
6979         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
6980         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
6981
6982         tmp = I915_READ(VTOTAL(cpu_transcoder));
6983         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
6984         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
6985         tmp = I915_READ(VBLANK(cpu_transcoder));
6986         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
6987         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
6988         tmp = I915_READ(VSYNC(cpu_transcoder));
6989         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
6990         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
6991
6992         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
6993                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
6994                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
6995                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
6996         }
6997 }
6998
6999 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7000                                     struct intel_crtc_state *pipe_config)
7001 {
7002         struct drm_device *dev = crtc->base.dev;
7003         struct drm_i915_private *dev_priv = to_i915(dev);
7004         u32 tmp;
7005
7006         tmp = I915_READ(PIPESRC(crtc->pipe));
7007         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7008         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7009
7010         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7011         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7012 }
7013
7014 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7015                                  struct intel_crtc_state *pipe_config)
7016 {
7017         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7018         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7019         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7020         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7021
7022         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7023         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7024         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7025         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7026
7027         mode->flags = pipe_config->base.adjusted_mode.flags;
7028         mode->type = DRM_MODE_TYPE_DRIVER;
7029
7030         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7031
7032         mode->hsync = drm_mode_hsync(mode);
7033         mode->vrefresh = drm_mode_vrefresh(mode);
7034         drm_mode_set_name(mode);
7035 }
7036
7037 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7038 {
7039         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7040         uint32_t pipeconf;
7041
7042         pipeconf = 0;
7043
7044         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7045             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7046                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7047
7048         if (intel_crtc->config->double_wide)
7049                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7050
7051         /* only g4x and later have fancy bpc/dither controls */
7052         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7053             IS_CHERRYVIEW(dev_priv)) {
7054                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7055                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7056                         pipeconf |= PIPECONF_DITHER_EN |
7057                                     PIPECONF_DITHER_TYPE_SP;
7058
7059                 switch (intel_crtc->config->pipe_bpp) {
7060                 case 18:
7061                         pipeconf |= PIPECONF_6BPC;
7062                         break;
7063                 case 24:
7064                         pipeconf |= PIPECONF_8BPC;
7065                         break;
7066                 case 30:
7067                         pipeconf |= PIPECONF_10BPC;
7068                         break;
7069                 default:
7070                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7071                         BUG();
7072                 }
7073         }
7074
7075         if (HAS_PIPE_CXSR(dev_priv)) {
7076                 if (intel_crtc->lowfreq_avail) {
7077                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7078                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7079                 } else {
7080                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7081                 }
7082         }
7083
7084         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7085                 if (INTEL_GEN(dev_priv) < 4 ||
7086                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7087                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7088                 else
7089                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7090         } else
7091                 pipeconf |= PIPECONF_PROGRESSIVE;
7092
7093         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7094              intel_crtc->config->limited_color_range)
7095                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7096
7097         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7098         POSTING_READ(PIPECONF(intel_crtc->pipe));
7099 }
7100
7101 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7102                                    struct intel_crtc_state *crtc_state)
7103 {
7104         struct drm_device *dev = crtc->base.dev;
7105         struct drm_i915_private *dev_priv = to_i915(dev);
7106         const struct intel_limit *limit;
7107         int refclk = 48000;
7108
7109         memset(&crtc_state->dpll_hw_state, 0,
7110                sizeof(crtc_state->dpll_hw_state));
7111
7112         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7113                 if (intel_panel_use_ssc(dev_priv)) {
7114                         refclk = dev_priv->vbt.lvds_ssc_freq;
7115                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7116                 }
7117
7118                 limit = &intel_limits_i8xx_lvds;
7119         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7120                 limit = &intel_limits_i8xx_dvo;
7121         } else {
7122                 limit = &intel_limits_i8xx_dac;
7123         }
7124
7125         if (!crtc_state->clock_set &&
7126             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7127                                  refclk, NULL, &crtc_state->dpll)) {
7128                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7129                 return -EINVAL;
7130         }
7131
7132         i8xx_compute_dpll(crtc, crtc_state, NULL);
7133
7134         return 0;
7135 }
7136
7137 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7138                                   struct intel_crtc_state *crtc_state)
7139 {
7140         struct drm_device *dev = crtc->base.dev;
7141         struct drm_i915_private *dev_priv = to_i915(dev);
7142         const struct intel_limit *limit;
7143         int refclk = 96000;
7144
7145         memset(&crtc_state->dpll_hw_state, 0,
7146                sizeof(crtc_state->dpll_hw_state));
7147
7148         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7149                 if (intel_panel_use_ssc(dev_priv)) {
7150                         refclk = dev_priv->vbt.lvds_ssc_freq;
7151                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7152                 }
7153
7154                 if (intel_is_dual_link_lvds(dev))
7155                         limit = &intel_limits_g4x_dual_channel_lvds;
7156                 else
7157                         limit = &intel_limits_g4x_single_channel_lvds;
7158         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7159                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7160                 limit = &intel_limits_g4x_hdmi;
7161         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7162                 limit = &intel_limits_g4x_sdvo;
7163         } else {
7164                 /* The option is for other outputs */
7165                 limit = &intel_limits_i9xx_sdvo;
7166         }
7167
7168         if (!crtc_state->clock_set &&
7169             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7170                                 refclk, NULL, &crtc_state->dpll)) {
7171                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7172                 return -EINVAL;
7173         }
7174
7175         i9xx_compute_dpll(crtc, crtc_state, NULL);
7176
7177         return 0;
7178 }
7179
7180 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7181                                   struct intel_crtc_state *crtc_state)
7182 {
7183         struct drm_device *dev = crtc->base.dev;
7184         struct drm_i915_private *dev_priv = to_i915(dev);
7185         const struct intel_limit *limit;
7186         int refclk = 96000;
7187
7188         memset(&crtc_state->dpll_hw_state, 0,
7189                sizeof(crtc_state->dpll_hw_state));
7190
7191         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7192                 if (intel_panel_use_ssc(dev_priv)) {
7193                         refclk = dev_priv->vbt.lvds_ssc_freq;
7194                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7195                 }
7196
7197                 limit = &intel_limits_pineview_lvds;
7198         } else {
7199                 limit = &intel_limits_pineview_sdvo;
7200         }
7201
7202         if (!crtc_state->clock_set &&
7203             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7204                                 refclk, NULL, &crtc_state->dpll)) {
7205                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7206                 return -EINVAL;
7207         }
7208
7209         i9xx_compute_dpll(crtc, crtc_state, NULL);
7210
7211         return 0;
7212 }
7213
7214 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7215                                    struct intel_crtc_state *crtc_state)
7216 {
7217         struct drm_device *dev = crtc->base.dev;
7218         struct drm_i915_private *dev_priv = to_i915(dev);
7219         const struct intel_limit *limit;
7220         int refclk = 96000;
7221
7222         memset(&crtc_state->dpll_hw_state, 0,
7223                sizeof(crtc_state->dpll_hw_state));
7224
7225         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7226                 if (intel_panel_use_ssc(dev_priv)) {
7227                         refclk = dev_priv->vbt.lvds_ssc_freq;
7228                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7229                 }
7230
7231                 limit = &intel_limits_i9xx_lvds;
7232         } else {
7233                 limit = &intel_limits_i9xx_sdvo;
7234         }
7235
7236         if (!crtc_state->clock_set &&
7237             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7238                                  refclk, NULL, &crtc_state->dpll)) {
7239                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7240                 return -EINVAL;
7241         }
7242
7243         i9xx_compute_dpll(crtc, crtc_state, NULL);
7244
7245         return 0;
7246 }
7247
7248 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7249                                   struct intel_crtc_state *crtc_state)
7250 {
7251         int refclk = 100000;
7252         const struct intel_limit *limit = &intel_limits_chv;
7253
7254         memset(&crtc_state->dpll_hw_state, 0,
7255                sizeof(crtc_state->dpll_hw_state));
7256
7257         if (!crtc_state->clock_set &&
7258             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7259                                 refclk, NULL, &crtc_state->dpll)) {
7260                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7261                 return -EINVAL;
7262         }
7263
7264         chv_compute_dpll(crtc, crtc_state);
7265
7266         return 0;
7267 }
7268
7269 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7270                                   struct intel_crtc_state *crtc_state)
7271 {
7272         int refclk = 100000;
7273         const struct intel_limit *limit = &intel_limits_vlv;
7274
7275         memset(&crtc_state->dpll_hw_state, 0,
7276                sizeof(crtc_state->dpll_hw_state));
7277
7278         if (!crtc_state->clock_set &&
7279             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7280                                 refclk, NULL, &crtc_state->dpll)) {
7281                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7282                 return -EINVAL;
7283         }
7284
7285         vlv_compute_dpll(crtc, crtc_state);
7286
7287         return 0;
7288 }
7289
7290 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7291                                  struct intel_crtc_state *pipe_config)
7292 {
7293         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7294         uint32_t tmp;
7295
7296         if (INTEL_GEN(dev_priv) <= 3 &&
7297             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7298                 return;
7299
7300         tmp = I915_READ(PFIT_CONTROL);
7301         if (!(tmp & PFIT_ENABLE))
7302                 return;
7303
7304         /* Check whether the pfit is attached to our pipe. */
7305         if (INTEL_GEN(dev_priv) < 4) {
7306                 if (crtc->pipe != PIPE_B)
7307                         return;
7308         } else {
7309                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7310                         return;
7311         }
7312
7313         pipe_config->gmch_pfit.control = tmp;
7314         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7315 }
7316
7317 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7318                                struct intel_crtc_state *pipe_config)
7319 {
7320         struct drm_device *dev = crtc->base.dev;
7321         struct drm_i915_private *dev_priv = to_i915(dev);
7322         int pipe = pipe_config->cpu_transcoder;
7323         struct dpll clock;
7324         u32 mdiv;
7325         int refclk = 100000;
7326
7327         /* In case of DSI, DPLL will not be used */
7328         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7329                 return;
7330
7331         mutex_lock(&dev_priv->sb_lock);
7332         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7333         mutex_unlock(&dev_priv->sb_lock);
7334
7335         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7336         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7337         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7338         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7339         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7340
7341         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7342 }
7343
7344 static void
7345 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7346                               struct intel_initial_plane_config *plane_config)
7347 {
7348         struct drm_device *dev = crtc->base.dev;
7349         struct drm_i915_private *dev_priv = to_i915(dev);
7350         u32 val, base, offset;
7351         int pipe = crtc->pipe, plane = crtc->plane;
7352         int fourcc, pixel_format;
7353         unsigned int aligned_height;
7354         struct drm_framebuffer *fb;
7355         struct intel_framebuffer *intel_fb;
7356
7357         val = I915_READ(DSPCNTR(plane));
7358         if (!(val & DISPLAY_PLANE_ENABLE))
7359                 return;
7360
7361         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7362         if (!intel_fb) {
7363                 DRM_DEBUG_KMS("failed to alloc fb\n");
7364                 return;
7365         }
7366
7367         fb = &intel_fb->base;
7368
7369         fb->dev = dev;
7370
7371         if (INTEL_GEN(dev_priv) >= 4) {
7372                 if (val & DISPPLANE_TILED) {
7373                         plane_config->tiling = I915_TILING_X;
7374                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7375                 }
7376         }
7377
7378         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7379         fourcc = i9xx_format_to_fourcc(pixel_format);
7380         fb->format = drm_format_info(fourcc);
7381
7382         if (INTEL_GEN(dev_priv) >= 4) {
7383                 if (plane_config->tiling)
7384                         offset = I915_READ(DSPTILEOFF(plane));
7385                 else
7386                         offset = I915_READ(DSPLINOFF(plane));
7387                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7388         } else {
7389                 base = I915_READ(DSPADDR(plane));
7390         }
7391         plane_config->base = base;
7392
7393         val = I915_READ(PIPESRC(pipe));
7394         fb->width = ((val >> 16) & 0xfff) + 1;
7395         fb->height = ((val >> 0) & 0xfff) + 1;
7396
7397         val = I915_READ(DSPSTRIDE(pipe));
7398         fb->pitches[0] = val & 0xffffffc0;
7399
7400         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7401
7402         plane_config->size = fb->pitches[0] * aligned_height;
7403
7404         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7405                       pipe_name(pipe), plane, fb->width, fb->height,
7406                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7407                       plane_config->size);
7408
7409         plane_config->fb = intel_fb;
7410 }
7411
7412 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7413                                struct intel_crtc_state *pipe_config)
7414 {
7415         struct drm_device *dev = crtc->base.dev;
7416         struct drm_i915_private *dev_priv = to_i915(dev);
7417         int pipe = pipe_config->cpu_transcoder;
7418         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7419         struct dpll clock;
7420         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7421         int refclk = 100000;
7422
7423         /* In case of DSI, DPLL will not be used */
7424         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7425                 return;
7426
7427         mutex_lock(&dev_priv->sb_lock);
7428         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7429         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7430         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7431         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7432         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7433         mutex_unlock(&dev_priv->sb_lock);
7434
7435         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7436         clock.m2 = (pll_dw0 & 0xff) << 22;
7437         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7438                 clock.m2 |= pll_dw2 & 0x3fffff;
7439         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7440         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7441         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7442
7443         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7444 }
7445
7446 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7447                                  struct intel_crtc_state *pipe_config)
7448 {
7449         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7450         enum intel_display_power_domain power_domain;
7451         uint32_t tmp;
7452         bool ret;
7453
7454         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7455         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7456                 return false;
7457
7458         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7459         pipe_config->shared_dpll = NULL;
7460
7461         ret = false;
7462
7463         tmp = I915_READ(PIPECONF(crtc->pipe));
7464         if (!(tmp & PIPECONF_ENABLE))
7465                 goto out;
7466
7467         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7468             IS_CHERRYVIEW(dev_priv)) {
7469                 switch (tmp & PIPECONF_BPC_MASK) {
7470                 case PIPECONF_6BPC:
7471                         pipe_config->pipe_bpp = 18;
7472                         break;
7473                 case PIPECONF_8BPC:
7474                         pipe_config->pipe_bpp = 24;
7475                         break;
7476                 case PIPECONF_10BPC:
7477                         pipe_config->pipe_bpp = 30;
7478                         break;
7479                 default:
7480                         break;
7481                 }
7482         }
7483
7484         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7485             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7486                 pipe_config->limited_color_range = true;
7487
7488         if (INTEL_GEN(dev_priv) < 4)
7489                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7490
7491         intel_get_pipe_timings(crtc, pipe_config);
7492         intel_get_pipe_src_size(crtc, pipe_config);
7493
7494         i9xx_get_pfit_config(crtc, pipe_config);
7495
7496         if (INTEL_GEN(dev_priv) >= 4) {
7497                 /* No way to read it out on pipes B and C */
7498                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7499                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7500                 else
7501                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7502                 pipe_config->pixel_multiplier =
7503                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7504                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7505                 pipe_config->dpll_hw_state.dpll_md = tmp;
7506         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7507                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7508                 tmp = I915_READ(DPLL(crtc->pipe));
7509                 pipe_config->pixel_multiplier =
7510                         ((tmp & SDVO_MULTIPLIER_MASK)
7511                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7512         } else {
7513                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7514                  * port and will be fixed up in the encoder->get_config
7515                  * function. */
7516                 pipe_config->pixel_multiplier = 1;
7517         }
7518         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7519         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7520                 /*
7521                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7522                  * on 830. Filter it out here so that we don't
7523                  * report errors due to that.
7524                  */
7525                 if (IS_I830(dev_priv))
7526                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7527
7528                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7529                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7530         } else {
7531                 /* Mask out read-only status bits. */
7532                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7533                                                      DPLL_PORTC_READY_MASK |
7534                                                      DPLL_PORTB_READY_MASK);
7535         }
7536
7537         if (IS_CHERRYVIEW(dev_priv))
7538                 chv_crtc_clock_get(crtc, pipe_config);
7539         else if (IS_VALLEYVIEW(dev_priv))
7540                 vlv_crtc_clock_get(crtc, pipe_config);
7541         else
7542                 i9xx_crtc_clock_get(crtc, pipe_config);
7543
7544         /*
7545          * Normally the dotclock is filled in by the encoder .get_config()
7546          * but in case the pipe is enabled w/o any ports we need a sane
7547          * default.
7548          */
7549         pipe_config->base.adjusted_mode.crtc_clock =
7550                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7551
7552         ret = true;
7553
7554 out:
7555         intel_display_power_put(dev_priv, power_domain);
7556
7557         return ret;
7558 }
7559
7560 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7561 {
7562         struct intel_encoder *encoder;
7563         int i;
7564         u32 val, final;
7565         bool has_lvds = false;
7566         bool has_cpu_edp = false;
7567         bool has_panel = false;
7568         bool has_ck505 = false;
7569         bool can_ssc = false;
7570         bool using_ssc_source = false;
7571
7572         /* We need to take the global config into account */
7573         for_each_intel_encoder(&dev_priv->drm, encoder) {
7574                 switch (encoder->type) {
7575                 case INTEL_OUTPUT_LVDS:
7576                         has_panel = true;
7577                         has_lvds = true;
7578                         break;
7579                 case INTEL_OUTPUT_EDP:
7580                         has_panel = true;
7581                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
7582                                 has_cpu_edp = true;
7583                         break;
7584                 default:
7585                         break;
7586                 }
7587         }
7588
7589         if (HAS_PCH_IBX(dev_priv)) {
7590                 has_ck505 = dev_priv->vbt.display_clock_mode;
7591                 can_ssc = has_ck505;
7592         } else {
7593                 has_ck505 = false;
7594                 can_ssc = true;
7595         }
7596
7597         /* Check if any DPLLs are using the SSC source */
7598         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7599                 u32 temp = I915_READ(PCH_DPLL(i));
7600
7601                 if (!(temp & DPLL_VCO_ENABLE))
7602                         continue;
7603
7604                 if ((temp & PLL_REF_INPUT_MASK) ==
7605                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7606                         using_ssc_source = true;
7607                         break;
7608                 }
7609         }
7610
7611         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7612                       has_panel, has_lvds, has_ck505, using_ssc_source);
7613
7614         /* Ironlake: try to setup display ref clock before DPLL
7615          * enabling. This is only under driver's control after
7616          * PCH B stepping, previous chipset stepping should be
7617          * ignoring this setting.
7618          */
7619         val = I915_READ(PCH_DREF_CONTROL);
7620
7621         /* As we must carefully and slowly disable/enable each source in turn,
7622          * compute the final state we want first and check if we need to
7623          * make any changes at all.
7624          */
7625         final = val;
7626         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7627         if (has_ck505)
7628                 final |= DREF_NONSPREAD_CK505_ENABLE;
7629         else
7630                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7631
7632         final &= ~DREF_SSC_SOURCE_MASK;
7633         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7634         final &= ~DREF_SSC1_ENABLE;
7635
7636         if (has_panel) {
7637                 final |= DREF_SSC_SOURCE_ENABLE;
7638
7639                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7640                         final |= DREF_SSC1_ENABLE;
7641
7642                 if (has_cpu_edp) {
7643                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7644                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7645                         else
7646                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7647                 } else
7648                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7649         } else if (using_ssc_source) {
7650                 final |= DREF_SSC_SOURCE_ENABLE;
7651                 final |= DREF_SSC1_ENABLE;
7652         }
7653
7654         if (final == val)
7655                 return;
7656
7657         /* Always enable nonspread source */
7658         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7659
7660         if (has_ck505)
7661                 val |= DREF_NONSPREAD_CK505_ENABLE;
7662         else
7663                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7664
7665         if (has_panel) {
7666                 val &= ~DREF_SSC_SOURCE_MASK;
7667                 val |= DREF_SSC_SOURCE_ENABLE;
7668
7669                 /* SSC must be turned on before enabling the CPU output  */
7670                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7671                         DRM_DEBUG_KMS("Using SSC on panel\n");
7672                         val |= DREF_SSC1_ENABLE;
7673                 } else
7674                         val &= ~DREF_SSC1_ENABLE;
7675
7676                 /* Get SSC going before enabling the outputs */
7677                 I915_WRITE(PCH_DREF_CONTROL, val);
7678                 POSTING_READ(PCH_DREF_CONTROL);
7679                 udelay(200);
7680
7681                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7682
7683                 /* Enable CPU source on CPU attached eDP */
7684                 if (has_cpu_edp) {
7685                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7686                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7687                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7688                         } else
7689                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7690                 } else
7691                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7692
7693                 I915_WRITE(PCH_DREF_CONTROL, val);
7694                 POSTING_READ(PCH_DREF_CONTROL);
7695                 udelay(200);
7696         } else {
7697                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7698
7699                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7700
7701                 /* Turn off CPU output */
7702                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7703
7704                 I915_WRITE(PCH_DREF_CONTROL, val);
7705                 POSTING_READ(PCH_DREF_CONTROL);
7706                 udelay(200);
7707
7708                 if (!using_ssc_source) {
7709                         DRM_DEBUG_KMS("Disabling SSC source\n");
7710
7711                         /* Turn off the SSC source */
7712                         val &= ~DREF_SSC_SOURCE_MASK;
7713                         val |= DREF_SSC_SOURCE_DISABLE;
7714
7715                         /* Turn off SSC1 */
7716                         val &= ~DREF_SSC1_ENABLE;
7717
7718                         I915_WRITE(PCH_DREF_CONTROL, val);
7719                         POSTING_READ(PCH_DREF_CONTROL);
7720                         udelay(200);
7721                 }
7722         }
7723
7724         BUG_ON(val != final);
7725 }
7726
7727 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7728 {
7729         uint32_t tmp;
7730
7731         tmp = I915_READ(SOUTH_CHICKEN2);
7732         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7733         I915_WRITE(SOUTH_CHICKEN2, tmp);
7734
7735         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7736                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7737                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7738
7739         tmp = I915_READ(SOUTH_CHICKEN2);
7740         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7741         I915_WRITE(SOUTH_CHICKEN2, tmp);
7742
7743         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7744                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7745                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7746 }
7747
7748 /* WaMPhyProgramming:hsw */
7749 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7750 {
7751         uint32_t tmp;
7752
7753         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7754         tmp &= ~(0xFF << 24);
7755         tmp |= (0x12 << 24);
7756         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7757
7758         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7759         tmp |= (1 << 11);
7760         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7761
7762         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7763         tmp |= (1 << 11);
7764         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7765
7766         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7767         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7768         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7769
7770         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7771         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7772         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7773
7774         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7775         tmp &= ~(7 << 13);
7776         tmp |= (5 << 13);
7777         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7778
7779         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7780         tmp &= ~(7 << 13);
7781         tmp |= (5 << 13);
7782         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7783
7784         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7785         tmp &= ~0xFF;
7786         tmp |= 0x1C;
7787         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7788
7789         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7790         tmp &= ~0xFF;
7791         tmp |= 0x1C;
7792         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7793
7794         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7795         tmp &= ~(0xFF << 16);
7796         tmp |= (0x1C << 16);
7797         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7798
7799         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7800         tmp &= ~(0xFF << 16);
7801         tmp |= (0x1C << 16);
7802         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7803
7804         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7805         tmp |= (1 << 27);
7806         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7807
7808         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7809         tmp |= (1 << 27);
7810         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7811
7812         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7813         tmp &= ~(0xF << 28);
7814         tmp |= (4 << 28);
7815         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7816
7817         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7818         tmp &= ~(0xF << 28);
7819         tmp |= (4 << 28);
7820         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7821 }
7822
7823 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7824  * Programming" based on the parameters passed:
7825  * - Sequence to enable CLKOUT_DP
7826  * - Sequence to enable CLKOUT_DP without spread
7827  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7828  */
7829 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
7830                                  bool with_spread, bool with_fdi)
7831 {
7832         uint32_t reg, tmp;
7833
7834         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7835                 with_spread = true;
7836         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
7837             with_fdi, "LP PCH doesn't have FDI\n"))
7838                 with_fdi = false;
7839
7840         mutex_lock(&dev_priv->sb_lock);
7841
7842         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7843         tmp &= ~SBI_SSCCTL_DISABLE;
7844         tmp |= SBI_SSCCTL_PATHALT;
7845         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7846
7847         udelay(24);
7848
7849         if (with_spread) {
7850                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7851                 tmp &= ~SBI_SSCCTL_PATHALT;
7852                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7853
7854                 if (with_fdi) {
7855                         lpt_reset_fdi_mphy(dev_priv);
7856                         lpt_program_fdi_mphy(dev_priv);
7857                 }
7858         }
7859
7860         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7861         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7862         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7863         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7864
7865         mutex_unlock(&dev_priv->sb_lock);
7866 }
7867
7868 /* Sequence to disable CLKOUT_DP */
7869 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
7870 {
7871         uint32_t reg, tmp;
7872
7873         mutex_lock(&dev_priv->sb_lock);
7874
7875         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7876         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7877         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7878         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7879
7880         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7881         if (!(tmp & SBI_SSCCTL_DISABLE)) {
7882                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
7883                         tmp |= SBI_SSCCTL_PATHALT;
7884                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7885                         udelay(32);
7886                 }
7887                 tmp |= SBI_SSCCTL_DISABLE;
7888                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7889         }
7890
7891         mutex_unlock(&dev_priv->sb_lock);
7892 }
7893
7894 #define BEND_IDX(steps) ((50 + (steps)) / 5)
7895
7896 static const uint16_t sscdivintphase[] = {
7897         [BEND_IDX( 50)] = 0x3B23,
7898         [BEND_IDX( 45)] = 0x3B23,
7899         [BEND_IDX( 40)] = 0x3C23,
7900         [BEND_IDX( 35)] = 0x3C23,
7901         [BEND_IDX( 30)] = 0x3D23,
7902         [BEND_IDX( 25)] = 0x3D23,
7903         [BEND_IDX( 20)] = 0x3E23,
7904         [BEND_IDX( 15)] = 0x3E23,
7905         [BEND_IDX( 10)] = 0x3F23,
7906         [BEND_IDX(  5)] = 0x3F23,
7907         [BEND_IDX(  0)] = 0x0025,
7908         [BEND_IDX( -5)] = 0x0025,
7909         [BEND_IDX(-10)] = 0x0125,
7910         [BEND_IDX(-15)] = 0x0125,
7911         [BEND_IDX(-20)] = 0x0225,
7912         [BEND_IDX(-25)] = 0x0225,
7913         [BEND_IDX(-30)] = 0x0325,
7914         [BEND_IDX(-35)] = 0x0325,
7915         [BEND_IDX(-40)] = 0x0425,
7916         [BEND_IDX(-45)] = 0x0425,
7917         [BEND_IDX(-50)] = 0x0525,
7918 };
7919
7920 /*
7921  * Bend CLKOUT_DP
7922  * steps -50 to 50 inclusive, in steps of 5
7923  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
7924  * change in clock period = -(steps / 10) * 5.787 ps
7925  */
7926 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
7927 {
7928         uint32_t tmp;
7929         int idx = BEND_IDX(steps);
7930
7931         if (WARN_ON(steps % 5 != 0))
7932                 return;
7933
7934         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
7935                 return;
7936
7937         mutex_lock(&dev_priv->sb_lock);
7938
7939         if (steps % 10 != 0)
7940                 tmp = 0xAAAAAAAB;
7941         else
7942                 tmp = 0x00000000;
7943         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
7944
7945         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
7946         tmp &= 0xffff0000;
7947         tmp |= sscdivintphase[idx];
7948         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
7949
7950         mutex_unlock(&dev_priv->sb_lock);
7951 }
7952
7953 #undef BEND_IDX
7954
7955 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
7956 {
7957         struct intel_encoder *encoder;
7958         bool has_vga = false;
7959
7960         for_each_intel_encoder(&dev_priv->drm, encoder) {
7961                 switch (encoder->type) {
7962                 case INTEL_OUTPUT_ANALOG:
7963                         has_vga = true;
7964                         break;
7965                 default:
7966                         break;
7967                 }
7968         }
7969
7970         if (has_vga) {
7971                 lpt_bend_clkout_dp(dev_priv, 0);
7972                 lpt_enable_clkout_dp(dev_priv, true, true);
7973         } else {
7974                 lpt_disable_clkout_dp(dev_priv);
7975         }
7976 }
7977
7978 /*
7979  * Initialize reference clocks when the driver loads
7980  */
7981 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
7982 {
7983         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
7984                 ironlake_init_pch_refclk(dev_priv);
7985         else if (HAS_PCH_LPT(dev_priv))
7986                 lpt_init_pch_refclk(dev_priv);
7987 }
7988
7989 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
7990 {
7991         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
7992         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7993         int pipe = intel_crtc->pipe;
7994         uint32_t val;
7995
7996         val = 0;
7997
7998         switch (intel_crtc->config->pipe_bpp) {
7999         case 18:
8000                 val |= PIPECONF_6BPC;
8001                 break;
8002         case 24:
8003                 val |= PIPECONF_8BPC;
8004                 break;
8005         case 30:
8006                 val |= PIPECONF_10BPC;
8007                 break;
8008         case 36:
8009                 val |= PIPECONF_12BPC;
8010                 break;
8011         default:
8012                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8013                 BUG();
8014         }
8015
8016         if (intel_crtc->config->dither)
8017                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8018
8019         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8020                 val |= PIPECONF_INTERLACED_ILK;
8021         else
8022                 val |= PIPECONF_PROGRESSIVE;
8023
8024         if (intel_crtc->config->limited_color_range)
8025                 val |= PIPECONF_COLOR_RANGE_SELECT;
8026
8027         I915_WRITE(PIPECONF(pipe), val);
8028         POSTING_READ(PIPECONF(pipe));
8029 }
8030
8031 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8032 {
8033         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8034         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8035         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8036         u32 val = 0;
8037
8038         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8039                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8040
8041         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8042                 val |= PIPECONF_INTERLACED_ILK;
8043         else
8044                 val |= PIPECONF_PROGRESSIVE;
8045
8046         I915_WRITE(PIPECONF(cpu_transcoder), val);
8047         POSTING_READ(PIPECONF(cpu_transcoder));
8048 }
8049
8050 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8051 {
8052         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8053         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8054
8055         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8056                 u32 val = 0;
8057
8058                 switch (intel_crtc->config->pipe_bpp) {
8059                 case 18:
8060                         val |= PIPEMISC_DITHER_6_BPC;
8061                         break;
8062                 case 24:
8063                         val |= PIPEMISC_DITHER_8_BPC;
8064                         break;
8065                 case 30:
8066                         val |= PIPEMISC_DITHER_10_BPC;
8067                         break;
8068                 case 36:
8069                         val |= PIPEMISC_DITHER_12_BPC;
8070                         break;
8071                 default:
8072                         /* Case prevented by pipe_config_set_bpp. */
8073                         BUG();
8074                 }
8075
8076                 if (intel_crtc->config->dither)
8077                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8078
8079                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8080         }
8081 }
8082
8083 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8084 {
8085         /*
8086          * Account for spread spectrum to avoid
8087          * oversubscribing the link. Max center spread
8088          * is 2.5%; use 5% for safety's sake.
8089          */
8090         u32 bps = target_clock * bpp * 21 / 20;
8091         return DIV_ROUND_UP(bps, link_bw * 8);
8092 }
8093
8094 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8095 {
8096         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8097 }
8098
8099 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8100                                   struct intel_crtc_state *crtc_state,
8101                                   struct dpll *reduced_clock)
8102 {
8103         struct drm_crtc *crtc = &intel_crtc->base;
8104         struct drm_device *dev = crtc->dev;
8105         struct drm_i915_private *dev_priv = to_i915(dev);
8106         u32 dpll, fp, fp2;
8107         int factor;
8108
8109         /* Enable autotuning of the PLL clock (if permissible) */
8110         factor = 21;
8111         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8112                 if ((intel_panel_use_ssc(dev_priv) &&
8113                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8114                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8115                         factor = 25;
8116         } else if (crtc_state->sdvo_tv_clock)
8117                 factor = 20;
8118
8119         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8120
8121         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8122                 fp |= FP_CB_TUNE;
8123
8124         if (reduced_clock) {
8125                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8126
8127                 if (reduced_clock->m < factor * reduced_clock->n)
8128                         fp2 |= FP_CB_TUNE;
8129         } else {
8130                 fp2 = fp;
8131         }
8132
8133         dpll = 0;
8134
8135         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8136                 dpll |= DPLLB_MODE_LVDS;
8137         else
8138                 dpll |= DPLLB_MODE_DAC_SERIAL;
8139
8140         dpll |= (crtc_state->pixel_multiplier - 1)
8141                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8142
8143         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8144             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8145                 dpll |= DPLL_SDVO_HIGH_SPEED;
8146
8147         if (intel_crtc_has_dp_encoder(crtc_state))
8148                 dpll |= DPLL_SDVO_HIGH_SPEED;
8149
8150         /*
8151          * The high speed IO clock is only really required for
8152          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8153          * possible to share the DPLL between CRT and HDMI. Enabling
8154          * the clock needlessly does no real harm, except use up a
8155          * bit of power potentially.
8156          *
8157          * We'll limit this to IVB with 3 pipes, since it has only two
8158          * DPLLs and so DPLL sharing is the only way to get three pipes
8159          * driving PCH ports at the same time. On SNB we could do this,
8160          * and potentially avoid enabling the second DPLL, but it's not
8161          * clear if it''s a win or loss power wise. No point in doing
8162          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8163          */
8164         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8165             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8166                 dpll |= DPLL_SDVO_HIGH_SPEED;
8167
8168         /* compute bitmask from p1 value */
8169         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8170         /* also FPA1 */
8171         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8172
8173         switch (crtc_state->dpll.p2) {
8174         case 5:
8175                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8176                 break;
8177         case 7:
8178                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8179                 break;
8180         case 10:
8181                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8182                 break;
8183         case 14:
8184                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8185                 break;
8186         }
8187
8188         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8189             intel_panel_use_ssc(dev_priv))
8190                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8191         else
8192                 dpll |= PLL_REF_INPUT_DREFCLK;
8193
8194         dpll |= DPLL_VCO_ENABLE;
8195
8196         crtc_state->dpll_hw_state.dpll = dpll;
8197         crtc_state->dpll_hw_state.fp0 = fp;
8198         crtc_state->dpll_hw_state.fp1 = fp2;
8199 }
8200
8201 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8202                                        struct intel_crtc_state *crtc_state)
8203 {
8204         struct drm_device *dev = crtc->base.dev;
8205         struct drm_i915_private *dev_priv = to_i915(dev);
8206         const struct intel_limit *limit;
8207         int refclk = 120000;
8208
8209         memset(&crtc_state->dpll_hw_state, 0,
8210                sizeof(crtc_state->dpll_hw_state));
8211
8212         crtc->lowfreq_avail = false;
8213
8214         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8215         if (!crtc_state->has_pch_encoder)
8216                 return 0;
8217
8218         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8219                 if (intel_panel_use_ssc(dev_priv)) {
8220                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8221                                       dev_priv->vbt.lvds_ssc_freq);
8222                         refclk = dev_priv->vbt.lvds_ssc_freq;
8223                 }
8224
8225                 if (intel_is_dual_link_lvds(dev)) {
8226                         if (refclk == 100000)
8227                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8228                         else
8229                                 limit = &intel_limits_ironlake_dual_lvds;
8230                 } else {
8231                         if (refclk == 100000)
8232                                 limit = &intel_limits_ironlake_single_lvds_100m;
8233                         else
8234                                 limit = &intel_limits_ironlake_single_lvds;
8235                 }
8236         } else {
8237                 limit = &intel_limits_ironlake_dac;
8238         }
8239
8240         if (!crtc_state->clock_set &&
8241             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8242                                 refclk, NULL, &crtc_state->dpll)) {
8243                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8244                 return -EINVAL;
8245         }
8246
8247         ironlake_compute_dpll(crtc, crtc_state, NULL);
8248
8249         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8250                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8251                                  pipe_name(crtc->pipe));
8252                 return -EINVAL;
8253         }
8254
8255         return 0;
8256 }
8257
8258 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8259                                          struct intel_link_m_n *m_n)
8260 {
8261         struct drm_device *dev = crtc->base.dev;
8262         struct drm_i915_private *dev_priv = to_i915(dev);
8263         enum pipe pipe = crtc->pipe;
8264
8265         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8266         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8267         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8268                 & ~TU_SIZE_MASK;
8269         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8270         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8271                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8272 }
8273
8274 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8275                                          enum transcoder transcoder,
8276                                          struct intel_link_m_n *m_n,
8277                                          struct intel_link_m_n *m2_n2)
8278 {
8279         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8280         enum pipe pipe = crtc->pipe;
8281
8282         if (INTEL_GEN(dev_priv) >= 5) {
8283                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8284                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8285                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8286                         & ~TU_SIZE_MASK;
8287                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8288                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8289                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8290                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8291                  * gen < 8) and if DRRS is supported (to make sure the
8292                  * registers are not unnecessarily read).
8293                  */
8294                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8295                         crtc->config->has_drrs) {
8296                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8297                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8298                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8299                                         & ~TU_SIZE_MASK;
8300                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8301                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8302                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8303                 }
8304         } else {
8305                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8306                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8307                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8308                         & ~TU_SIZE_MASK;
8309                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8310                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8311                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8312         }
8313 }
8314
8315 void intel_dp_get_m_n(struct intel_crtc *crtc,
8316                       struct intel_crtc_state *pipe_config)
8317 {
8318         if (pipe_config->has_pch_encoder)
8319                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8320         else
8321                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8322                                              &pipe_config->dp_m_n,
8323                                              &pipe_config->dp_m2_n2);
8324 }
8325
8326 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8327                                         struct intel_crtc_state *pipe_config)
8328 {
8329         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8330                                      &pipe_config->fdi_m_n, NULL);
8331 }
8332
8333 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8334                                     struct intel_crtc_state *pipe_config)
8335 {
8336         struct drm_device *dev = crtc->base.dev;
8337         struct drm_i915_private *dev_priv = to_i915(dev);
8338         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8339         uint32_t ps_ctrl = 0;
8340         int id = -1;
8341         int i;
8342
8343         /* find scaler attached to this pipe */
8344         for (i = 0; i < crtc->num_scalers; i++) {
8345                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8346                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8347                         id = i;
8348                         pipe_config->pch_pfit.enabled = true;
8349                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8350                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8351                         break;
8352                 }
8353         }
8354
8355         scaler_state->scaler_id = id;
8356         if (id >= 0) {
8357                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8358         } else {
8359                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8360         }
8361 }
8362
8363 static void
8364 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8365                                  struct intel_initial_plane_config *plane_config)
8366 {
8367         struct drm_device *dev = crtc->base.dev;
8368         struct drm_i915_private *dev_priv = to_i915(dev);
8369         u32 val, base, offset, stride_mult, tiling;
8370         int pipe = crtc->pipe;
8371         int fourcc, pixel_format;
8372         unsigned int aligned_height;
8373         struct drm_framebuffer *fb;
8374         struct intel_framebuffer *intel_fb;
8375
8376         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8377         if (!intel_fb) {
8378                 DRM_DEBUG_KMS("failed to alloc fb\n");
8379                 return;
8380         }
8381
8382         fb = &intel_fb->base;
8383
8384         fb->dev = dev;
8385
8386         val = I915_READ(PLANE_CTL(pipe, 0));
8387         if (!(val & PLANE_CTL_ENABLE))
8388                 goto error;
8389
8390         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8391         fourcc = skl_format_to_fourcc(pixel_format,
8392                                       val & PLANE_CTL_ORDER_RGBX,
8393                                       val & PLANE_CTL_ALPHA_MASK);
8394         fb->format = drm_format_info(fourcc);
8395
8396         tiling = val & PLANE_CTL_TILED_MASK;
8397         switch (tiling) {
8398         case PLANE_CTL_TILED_LINEAR:
8399                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8400                 break;
8401         case PLANE_CTL_TILED_X:
8402                 plane_config->tiling = I915_TILING_X;
8403                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8404                 break;
8405         case PLANE_CTL_TILED_Y:
8406                 fb->modifier = I915_FORMAT_MOD_Y_TILED;
8407                 break;
8408         case PLANE_CTL_TILED_YF:
8409                 fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8410                 break;
8411         default:
8412                 MISSING_CASE(tiling);
8413                 goto error;
8414         }
8415
8416         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
8417         plane_config->base = base;
8418
8419         offset = I915_READ(PLANE_OFFSET(pipe, 0));
8420
8421         val = I915_READ(PLANE_SIZE(pipe, 0));
8422         fb->height = ((val >> 16) & 0xfff) + 1;
8423         fb->width = ((val >> 0) & 0x1fff) + 1;
8424
8425         val = I915_READ(PLANE_STRIDE(pipe, 0));
8426         stride_mult = intel_fb_stride_alignment(fb, 0);
8427         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8428
8429         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8430
8431         plane_config->size = fb->pitches[0] * aligned_height;
8432
8433         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8434                       pipe_name(pipe), fb->width, fb->height,
8435                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8436                       plane_config->size);
8437
8438         plane_config->fb = intel_fb;
8439         return;
8440
8441 error:
8442         kfree(intel_fb);
8443 }
8444
8445 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8446                                      struct intel_crtc_state *pipe_config)
8447 {
8448         struct drm_device *dev = crtc->base.dev;
8449         struct drm_i915_private *dev_priv = to_i915(dev);
8450         uint32_t tmp;
8451
8452         tmp = I915_READ(PF_CTL(crtc->pipe));
8453
8454         if (tmp & PF_ENABLE) {
8455                 pipe_config->pch_pfit.enabled = true;
8456                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8457                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8458
8459                 /* We currently do not free assignements of panel fitters on
8460                  * ivb/hsw (since we don't use the higher upscaling modes which
8461                  * differentiates them) so just WARN about this case for now. */
8462                 if (IS_GEN7(dev_priv)) {
8463                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8464                                 PF_PIPE_SEL_IVB(crtc->pipe));
8465                 }
8466         }
8467 }
8468
8469 static void
8470 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
8471                                   struct intel_initial_plane_config *plane_config)
8472 {
8473         struct drm_device *dev = crtc->base.dev;
8474         struct drm_i915_private *dev_priv = to_i915(dev);
8475         u32 val, base, offset;
8476         int pipe = crtc->pipe;
8477         int fourcc, pixel_format;
8478         unsigned int aligned_height;
8479         struct drm_framebuffer *fb;
8480         struct intel_framebuffer *intel_fb;
8481
8482         val = I915_READ(DSPCNTR(pipe));
8483         if (!(val & DISPLAY_PLANE_ENABLE))
8484                 return;
8485
8486         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8487         if (!intel_fb) {
8488                 DRM_DEBUG_KMS("failed to alloc fb\n");
8489                 return;
8490         }
8491
8492         fb = &intel_fb->base;
8493
8494         fb->dev = dev;
8495
8496         if (INTEL_GEN(dev_priv) >= 4) {
8497                 if (val & DISPPLANE_TILED) {
8498                         plane_config->tiling = I915_TILING_X;
8499                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8500                 }
8501         }
8502
8503         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8504         fourcc = i9xx_format_to_fourcc(pixel_format);
8505         fb->format = drm_format_info(fourcc);
8506
8507         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
8508         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8509                 offset = I915_READ(DSPOFFSET(pipe));
8510         } else {
8511                 if (plane_config->tiling)
8512                         offset = I915_READ(DSPTILEOFF(pipe));
8513                 else
8514                         offset = I915_READ(DSPLINOFF(pipe));
8515         }
8516         plane_config->base = base;
8517
8518         val = I915_READ(PIPESRC(pipe));
8519         fb->width = ((val >> 16) & 0xfff) + 1;
8520         fb->height = ((val >> 0) & 0xfff) + 1;
8521
8522         val = I915_READ(DSPSTRIDE(pipe));
8523         fb->pitches[0] = val & 0xffffffc0;
8524
8525         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8526
8527         plane_config->size = fb->pitches[0] * aligned_height;
8528
8529         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8530                       pipe_name(pipe), fb->width, fb->height,
8531                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8532                       plane_config->size);
8533
8534         plane_config->fb = intel_fb;
8535 }
8536
8537 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8538                                      struct intel_crtc_state *pipe_config)
8539 {
8540         struct drm_device *dev = crtc->base.dev;
8541         struct drm_i915_private *dev_priv = to_i915(dev);
8542         enum intel_display_power_domain power_domain;
8543         uint32_t tmp;
8544         bool ret;
8545
8546         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8547         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8548                 return false;
8549
8550         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8551         pipe_config->shared_dpll = NULL;
8552
8553         ret = false;
8554         tmp = I915_READ(PIPECONF(crtc->pipe));
8555         if (!(tmp & PIPECONF_ENABLE))
8556                 goto out;
8557
8558         switch (tmp & PIPECONF_BPC_MASK) {
8559         case PIPECONF_6BPC:
8560                 pipe_config->pipe_bpp = 18;
8561                 break;
8562         case PIPECONF_8BPC:
8563                 pipe_config->pipe_bpp = 24;
8564                 break;
8565         case PIPECONF_10BPC:
8566                 pipe_config->pipe_bpp = 30;
8567                 break;
8568         case PIPECONF_12BPC:
8569                 pipe_config->pipe_bpp = 36;
8570                 break;
8571         default:
8572                 break;
8573         }
8574
8575         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8576                 pipe_config->limited_color_range = true;
8577
8578         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8579                 struct intel_shared_dpll *pll;
8580                 enum intel_dpll_id pll_id;
8581
8582                 pipe_config->has_pch_encoder = true;
8583
8584                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8585                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8586                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8587
8588                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8589
8590                 if (HAS_PCH_IBX(dev_priv)) {
8591                         /*
8592                          * The pipe->pch transcoder and pch transcoder->pll
8593                          * mapping is fixed.
8594                          */
8595                         pll_id = (enum intel_dpll_id) crtc->pipe;
8596                 } else {
8597                         tmp = I915_READ(PCH_DPLL_SEL);
8598                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8599                                 pll_id = DPLL_ID_PCH_PLL_B;
8600                         else
8601                                 pll_id= DPLL_ID_PCH_PLL_A;
8602                 }
8603
8604                 pipe_config->shared_dpll =
8605                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8606                 pll = pipe_config->shared_dpll;
8607
8608                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
8609                                                  &pipe_config->dpll_hw_state));
8610
8611                 tmp = pipe_config->dpll_hw_state.dpll;
8612                 pipe_config->pixel_multiplier =
8613                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8614                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8615
8616                 ironlake_pch_clock_get(crtc, pipe_config);
8617         } else {
8618                 pipe_config->pixel_multiplier = 1;
8619         }
8620
8621         intel_get_pipe_timings(crtc, pipe_config);
8622         intel_get_pipe_src_size(crtc, pipe_config);
8623
8624         ironlake_get_pfit_config(crtc, pipe_config);
8625
8626         ret = true;
8627
8628 out:
8629         intel_display_power_put(dev_priv, power_domain);
8630
8631         return ret;
8632 }
8633
8634 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8635 {
8636         struct drm_device *dev = &dev_priv->drm;
8637         struct intel_crtc *crtc;
8638
8639         for_each_intel_crtc(dev, crtc)
8640                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8641                      pipe_name(crtc->pipe));
8642
8643         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
8644         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8645         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8646         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8647         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8648         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8649              "CPU PWM1 enabled\n");
8650         if (IS_HASWELL(dev_priv))
8651                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8652                      "CPU PWM2 enabled\n");
8653         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8654              "PCH PWM1 enabled\n");
8655         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8656              "Utility pin enabled\n");
8657         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8658
8659         /*
8660          * In theory we can still leave IRQs enabled, as long as only the HPD
8661          * interrupts remain enabled. We used to check for that, but since it's
8662          * gen-specific and since we only disable LCPLL after we fully disable
8663          * the interrupts, the check below should be enough.
8664          */
8665         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8666 }
8667
8668 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8669 {
8670         if (IS_HASWELL(dev_priv))
8671                 return I915_READ(D_COMP_HSW);
8672         else
8673                 return I915_READ(D_COMP_BDW);
8674 }
8675
8676 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8677 {
8678         if (IS_HASWELL(dev_priv)) {
8679                 mutex_lock(&dev_priv->rps.hw_lock);
8680                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8681                                             val))
8682                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8683                 mutex_unlock(&dev_priv->rps.hw_lock);
8684         } else {
8685                 I915_WRITE(D_COMP_BDW, val);
8686                 POSTING_READ(D_COMP_BDW);
8687         }
8688 }
8689
8690 /*
8691  * This function implements pieces of two sequences from BSpec:
8692  * - Sequence for display software to disable LCPLL
8693  * - Sequence for display software to allow package C8+
8694  * The steps implemented here are just the steps that actually touch the LCPLL
8695  * register. Callers should take care of disabling all the display engine
8696  * functions, doing the mode unset, fixing interrupts, etc.
8697  */
8698 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8699                               bool switch_to_fclk, bool allow_power_down)
8700 {
8701         uint32_t val;
8702
8703         assert_can_disable_lcpll(dev_priv);
8704
8705         val = I915_READ(LCPLL_CTL);
8706
8707         if (switch_to_fclk) {
8708                 val |= LCPLL_CD_SOURCE_FCLK;
8709                 I915_WRITE(LCPLL_CTL, val);
8710
8711                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8712                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8713                         DRM_ERROR("Switching to FCLK failed\n");
8714
8715                 val = I915_READ(LCPLL_CTL);
8716         }
8717
8718         val |= LCPLL_PLL_DISABLE;
8719         I915_WRITE(LCPLL_CTL, val);
8720         POSTING_READ(LCPLL_CTL);
8721
8722         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8723                 DRM_ERROR("LCPLL still locked\n");
8724
8725         val = hsw_read_dcomp(dev_priv);
8726         val |= D_COMP_COMP_DISABLE;
8727         hsw_write_dcomp(dev_priv, val);
8728         ndelay(100);
8729
8730         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8731                      1))
8732                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8733
8734         if (allow_power_down) {
8735                 val = I915_READ(LCPLL_CTL);
8736                 val |= LCPLL_POWER_DOWN_ALLOW;
8737                 I915_WRITE(LCPLL_CTL, val);
8738                 POSTING_READ(LCPLL_CTL);
8739         }
8740 }
8741
8742 /*
8743  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8744  * source.
8745  */
8746 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8747 {
8748         uint32_t val;
8749
8750         val = I915_READ(LCPLL_CTL);
8751
8752         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8753                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8754                 return;
8755
8756         /*
8757          * Make sure we're not on PC8 state before disabling PC8, otherwise
8758          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8759          */
8760         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8761
8762         if (val & LCPLL_POWER_DOWN_ALLOW) {
8763                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8764                 I915_WRITE(LCPLL_CTL, val);
8765                 POSTING_READ(LCPLL_CTL);
8766         }
8767
8768         val = hsw_read_dcomp(dev_priv);
8769         val |= D_COMP_COMP_FORCE;
8770         val &= ~D_COMP_COMP_DISABLE;
8771         hsw_write_dcomp(dev_priv, val);
8772
8773         val = I915_READ(LCPLL_CTL);
8774         val &= ~LCPLL_PLL_DISABLE;
8775         I915_WRITE(LCPLL_CTL, val);
8776
8777         if (intel_wait_for_register(dev_priv,
8778                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8779                                     5))
8780                 DRM_ERROR("LCPLL not locked yet\n");
8781
8782         if (val & LCPLL_CD_SOURCE_FCLK) {
8783                 val = I915_READ(LCPLL_CTL);
8784                 val &= ~LCPLL_CD_SOURCE_FCLK;
8785                 I915_WRITE(LCPLL_CTL, val);
8786
8787                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8788                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8789                         DRM_ERROR("Switching back to LCPLL failed\n");
8790         }
8791
8792         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8793         intel_update_cdclk(dev_priv);
8794 }
8795
8796 /*
8797  * Package states C8 and deeper are really deep PC states that can only be
8798  * reached when all the devices on the system allow it, so even if the graphics
8799  * device allows PC8+, it doesn't mean the system will actually get to these
8800  * states. Our driver only allows PC8+ when going into runtime PM.
8801  *
8802  * The requirements for PC8+ are that all the outputs are disabled, the power
8803  * well is disabled and most interrupts are disabled, and these are also
8804  * requirements for runtime PM. When these conditions are met, we manually do
8805  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8806  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8807  * hang the machine.
8808  *
8809  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8810  * the state of some registers, so when we come back from PC8+ we need to
8811  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8812  * need to take care of the registers kept by RC6. Notice that this happens even
8813  * if we don't put the device in PCI D3 state (which is what currently happens
8814  * because of the runtime PM support).
8815  *
8816  * For more, read "Display Sequences for Package C8" on the hardware
8817  * documentation.
8818  */
8819 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8820 {
8821         uint32_t val;
8822
8823         DRM_DEBUG_KMS("Enabling package C8+\n");
8824
8825         if (HAS_PCH_LPT_LP(dev_priv)) {
8826                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8827                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8828                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8829         }
8830
8831         lpt_disable_clkout_dp(dev_priv);
8832         hsw_disable_lcpll(dev_priv, true, true);
8833 }
8834
8835 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8836 {
8837         uint32_t val;
8838
8839         DRM_DEBUG_KMS("Disabling package C8+\n");
8840
8841         hsw_restore_lcpll(dev_priv);
8842         lpt_init_pch_refclk(dev_priv);
8843
8844         if (HAS_PCH_LPT_LP(dev_priv)) {
8845                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8846                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
8847                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8848         }
8849 }
8850
8851 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
8852                                       struct intel_crtc_state *crtc_state)
8853 {
8854         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
8855                 struct intel_encoder *encoder =
8856                         intel_ddi_get_crtc_new_encoder(crtc_state);
8857
8858                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
8859                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8860                                          pipe_name(crtc->pipe));
8861                         return -EINVAL;
8862                 }
8863         }
8864
8865         crtc->lowfreq_avail = false;
8866
8867         return 0;
8868 }
8869
8870 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
8871                                    enum port port,
8872                                    struct intel_crtc_state *pipe_config)
8873 {
8874         enum intel_dpll_id id;
8875         u32 temp;
8876
8877         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
8878         id = temp >> (port * 2);
8879
8880         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
8881                 return;
8882
8883         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8884 }
8885
8886 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
8887                                 enum port port,
8888                                 struct intel_crtc_state *pipe_config)
8889 {
8890         enum intel_dpll_id id;
8891
8892         switch (port) {
8893         case PORT_A:
8894                 id = DPLL_ID_SKL_DPLL0;
8895                 break;
8896         case PORT_B:
8897                 id = DPLL_ID_SKL_DPLL1;
8898                 break;
8899         case PORT_C:
8900                 id = DPLL_ID_SKL_DPLL2;
8901                 break;
8902         default:
8903                 DRM_ERROR("Incorrect port type\n");
8904                 return;
8905         }
8906
8907         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8908 }
8909
8910 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
8911                                 enum port port,
8912                                 struct intel_crtc_state *pipe_config)
8913 {
8914         enum intel_dpll_id id;
8915         u32 temp;
8916
8917         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
8918         id = temp >> (port * 3 + 1);
8919
8920         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
8921                 return;
8922
8923         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8924 }
8925
8926 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
8927                                 enum port port,
8928                                 struct intel_crtc_state *pipe_config)
8929 {
8930         enum intel_dpll_id id;
8931         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
8932
8933         switch (ddi_pll_sel) {
8934         case PORT_CLK_SEL_WRPLL1:
8935                 id = DPLL_ID_WRPLL1;
8936                 break;
8937         case PORT_CLK_SEL_WRPLL2:
8938                 id = DPLL_ID_WRPLL2;
8939                 break;
8940         case PORT_CLK_SEL_SPLL:
8941                 id = DPLL_ID_SPLL;
8942                 break;
8943         case PORT_CLK_SEL_LCPLL_810:
8944                 id = DPLL_ID_LCPLL_810;
8945                 break;
8946         case PORT_CLK_SEL_LCPLL_1350:
8947                 id = DPLL_ID_LCPLL_1350;
8948                 break;
8949         case PORT_CLK_SEL_LCPLL_2700:
8950                 id = DPLL_ID_LCPLL_2700;
8951                 break;
8952         default:
8953                 MISSING_CASE(ddi_pll_sel);
8954                 /* fall through */
8955         case PORT_CLK_SEL_NONE:
8956                 return;
8957         }
8958
8959         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8960 }
8961
8962 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
8963                                      struct intel_crtc_state *pipe_config,
8964                                      u64 *power_domain_mask)
8965 {
8966         struct drm_device *dev = crtc->base.dev;
8967         struct drm_i915_private *dev_priv = to_i915(dev);
8968         enum intel_display_power_domain power_domain;
8969         u32 tmp;
8970
8971         /*
8972          * The pipe->transcoder mapping is fixed with the exception of the eDP
8973          * transcoder handled below.
8974          */
8975         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8976
8977         /*
8978          * XXX: Do intel_display_power_get_if_enabled before reading this (for
8979          * consistency and less surprising code; it's in always on power).
8980          */
8981         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
8982         if (tmp & TRANS_DDI_FUNC_ENABLE) {
8983                 enum pipe trans_edp_pipe;
8984                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
8985                 default:
8986                         WARN(1, "unknown pipe linked to edp transcoder\n");
8987                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
8988                 case TRANS_DDI_EDP_INPUT_A_ON:
8989                         trans_edp_pipe = PIPE_A;
8990                         break;
8991                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
8992                         trans_edp_pipe = PIPE_B;
8993                         break;
8994                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
8995                         trans_edp_pipe = PIPE_C;
8996                         break;
8997                 }
8998
8999                 if (trans_edp_pipe == crtc->pipe)
9000                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9001         }
9002
9003         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9004         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9005                 return false;
9006         *power_domain_mask |= BIT_ULL(power_domain);
9007
9008         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9009
9010         return tmp & PIPECONF_ENABLE;
9011 }
9012
9013 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9014                                          struct intel_crtc_state *pipe_config,
9015                                          u64 *power_domain_mask)
9016 {
9017         struct drm_device *dev = crtc->base.dev;
9018         struct drm_i915_private *dev_priv = to_i915(dev);
9019         enum intel_display_power_domain power_domain;
9020         enum port port;
9021         enum transcoder cpu_transcoder;
9022         u32 tmp;
9023
9024         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9025                 if (port == PORT_A)
9026                         cpu_transcoder = TRANSCODER_DSI_A;
9027                 else
9028                         cpu_transcoder = TRANSCODER_DSI_C;
9029
9030                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9031                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9032                         continue;
9033                 *power_domain_mask |= BIT_ULL(power_domain);
9034
9035                 /*
9036                  * The PLL needs to be enabled with a valid divider
9037                  * configuration, otherwise accessing DSI registers will hang
9038                  * the machine. See BSpec North Display Engine
9039                  * registers/MIPI[BXT]. We can break out here early, since we
9040                  * need the same DSI PLL to be enabled for both DSI ports.
9041                  */
9042                 if (!intel_dsi_pll_is_enabled(dev_priv))
9043                         break;
9044
9045                 /* XXX: this works for video mode only */
9046                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9047                 if (!(tmp & DPI_ENABLE))
9048                         continue;
9049
9050                 tmp = I915_READ(MIPI_CTRL(port));
9051                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9052                         continue;
9053
9054                 pipe_config->cpu_transcoder = cpu_transcoder;
9055                 break;
9056         }
9057
9058         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9059 }
9060
9061 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9062                                        struct intel_crtc_state *pipe_config)
9063 {
9064         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9065         struct intel_shared_dpll *pll;
9066         enum port port;
9067         uint32_t tmp;
9068
9069         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9070
9071         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9072
9073         if (IS_CANNONLAKE(dev_priv))
9074                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9075         else if (IS_GEN9_BC(dev_priv))
9076                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9077         else if (IS_GEN9_LP(dev_priv))
9078                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9079         else
9080                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9081
9082         pll = pipe_config->shared_dpll;
9083         if (pll) {
9084                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9085                                                  &pipe_config->dpll_hw_state));
9086         }
9087
9088         /*
9089          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9090          * DDI E. So just check whether this pipe is wired to DDI E and whether
9091          * the PCH transcoder is on.
9092          */
9093         if (INTEL_GEN(dev_priv) < 9 &&
9094             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9095                 pipe_config->has_pch_encoder = true;
9096
9097                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9098                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9099                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9100
9101                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9102         }
9103 }
9104
9105 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9106                                     struct intel_crtc_state *pipe_config)
9107 {
9108         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9109         enum intel_display_power_domain power_domain;
9110         u64 power_domain_mask;
9111         bool active;
9112
9113         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9114         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9115                 return false;
9116         power_domain_mask = BIT_ULL(power_domain);
9117
9118         pipe_config->shared_dpll = NULL;
9119
9120         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9121
9122         if (IS_GEN9_LP(dev_priv) &&
9123             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9124                 WARN_ON(active);
9125                 active = true;
9126         }
9127
9128         if (!active)
9129                 goto out;
9130
9131         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9132                 haswell_get_ddi_port_state(crtc, pipe_config);
9133                 intel_get_pipe_timings(crtc, pipe_config);
9134         }
9135
9136         intel_get_pipe_src_size(crtc, pipe_config);
9137
9138         pipe_config->gamma_mode =
9139                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9140
9141         if (INTEL_GEN(dev_priv) >= 9) {
9142                 intel_crtc_init_scalers(crtc, pipe_config);
9143
9144                 pipe_config->scaler_state.scaler_id = -1;
9145                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9146         }
9147
9148         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9149         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9150                 power_domain_mask |= BIT_ULL(power_domain);
9151                 if (INTEL_GEN(dev_priv) >= 9)
9152                         skylake_get_pfit_config(crtc, pipe_config);
9153                 else
9154                         ironlake_get_pfit_config(crtc, pipe_config);
9155         }
9156
9157         if (IS_HASWELL(dev_priv))
9158                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9159                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9160
9161         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9162             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9163                 pipe_config->pixel_multiplier =
9164                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9165         } else {
9166                 pipe_config->pixel_multiplier = 1;
9167         }
9168
9169 out:
9170         for_each_power_domain(power_domain, power_domain_mask)
9171                 intel_display_power_put(dev_priv, power_domain);
9172
9173         return active;
9174 }
9175
9176 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9177 {
9178         struct drm_i915_private *dev_priv =
9179                 to_i915(plane_state->base.plane->dev);
9180         const struct drm_framebuffer *fb = plane_state->base.fb;
9181         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9182         u32 base;
9183
9184         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9185                 base = obj->phys_handle->busaddr;
9186         else
9187                 base = intel_plane_ggtt_offset(plane_state);
9188
9189         base += plane_state->main.offset;
9190
9191         /* ILK+ do this automagically */
9192         if (HAS_GMCH_DISPLAY(dev_priv) &&
9193             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9194                 base += (plane_state->base.crtc_h *
9195                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9196
9197         return base;
9198 }
9199
9200 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9201 {
9202         int x = plane_state->base.crtc_x;
9203         int y = plane_state->base.crtc_y;
9204         u32 pos = 0;
9205
9206         if (x < 0) {
9207                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9208                 x = -x;
9209         }
9210         pos |= x << CURSOR_X_SHIFT;
9211
9212         if (y < 0) {
9213                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9214                 y = -y;
9215         }
9216         pos |= y << CURSOR_Y_SHIFT;
9217
9218         return pos;
9219 }
9220
9221 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9222 {
9223         const struct drm_mode_config *config =
9224                 &plane_state->base.plane->dev->mode_config;
9225         int width = plane_state->base.crtc_w;
9226         int height = plane_state->base.crtc_h;
9227
9228         return width > 0 && width <= config->cursor_width &&
9229                 height > 0 && height <= config->cursor_height;
9230 }
9231
9232 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9233                               struct intel_plane_state *plane_state)
9234 {
9235         const struct drm_framebuffer *fb = plane_state->base.fb;
9236         int src_x, src_y;
9237         u32 offset;
9238         int ret;
9239
9240         ret = drm_plane_helper_check_state(&plane_state->base,
9241                                            &plane_state->clip,
9242                                            DRM_PLANE_HELPER_NO_SCALING,
9243                                            DRM_PLANE_HELPER_NO_SCALING,
9244                                            true, true);
9245         if (ret)
9246                 return ret;
9247
9248         if (!fb)
9249                 return 0;
9250
9251         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9252                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9253                 return -EINVAL;
9254         }
9255
9256         src_x = plane_state->base.src_x >> 16;
9257         src_y = plane_state->base.src_y >> 16;
9258
9259         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9260         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9261
9262         if (src_x != 0 || src_y != 0) {
9263                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9264                 return -EINVAL;
9265         }
9266
9267         plane_state->main.offset = offset;
9268
9269         return 0;
9270 }
9271
9272 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9273                            const struct intel_plane_state *plane_state)
9274 {
9275         const struct drm_framebuffer *fb = plane_state->base.fb;
9276
9277         return CURSOR_ENABLE |
9278                 CURSOR_GAMMA_ENABLE |
9279                 CURSOR_FORMAT_ARGB |
9280                 CURSOR_STRIDE(fb->pitches[0]);
9281 }
9282
9283 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9284 {
9285         int width = plane_state->base.crtc_w;
9286
9287         /*
9288          * 845g/865g are only limited by the width of their cursors,
9289          * the height is arbitrary up to the precision of the register.
9290          */
9291         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9292 }
9293
9294 static int i845_check_cursor(struct intel_plane *plane,
9295                              struct intel_crtc_state *crtc_state,
9296                              struct intel_plane_state *plane_state)
9297 {
9298         const struct drm_framebuffer *fb = plane_state->base.fb;
9299         int ret;
9300
9301         ret = intel_check_cursor(crtc_state, plane_state);
9302         if (ret)
9303                 return ret;
9304
9305         /* if we want to turn off the cursor ignore width and height */
9306         if (!fb)
9307                 return 0;
9308
9309         /* Check for which cursor types we support */
9310         if (!i845_cursor_size_ok(plane_state)) {
9311                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9312                           plane_state->base.crtc_w,
9313                           plane_state->base.crtc_h);
9314                 return -EINVAL;
9315         }
9316
9317         switch (fb->pitches[0]) {
9318         case 256:
9319         case 512:
9320         case 1024:
9321         case 2048:
9322                 break;
9323         default:
9324                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9325                               fb->pitches[0]);
9326                 return -EINVAL;
9327         }
9328
9329         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9330
9331         return 0;
9332 }
9333
9334 static void i845_update_cursor(struct intel_plane *plane,
9335                                const struct intel_crtc_state *crtc_state,
9336                                const struct intel_plane_state *plane_state)
9337 {
9338         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9339         u32 cntl = 0, base = 0, pos = 0, size = 0;
9340         unsigned long irqflags;
9341
9342         if (plane_state && plane_state->base.visible) {
9343                 unsigned int width = plane_state->base.crtc_w;
9344                 unsigned int height = plane_state->base.crtc_h;
9345
9346                 cntl = plane_state->ctl;
9347                 size = (height << 12) | width;
9348
9349                 base = intel_cursor_base(plane_state);
9350                 pos = intel_cursor_position(plane_state);
9351         }
9352
9353         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9354
9355         /* On these chipsets we can only modify the base/size/stride
9356          * whilst the cursor is disabled.
9357          */
9358         if (plane->cursor.base != base ||
9359             plane->cursor.size != size ||
9360             plane->cursor.cntl != cntl) {
9361                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9362                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9363                 I915_WRITE_FW(CURSIZE, size);
9364                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9365                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9366
9367                 plane->cursor.base = base;
9368                 plane->cursor.size = size;
9369                 plane->cursor.cntl = cntl;
9370         } else {
9371                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9372         }
9373
9374         POSTING_READ_FW(CURCNTR(PIPE_A));
9375
9376         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9377 }
9378
9379 static void i845_disable_cursor(struct intel_plane *plane,
9380                                 struct intel_crtc *crtc)
9381 {
9382         i845_update_cursor(plane, NULL, NULL);
9383 }
9384
9385 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9386                            const struct intel_plane_state *plane_state)
9387 {
9388         struct drm_i915_private *dev_priv =
9389                 to_i915(plane_state->base.plane->dev);
9390         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9391         u32 cntl;
9392
9393         cntl = MCURSOR_GAMMA_ENABLE;
9394
9395         if (HAS_DDI(dev_priv))
9396                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9397
9398         cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9399
9400         switch (plane_state->base.crtc_w) {
9401         case 64:
9402                 cntl |= CURSOR_MODE_64_ARGB_AX;
9403                 break;
9404         case 128:
9405                 cntl |= CURSOR_MODE_128_ARGB_AX;
9406                 break;
9407         case 256:
9408                 cntl |= CURSOR_MODE_256_ARGB_AX;
9409                 break;
9410         default:
9411                 MISSING_CASE(plane_state->base.crtc_w);
9412                 return 0;
9413         }
9414
9415         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9416                 cntl |= CURSOR_ROTATE_180;
9417
9418         return cntl;
9419 }
9420
9421 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9422 {
9423         struct drm_i915_private *dev_priv =
9424                 to_i915(plane_state->base.plane->dev);
9425         int width = plane_state->base.crtc_w;
9426         int height = plane_state->base.crtc_h;
9427
9428         if (!intel_cursor_size_ok(plane_state))
9429                 return false;
9430
9431         /* Cursor width is limited to a few power-of-two sizes */
9432         switch (width) {
9433         case 256:
9434         case 128:
9435         case 64:
9436                 break;
9437         default:
9438                 return false;
9439         }
9440
9441         /*
9442          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9443          * height from 8 lines up to the cursor width, when the
9444          * cursor is not rotated. Everything else requires square
9445          * cursors.
9446          */
9447         if (HAS_CUR_FBC(dev_priv) &&
9448             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9449                 if (height < 8 || height > width)
9450                         return false;
9451         } else {
9452                 if (height != width)
9453                         return false;
9454         }
9455
9456         return true;
9457 }
9458
9459 static int i9xx_check_cursor(struct intel_plane *plane,
9460                              struct intel_crtc_state *crtc_state,
9461                              struct intel_plane_state *plane_state)
9462 {
9463         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9464         const struct drm_framebuffer *fb = plane_state->base.fb;
9465         enum pipe pipe = plane->pipe;
9466         int ret;
9467
9468         ret = intel_check_cursor(crtc_state, plane_state);
9469         if (ret)
9470                 return ret;
9471
9472         /* if we want to turn off the cursor ignore width and height */
9473         if (!fb)
9474                 return 0;
9475
9476         /* Check for which cursor types we support */
9477         if (!i9xx_cursor_size_ok(plane_state)) {
9478                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9479                           plane_state->base.crtc_w,
9480                           plane_state->base.crtc_h);
9481                 return -EINVAL;
9482         }
9483
9484         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9485                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9486                               fb->pitches[0], plane_state->base.crtc_w);
9487                 return -EINVAL;
9488         }
9489
9490         /*
9491          * There's something wrong with the cursor on CHV pipe C.
9492          * If it straddles the left edge of the screen then
9493          * moving it away from the edge or disabling it often
9494          * results in a pipe underrun, and often that can lead to
9495          * dead pipe (constant underrun reported, and it scans
9496          * out just a solid color). To recover from that, the
9497          * display power well must be turned off and on again.
9498          * Refuse the put the cursor into that compromised position.
9499          */
9500         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9501             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9502                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9503                 return -EINVAL;
9504         }
9505
9506         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9507
9508         return 0;
9509 }
9510
9511 static void i9xx_update_cursor(struct intel_plane *plane,
9512                                const struct intel_crtc_state *crtc_state,
9513                                const struct intel_plane_state *plane_state)
9514 {
9515         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9516         enum pipe pipe = plane->pipe;
9517         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9518         unsigned long irqflags;
9519
9520         if (plane_state && plane_state->base.visible) {
9521                 cntl = plane_state->ctl;
9522
9523                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9524                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9525
9526                 base = intel_cursor_base(plane_state);
9527                 pos = intel_cursor_position(plane_state);
9528         }
9529
9530         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9531
9532         /*
9533          * On some platforms writing CURCNTR first will also
9534          * cause CURPOS to be armed by the CURBASE write.
9535          * Without the CURCNTR write the CURPOS write would
9536          * arm itself.
9537          *
9538          * CURCNTR and CUR_FBC_CTL are always
9539          * armed by the CURBASE write only.
9540          */
9541         if (plane->cursor.base != base ||
9542             plane->cursor.size != fbc_ctl ||
9543             plane->cursor.cntl != cntl) {
9544                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9545                 if (HAS_CUR_FBC(dev_priv))
9546                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9547                 I915_WRITE_FW(CURPOS(pipe), pos);
9548                 I915_WRITE_FW(CURBASE(pipe), base);
9549
9550                 plane->cursor.base = base;
9551                 plane->cursor.size = fbc_ctl;
9552                 plane->cursor.cntl = cntl;
9553         } else {
9554                 I915_WRITE_FW(CURPOS(pipe), pos);
9555         }
9556
9557         POSTING_READ_FW(CURBASE(pipe));
9558
9559         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9560 }
9561
9562 static void i9xx_disable_cursor(struct intel_plane *plane,
9563                                 struct intel_crtc *crtc)
9564 {
9565         i9xx_update_cursor(plane, NULL, NULL);
9566 }
9567
9568
9569 /* VESA 640x480x72Hz mode to set on the pipe */
9570 static struct drm_display_mode load_detect_mode = {
9571         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9572                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9573 };
9574
9575 struct drm_framebuffer *
9576 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9577                          struct drm_mode_fb_cmd2 *mode_cmd)
9578 {
9579         struct intel_framebuffer *intel_fb;
9580         int ret;
9581
9582         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9583         if (!intel_fb)
9584                 return ERR_PTR(-ENOMEM);
9585
9586         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9587         if (ret)
9588                 goto err;
9589
9590         return &intel_fb->base;
9591
9592 err:
9593         kfree(intel_fb);
9594         return ERR_PTR(ret);
9595 }
9596
9597 static u32
9598 intel_framebuffer_pitch_for_width(int width, int bpp)
9599 {
9600         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
9601         return ALIGN(pitch, 64);
9602 }
9603
9604 static u32
9605 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
9606 {
9607         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
9608         return PAGE_ALIGN(pitch * mode->vdisplay);
9609 }
9610
9611 static struct drm_framebuffer *
9612 intel_framebuffer_create_for_mode(struct drm_device *dev,
9613                                   struct drm_display_mode *mode,
9614                                   int depth, int bpp)
9615 {
9616         struct drm_framebuffer *fb;
9617         struct drm_i915_gem_object *obj;
9618         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
9619
9620         obj = i915_gem_object_create(to_i915(dev),
9621                                     intel_framebuffer_size_for_mode(mode, bpp));
9622         if (IS_ERR(obj))
9623                 return ERR_CAST(obj);
9624
9625         mode_cmd.width = mode->hdisplay;
9626         mode_cmd.height = mode->vdisplay;
9627         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
9628                                                                 bpp);
9629         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
9630
9631         fb = intel_framebuffer_create(obj, &mode_cmd);
9632         if (IS_ERR(fb))
9633                 i915_gem_object_put(obj);
9634
9635         return fb;
9636 }
9637
9638 static struct drm_framebuffer *
9639 mode_fits_in_fbdev(struct drm_device *dev,
9640                    struct drm_display_mode *mode)
9641 {
9642 #ifdef CONFIG_DRM_FBDEV_EMULATION
9643         struct drm_i915_private *dev_priv = to_i915(dev);
9644         struct drm_i915_gem_object *obj;
9645         struct drm_framebuffer *fb;
9646
9647         if (!dev_priv->fbdev)
9648                 return NULL;
9649
9650         if (!dev_priv->fbdev->fb)
9651                 return NULL;
9652
9653         obj = dev_priv->fbdev->fb->obj;
9654         BUG_ON(!obj);
9655
9656         fb = &dev_priv->fbdev->fb->base;
9657         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
9658                                                                fb->format->cpp[0] * 8))
9659                 return NULL;
9660
9661         if (obj->base.size < mode->vdisplay * fb->pitches[0])
9662                 return NULL;
9663
9664         drm_framebuffer_reference(fb);
9665         return fb;
9666 #else
9667         return NULL;
9668 #endif
9669 }
9670
9671 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
9672                                            struct drm_crtc *crtc,
9673                                            struct drm_display_mode *mode,
9674                                            struct drm_framebuffer *fb,
9675                                            int x, int y)
9676 {
9677         struct drm_plane_state *plane_state;
9678         int hdisplay, vdisplay;
9679         int ret;
9680
9681         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
9682         if (IS_ERR(plane_state))
9683                 return PTR_ERR(plane_state);
9684
9685         if (mode)
9686                 drm_mode_get_hv_timing(mode, &hdisplay, &vdisplay);
9687         else
9688                 hdisplay = vdisplay = 0;
9689
9690         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
9691         if (ret)
9692                 return ret;
9693         drm_atomic_set_fb_for_plane(plane_state, fb);
9694         plane_state->crtc_x = 0;
9695         plane_state->crtc_y = 0;
9696         plane_state->crtc_w = hdisplay;
9697         plane_state->crtc_h = vdisplay;
9698         plane_state->src_x = x << 16;
9699         plane_state->src_y = y << 16;
9700         plane_state->src_w = hdisplay << 16;
9701         plane_state->src_h = vdisplay << 16;
9702
9703         return 0;
9704 }
9705
9706 int intel_get_load_detect_pipe(struct drm_connector *connector,
9707                                struct drm_display_mode *mode,
9708                                struct intel_load_detect_pipe *old,
9709                                struct drm_modeset_acquire_ctx *ctx)
9710 {
9711         struct intel_crtc *intel_crtc;
9712         struct intel_encoder *intel_encoder =
9713                 intel_attached_encoder(connector);
9714         struct drm_crtc *possible_crtc;
9715         struct drm_encoder *encoder = &intel_encoder->base;
9716         struct drm_crtc *crtc = NULL;
9717         struct drm_device *dev = encoder->dev;
9718         struct drm_i915_private *dev_priv = to_i915(dev);
9719         struct drm_framebuffer *fb;
9720         struct drm_mode_config *config = &dev->mode_config;
9721         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9722         struct drm_connector_state *connector_state;
9723         struct intel_crtc_state *crtc_state;
9724         int ret, i = -1;
9725
9726         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9727                       connector->base.id, connector->name,
9728                       encoder->base.id, encoder->name);
9729
9730         old->restore_state = NULL;
9731
9732         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9733
9734         /*
9735          * Algorithm gets a little messy:
9736          *
9737          *   - if the connector already has an assigned crtc, use it (but make
9738          *     sure it's on first)
9739          *
9740          *   - try to find the first unused crtc that can drive this connector,
9741          *     and use that if we find one
9742          */
9743
9744         /* See if we already have a CRTC for this connector */
9745         if (connector->state->crtc) {
9746                 crtc = connector->state->crtc;
9747
9748                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9749                 if (ret)
9750                         goto fail;
9751
9752                 /* Make sure the crtc and connector are running */
9753                 goto found;
9754         }
9755
9756         /* Find an unused one (if possible) */
9757         for_each_crtc(dev, possible_crtc) {
9758                 i++;
9759                 if (!(encoder->possible_crtcs & (1 << i)))
9760                         continue;
9761
9762                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9763                 if (ret)
9764                         goto fail;
9765
9766                 if (possible_crtc->state->enable) {
9767                         drm_modeset_unlock(&possible_crtc->mutex);
9768                         continue;
9769                 }
9770
9771                 crtc = possible_crtc;
9772                 break;
9773         }
9774
9775         /*
9776          * If we didn't find an unused CRTC, don't use any.
9777          */
9778         if (!crtc) {
9779                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9780                 ret = -ENODEV;
9781                 goto fail;
9782         }
9783
9784 found:
9785         intel_crtc = to_intel_crtc(crtc);
9786
9787         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9788         if (ret)
9789                 goto fail;
9790
9791         state = drm_atomic_state_alloc(dev);
9792         restore_state = drm_atomic_state_alloc(dev);
9793         if (!state || !restore_state) {
9794                 ret = -ENOMEM;
9795                 goto fail;
9796         }
9797
9798         state->acquire_ctx = ctx;
9799         restore_state->acquire_ctx = ctx;
9800
9801         connector_state = drm_atomic_get_connector_state(state, connector);
9802         if (IS_ERR(connector_state)) {
9803                 ret = PTR_ERR(connector_state);
9804                 goto fail;
9805         }
9806
9807         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
9808         if (ret)
9809                 goto fail;
9810
9811         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9812         if (IS_ERR(crtc_state)) {
9813                 ret = PTR_ERR(crtc_state);
9814                 goto fail;
9815         }
9816
9817         crtc_state->base.active = crtc_state->base.enable = true;
9818
9819         if (!mode)
9820                 mode = &load_detect_mode;
9821
9822         /* We need a framebuffer large enough to accommodate all accesses
9823          * that the plane may generate whilst we perform load detection.
9824          * We can not rely on the fbcon either being present (we get called
9825          * during its initialisation to detect all boot displays, or it may
9826          * not even exist) or that it is large enough to satisfy the
9827          * requested mode.
9828          */
9829         fb = mode_fits_in_fbdev(dev, mode);
9830         if (fb == NULL) {
9831                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
9832                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
9833         } else
9834                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
9835         if (IS_ERR(fb)) {
9836                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
9837                 ret = PTR_ERR(fb);
9838                 goto fail;
9839         }
9840
9841         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
9842         if (ret)
9843                 goto fail;
9844
9845         drm_framebuffer_unreference(fb);
9846
9847         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
9848         if (ret)
9849                 goto fail;
9850
9851         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
9852         if (!ret)
9853                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
9854         if (!ret)
9855                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
9856         if (ret) {
9857                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
9858                 goto fail;
9859         }
9860
9861         ret = drm_atomic_commit(state);
9862         if (ret) {
9863                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9864                 goto fail;
9865         }
9866
9867         old->restore_state = restore_state;
9868         drm_atomic_state_put(state);
9869
9870         /* let the connector get through one full cycle before testing */
9871         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
9872         return true;
9873
9874 fail:
9875         if (state) {
9876                 drm_atomic_state_put(state);
9877                 state = NULL;
9878         }
9879         if (restore_state) {
9880                 drm_atomic_state_put(restore_state);
9881                 restore_state = NULL;
9882         }
9883
9884         if (ret == -EDEADLK)
9885                 return ret;
9886
9887         return false;
9888 }
9889
9890 void intel_release_load_detect_pipe(struct drm_connector *connector,
9891                                     struct intel_load_detect_pipe *old,
9892                                     struct drm_modeset_acquire_ctx *ctx)
9893 {
9894         struct intel_encoder *intel_encoder =
9895                 intel_attached_encoder(connector);
9896         struct drm_encoder *encoder = &intel_encoder->base;
9897         struct drm_atomic_state *state = old->restore_state;
9898         int ret;
9899
9900         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9901                       connector->base.id, connector->name,
9902                       encoder->base.id, encoder->name);
9903
9904         if (!state)
9905                 return;
9906
9907         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
9908         if (ret)
9909                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
9910         drm_atomic_state_put(state);
9911 }
9912
9913 static int i9xx_pll_refclk(struct drm_device *dev,
9914                            const struct intel_crtc_state *pipe_config)
9915 {
9916         struct drm_i915_private *dev_priv = to_i915(dev);
9917         u32 dpll = pipe_config->dpll_hw_state.dpll;
9918
9919         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
9920                 return dev_priv->vbt.lvds_ssc_freq;
9921         else if (HAS_PCH_SPLIT(dev_priv))
9922                 return 120000;
9923         else if (!IS_GEN2(dev_priv))
9924                 return 96000;
9925         else
9926                 return 48000;
9927 }
9928
9929 /* Returns the clock of the currently programmed mode of the given pipe. */
9930 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
9931                                 struct intel_crtc_state *pipe_config)
9932 {
9933         struct drm_device *dev = crtc->base.dev;
9934         struct drm_i915_private *dev_priv = to_i915(dev);
9935         int pipe = pipe_config->cpu_transcoder;
9936         u32 dpll = pipe_config->dpll_hw_state.dpll;
9937         u32 fp;
9938         struct dpll clock;
9939         int port_clock;
9940         int refclk = i9xx_pll_refclk(dev, pipe_config);
9941
9942         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
9943                 fp = pipe_config->dpll_hw_state.fp0;
9944         else
9945                 fp = pipe_config->dpll_hw_state.fp1;
9946
9947         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
9948         if (IS_PINEVIEW(dev_priv)) {
9949                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
9950                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
9951         } else {
9952                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
9953                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
9954         }
9955
9956         if (!IS_GEN2(dev_priv)) {
9957                 if (IS_PINEVIEW(dev_priv))
9958                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
9959                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
9960                 else
9961                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
9962                                DPLL_FPA01_P1_POST_DIV_SHIFT);
9963
9964                 switch (dpll & DPLL_MODE_MASK) {
9965                 case DPLLB_MODE_DAC_SERIAL:
9966                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
9967                                 5 : 10;
9968                         break;
9969                 case DPLLB_MODE_LVDS:
9970                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
9971                                 7 : 14;
9972                         break;
9973                 default:
9974                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
9975                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
9976                         return;
9977                 }
9978
9979                 if (IS_PINEVIEW(dev_priv))
9980                         port_clock = pnv_calc_dpll_params(refclk, &clock);
9981                 else
9982                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
9983         } else {
9984                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
9985                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
9986
9987                 if (is_lvds) {
9988                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
9989                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
9990
9991                         if (lvds & LVDS_CLKB_POWER_UP)
9992                                 clock.p2 = 7;
9993                         else
9994                                 clock.p2 = 14;
9995                 } else {
9996                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
9997                                 clock.p1 = 2;
9998                         else {
9999                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10000                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10001                         }
10002                         if (dpll & PLL_P2_DIVIDE_BY_4)
10003                                 clock.p2 = 4;
10004                         else
10005                                 clock.p2 = 2;
10006                 }
10007
10008                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10009         }
10010
10011         /*
10012          * This value includes pixel_multiplier. We will use
10013          * port_clock to compute adjusted_mode.crtc_clock in the
10014          * encoder's get_config() function.
10015          */
10016         pipe_config->port_clock = port_clock;
10017 }
10018
10019 int intel_dotclock_calculate(int link_freq,
10020                              const struct intel_link_m_n *m_n)
10021 {
10022         /*
10023          * The calculation for the data clock is:
10024          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10025          * But we want to avoid losing precison if possible, so:
10026          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10027          *
10028          * and the link clock is simpler:
10029          * link_clock = (m * link_clock) / n
10030          */
10031
10032         if (!m_n->link_n)
10033                 return 0;
10034
10035         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10036 }
10037
10038 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10039                                    struct intel_crtc_state *pipe_config)
10040 {
10041         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10042
10043         /* read out port_clock from the DPLL */
10044         i9xx_crtc_clock_get(crtc, pipe_config);
10045
10046         /*
10047          * In case there is an active pipe without active ports,
10048          * we may need some idea for the dotclock anyway.
10049          * Calculate one based on the FDI configuration.
10050          */
10051         pipe_config->base.adjusted_mode.crtc_clock =
10052                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10053                                          &pipe_config->fdi_m_n);
10054 }
10055
10056 /** Returns the currently programmed mode of the given pipe. */
10057 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10058                                              struct drm_crtc *crtc)
10059 {
10060         struct drm_i915_private *dev_priv = to_i915(dev);
10061         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10062         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10063         struct drm_display_mode *mode;
10064         struct intel_crtc_state *pipe_config;
10065         int htot = I915_READ(HTOTAL(cpu_transcoder));
10066         int hsync = I915_READ(HSYNC(cpu_transcoder));
10067         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10068         int vsync = I915_READ(VSYNC(cpu_transcoder));
10069         enum pipe pipe = intel_crtc->pipe;
10070
10071         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10072         if (!mode)
10073                 return NULL;
10074
10075         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10076         if (!pipe_config) {
10077                 kfree(mode);
10078                 return NULL;
10079         }
10080
10081         /*
10082          * Construct a pipe_config sufficient for getting the clock info
10083          * back out of crtc_clock_get.
10084          *
10085          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10086          * to use a real value here instead.
10087          */
10088         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10089         pipe_config->pixel_multiplier = 1;
10090         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10091         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10092         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10093         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10094
10095         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10096         mode->hdisplay = (htot & 0xffff) + 1;
10097         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10098         mode->hsync_start = (hsync & 0xffff) + 1;
10099         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10100         mode->vdisplay = (vtot & 0xffff) + 1;
10101         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10102         mode->vsync_start = (vsync & 0xffff) + 1;
10103         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10104
10105         drm_mode_set_name(mode);
10106
10107         kfree(pipe_config);
10108
10109         return mode;
10110 }
10111
10112 static void intel_crtc_destroy(struct drm_crtc *crtc)
10113 {
10114         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10115         struct drm_device *dev = crtc->dev;
10116         struct intel_flip_work *work;
10117
10118         spin_lock_irq(&dev->event_lock);
10119         work = intel_crtc->flip_work;
10120         intel_crtc->flip_work = NULL;
10121         spin_unlock_irq(&dev->event_lock);
10122
10123         if (work) {
10124                 cancel_work_sync(&work->mmio_work);
10125                 cancel_work_sync(&work->unpin_work);
10126                 kfree(work);
10127         }
10128
10129         drm_crtc_cleanup(crtc);
10130
10131         kfree(intel_crtc);
10132 }
10133
10134 static void intel_unpin_work_fn(struct work_struct *__work)
10135 {
10136         struct intel_flip_work *work =
10137                 container_of(__work, struct intel_flip_work, unpin_work);
10138         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10139         struct drm_device *dev = crtc->base.dev;
10140         struct drm_plane *primary = crtc->base.primary;
10141
10142         if (is_mmio_work(work))
10143                 flush_work(&work->mmio_work);
10144
10145         mutex_lock(&dev->struct_mutex);
10146         intel_unpin_fb_vma(work->old_vma);
10147         i915_gem_object_put(work->pending_flip_obj);
10148         mutex_unlock(&dev->struct_mutex);
10149
10150         i915_gem_request_put(work->flip_queued_req);
10151
10152         intel_frontbuffer_flip_complete(to_i915(dev),
10153                                         to_intel_plane(primary)->frontbuffer_bit);
10154         intel_fbc_post_update(crtc);
10155         drm_framebuffer_unreference(work->old_fb);
10156
10157         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10158         atomic_dec(&crtc->unpin_work_count);
10159
10160         kfree(work);
10161 }
10162
10163 /* Is 'a' after or equal to 'b'? */
10164 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10165 {
10166         return !((a - b) & 0x80000000);
10167 }
10168
10169 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
10170                                    struct intel_flip_work *work)
10171 {
10172         struct drm_device *dev = crtc->base.dev;
10173         struct drm_i915_private *dev_priv = to_i915(dev);
10174
10175         if (abort_flip_on_reset(crtc))
10176                 return true;
10177
10178         /*
10179          * The relevant registers doen't exist on pre-ctg.
10180          * As the flip done interrupt doesn't trigger for mmio
10181          * flips on gmch platforms, a flip count check isn't
10182          * really needed there. But since ctg has the registers,
10183          * include it in the check anyway.
10184          */
10185         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10186                 return true;
10187
10188         /*
10189          * BDW signals flip done immediately if the plane
10190          * is disabled, even if the plane enable is already
10191          * armed to occur at the next vblank :(
10192          */
10193
10194         /*
10195          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10196          * used the same base address. In that case the mmio flip might
10197          * have completed, but the CS hasn't even executed the flip yet.
10198          *
10199          * A flip count check isn't enough as the CS might have updated
10200          * the base address just after start of vblank, but before we
10201          * managed to process the interrupt. This means we'd complete the
10202          * CS flip too soon.
10203          *
10204          * Combining both checks should get us a good enough result. It may
10205          * still happen that the CS flip has been executed, but has not
10206          * yet actually completed. But in case the base address is the same
10207          * anyway, we don't really care.
10208          */
10209         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10210                 crtc->flip_work->gtt_offset &&
10211                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10212                                     crtc->flip_work->flip_count);
10213 }
10214
10215 static bool
10216 __pageflip_finished_mmio(struct intel_crtc *crtc,
10217                                struct intel_flip_work *work)
10218 {
10219         /*
10220          * MMIO work completes when vblank is different from
10221          * flip_queued_vblank.
10222          *
10223          * Reset counter value doesn't matter, this is handled by
10224          * i915_wait_request finishing early, so no need to handle
10225          * reset here.
10226          */
10227         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
10228 }
10229
10230
10231 static bool pageflip_finished(struct intel_crtc *crtc,
10232                               struct intel_flip_work *work)
10233 {
10234         if (!atomic_read(&work->pending))
10235                 return false;
10236
10237         smp_rmb();
10238
10239         if (is_mmio_work(work))
10240                 return __pageflip_finished_mmio(crtc, work);
10241         else
10242                 return __pageflip_finished_cs(crtc, work);
10243 }
10244
10245 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
10246 {
10247         struct drm_device *dev = &dev_priv->drm;
10248         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10249         struct intel_flip_work *work;
10250         unsigned long flags;
10251
10252         /* Ignore early vblank irqs */
10253         if (!crtc)
10254                 return;
10255
10256         /*
10257          * This is called both by irq handlers and the reset code (to complete
10258          * lost pageflips) so needs the full irqsave spinlocks.
10259          */
10260         spin_lock_irqsave(&dev->event_lock, flags);
10261         work = crtc->flip_work;
10262
10263         if (work != NULL &&
10264             !is_mmio_work(work) &&
10265             pageflip_finished(crtc, work))
10266                 page_flip_completed(crtc);
10267
10268         spin_unlock_irqrestore(&dev->event_lock, flags);
10269 }
10270
10271 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
10272 {
10273         struct drm_device *dev = &dev_priv->drm;
10274         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10275         struct intel_flip_work *work;
10276         unsigned long flags;
10277
10278         /* Ignore early vblank irqs */
10279         if (!crtc)
10280                 return;
10281
10282         /*
10283          * This is called both by irq handlers and the reset code (to complete
10284          * lost pageflips) so needs the full irqsave spinlocks.
10285          */
10286         spin_lock_irqsave(&dev->event_lock, flags);
10287         work = crtc->flip_work;
10288
10289         if (work != NULL &&
10290             is_mmio_work(work) &&
10291             pageflip_finished(crtc, work))
10292                 page_flip_completed(crtc);
10293
10294         spin_unlock_irqrestore(&dev->event_lock, flags);
10295 }
10296
10297 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
10298                                                struct intel_flip_work *work)
10299 {
10300         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
10301
10302         /* Ensure that the work item is consistent when activating it ... */
10303         smp_mb__before_atomic();
10304         atomic_set(&work->pending, 1);
10305 }
10306
10307 static int intel_gen2_queue_flip(struct drm_device *dev,
10308                                  struct drm_crtc *crtc,
10309                                  struct drm_framebuffer *fb,
10310                                  struct drm_i915_gem_object *obj,
10311                                  struct drm_i915_gem_request *req,
10312                                  uint32_t flags)
10313 {
10314         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10315         u32 flip_mask, *cs;
10316
10317         cs = intel_ring_begin(req, 6);
10318         if (IS_ERR(cs))
10319                 return PTR_ERR(cs);
10320
10321         /* Can't queue multiple flips, so wait for the previous
10322          * one to finish before executing the next.
10323          */
10324         if (intel_crtc->plane)
10325                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10326         else
10327                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10328         *cs++ = MI_WAIT_FOR_EVENT | flip_mask;
10329         *cs++ = MI_NOOP;
10330         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10331         *cs++ = fb->pitches[0];
10332         *cs++ = intel_crtc->flip_work->gtt_offset;
10333         *cs++ = 0; /* aux display base address, unused */
10334
10335         return 0;
10336 }
10337
10338 static int intel_gen3_queue_flip(struct drm_device *dev,
10339                                  struct drm_crtc *crtc,
10340                                  struct drm_framebuffer *fb,
10341                                  struct drm_i915_gem_object *obj,
10342                                  struct drm_i915_gem_request *req,
10343                                  uint32_t flags)
10344 {
10345         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10346         u32 flip_mask, *cs;
10347
10348         cs = intel_ring_begin(req, 6);
10349         if (IS_ERR(cs))
10350                 return PTR_ERR(cs);
10351
10352         if (intel_crtc->plane)
10353                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10354         else
10355                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10356         *cs++ = MI_WAIT_FOR_EVENT | flip_mask;
10357         *cs++ = MI_NOOP;
10358         *cs++ = MI_DISPLAY_FLIP_I915 | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10359         *cs++ = fb->pitches[0];
10360         *cs++ = intel_crtc->flip_work->gtt_offset;
10361         *cs++ = MI_NOOP;
10362
10363         return 0;
10364 }
10365
10366 static int intel_gen4_queue_flip(struct drm_device *dev,
10367                                  struct drm_crtc *crtc,
10368                                  struct drm_framebuffer *fb,
10369                                  struct drm_i915_gem_object *obj,
10370                                  struct drm_i915_gem_request *req,
10371                                  uint32_t flags)
10372 {
10373         struct drm_i915_private *dev_priv = to_i915(dev);
10374         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10375         u32 pf, pipesrc, *cs;
10376
10377         cs = intel_ring_begin(req, 4);
10378         if (IS_ERR(cs))
10379                 return PTR_ERR(cs);
10380
10381         /* i965+ uses the linear or tiled offsets from the
10382          * Display Registers (which do not change across a page-flip)
10383          * so we need only reprogram the base address.
10384          */
10385         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10386         *cs++ = fb->pitches[0];
10387         *cs++ = intel_crtc->flip_work->gtt_offset |
10388                 intel_fb_modifier_to_tiling(fb->modifier);
10389
10390         /* XXX Enabling the panel-fitter across page-flip is so far
10391          * untested on non-native modes, so ignore it for now.
10392          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10393          */
10394         pf = 0;
10395         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10396         *cs++ = pf | pipesrc;
10397
10398         return 0;
10399 }
10400
10401 static int intel_gen6_queue_flip(struct drm_device *dev,
10402                                  struct drm_crtc *crtc,
10403                                  struct drm_framebuffer *fb,
10404                                  struct drm_i915_gem_object *obj,
10405                                  struct drm_i915_gem_request *req,
10406                                  uint32_t flags)
10407 {
10408         struct drm_i915_private *dev_priv = to_i915(dev);
10409         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10410         u32 pf, pipesrc, *cs;
10411
10412         cs = intel_ring_begin(req, 4);
10413         if (IS_ERR(cs))
10414                 return PTR_ERR(cs);
10415
10416         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10417         *cs++ = fb->pitches[0] | intel_fb_modifier_to_tiling(fb->modifier);
10418         *cs++ = intel_crtc->flip_work->gtt_offset;
10419
10420         /* Contrary to the suggestions in the documentation,
10421          * "Enable Panel Fitter" does not seem to be required when page
10422          * flipping with a non-native mode, and worse causes a normal
10423          * modeset to fail.
10424          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10425          */
10426         pf = 0;
10427         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10428         *cs++ = pf | pipesrc;
10429
10430         return 0;
10431 }
10432
10433 static int intel_gen7_queue_flip(struct drm_device *dev,
10434                                  struct drm_crtc *crtc,
10435                                  struct drm_framebuffer *fb,
10436                                  struct drm_i915_gem_object *obj,
10437                                  struct drm_i915_gem_request *req,
10438                                  uint32_t flags)
10439 {
10440         struct drm_i915_private *dev_priv = to_i915(dev);
10441         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10442         u32 *cs, plane_bit = 0;
10443         int len, ret;
10444
10445         switch (intel_crtc->plane) {
10446         case PLANE_A:
10447                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10448                 break;
10449         case PLANE_B:
10450                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10451                 break;
10452         case PLANE_C:
10453                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10454                 break;
10455         default:
10456                 WARN_ONCE(1, "unknown plane in flip command\n");
10457                 return -ENODEV;
10458         }
10459
10460         len = 4;
10461         if (req->engine->id == RCS) {
10462                 len += 6;
10463                 /*
10464                  * On Gen 8, SRM is now taking an extra dword to accommodate
10465                  * 48bits addresses, and we need a NOOP for the batch size to
10466                  * stay even.
10467                  */
10468                 if (IS_GEN8(dev_priv))
10469                         len += 2;
10470         }
10471
10472         /*
10473          * BSpec MI_DISPLAY_FLIP for IVB:
10474          * "The full packet must be contained within the same cache line."
10475          *
10476          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10477          * cacheline, if we ever start emitting more commands before
10478          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10479          * then do the cacheline alignment, and finally emit the
10480          * MI_DISPLAY_FLIP.
10481          */
10482         ret = intel_ring_cacheline_align(req);
10483         if (ret)
10484                 return ret;
10485
10486         cs = intel_ring_begin(req, len);
10487         if (IS_ERR(cs))
10488                 return PTR_ERR(cs);
10489
10490         /* Unmask the flip-done completion message. Note that the bspec says that
10491          * we should do this for both the BCS and RCS, and that we must not unmask
10492          * more than one flip event at any time (or ensure that one flip message
10493          * can be sent by waiting for flip-done prior to queueing new flips).
10494          * Experimentation says that BCS works despite DERRMR masking all
10495          * flip-done completion events and that unmasking all planes at once
10496          * for the RCS also doesn't appear to drop events. Setting the DERRMR
10497          * to zero does lead to lockups within MI_DISPLAY_FLIP.
10498          */
10499         if (req->engine->id == RCS) {
10500                 *cs++ = MI_LOAD_REGISTER_IMM(1);
10501                 *cs++ = i915_mmio_reg_offset(DERRMR);
10502                 *cs++ = ~(DERRMR_PIPEA_PRI_FLIP_DONE |
10503                           DERRMR_PIPEB_PRI_FLIP_DONE |
10504                           DERRMR_PIPEC_PRI_FLIP_DONE);
10505                 if (IS_GEN8(dev_priv))
10506                         *cs++ = MI_STORE_REGISTER_MEM_GEN8 |
10507                                 MI_SRM_LRM_GLOBAL_GTT;
10508                 else
10509                         *cs++ = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
10510                 *cs++ = i915_mmio_reg_offset(DERRMR);
10511                 *cs++ = i915_ggtt_offset(req->engine->scratch) + 256;
10512                 if (IS_GEN8(dev_priv)) {
10513                         *cs++ = 0;
10514                         *cs++ = MI_NOOP;
10515                 }
10516         }
10517
10518         *cs++ = MI_DISPLAY_FLIP_I915 | plane_bit;
10519         *cs++ = fb->pitches[0] | intel_fb_modifier_to_tiling(fb->modifier);
10520         *cs++ = intel_crtc->flip_work->gtt_offset;
10521         *cs++ = MI_NOOP;
10522
10523         return 0;
10524 }
10525
10526 static bool use_mmio_flip(struct intel_engine_cs *engine,
10527                           struct drm_i915_gem_object *obj)
10528 {
10529         /*
10530          * This is not being used for older platforms, because
10531          * non-availability of flip done interrupt forces us to use
10532          * CS flips. Older platforms derive flip done using some clever
10533          * tricks involving the flip_pending status bits and vblank irqs.
10534          * So using MMIO flips there would disrupt this mechanism.
10535          */
10536
10537         if (engine == NULL)
10538                 return true;
10539
10540         if (INTEL_GEN(engine->i915) < 5)
10541                 return false;
10542
10543         if (i915.use_mmio_flip < 0)
10544                 return false;
10545         else if (i915.use_mmio_flip > 0)
10546                 return true;
10547         else if (i915.enable_execlists)
10548                 return true;
10549
10550         return engine != i915_gem_object_last_write_engine(obj);
10551 }
10552
10553 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
10554                              unsigned int rotation,
10555                              struct intel_flip_work *work)
10556 {
10557         struct drm_device *dev = intel_crtc->base.dev;
10558         struct drm_i915_private *dev_priv = to_i915(dev);
10559         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
10560         const enum pipe pipe = intel_crtc->pipe;
10561         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
10562
10563         ctl = I915_READ(PLANE_CTL(pipe, 0));
10564         ctl &= ~PLANE_CTL_TILED_MASK;
10565         switch (fb->modifier) {
10566         case DRM_FORMAT_MOD_LINEAR:
10567                 break;
10568         case I915_FORMAT_MOD_X_TILED:
10569                 ctl |= PLANE_CTL_TILED_X;
10570                 break;
10571         case I915_FORMAT_MOD_Y_TILED:
10572                 ctl |= PLANE_CTL_TILED_Y;
10573                 break;
10574         case I915_FORMAT_MOD_Yf_TILED:
10575                 ctl |= PLANE_CTL_TILED_YF;
10576                 break;
10577         default:
10578                 MISSING_CASE(fb->modifier);
10579         }
10580
10581         /*
10582          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
10583          * PLANE_SURF updates, the update is then guaranteed to be atomic.
10584          */
10585         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
10586         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
10587
10588         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
10589         POSTING_READ(PLANE_SURF(pipe, 0));
10590 }
10591
10592 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
10593                              struct intel_flip_work *work)
10594 {
10595         struct drm_device *dev = intel_crtc->base.dev;
10596         struct drm_i915_private *dev_priv = to_i915(dev);
10597         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
10598         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
10599         u32 dspcntr;
10600
10601         dspcntr = I915_READ(reg);
10602
10603         if (fb->modifier == I915_FORMAT_MOD_X_TILED)
10604                 dspcntr |= DISPPLANE_TILED;
10605         else
10606                 dspcntr &= ~DISPPLANE_TILED;
10607
10608         I915_WRITE(reg, dspcntr);
10609
10610         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
10611         POSTING_READ(DSPSURF(intel_crtc->plane));
10612 }
10613
10614 static void intel_mmio_flip_work_func(struct work_struct *w)
10615 {
10616         struct intel_flip_work *work =
10617                 container_of(w, struct intel_flip_work, mmio_work);
10618         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10619         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10620         struct intel_framebuffer *intel_fb =
10621                 to_intel_framebuffer(crtc->base.primary->fb);
10622         struct drm_i915_gem_object *obj = intel_fb->obj;
10623
10624         WARN_ON(i915_gem_object_wait(obj, 0, MAX_SCHEDULE_TIMEOUT, NULL) < 0);
10625
10626         intel_pipe_update_start(crtc);
10627
10628         if (INTEL_GEN(dev_priv) >= 9)
10629                 skl_do_mmio_flip(crtc, work->rotation, work);
10630         else
10631                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
10632                 ilk_do_mmio_flip(crtc, work);
10633
10634         intel_pipe_update_end(crtc, work);
10635 }
10636
10637 static int intel_default_queue_flip(struct drm_device *dev,
10638                                     struct drm_crtc *crtc,
10639                                     struct drm_framebuffer *fb,
10640                                     struct drm_i915_gem_object *obj,
10641                                     struct drm_i915_gem_request *req,
10642                                     uint32_t flags)
10643 {
10644         return -ENODEV;
10645 }
10646
10647 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
10648                                       struct intel_crtc *intel_crtc,
10649                                       struct intel_flip_work *work)
10650 {
10651         u32 addr, vblank;
10652
10653         if (!atomic_read(&work->pending))
10654                 return false;
10655
10656         smp_rmb();
10657
10658         vblank = intel_crtc_get_vblank_counter(intel_crtc);
10659         if (work->flip_ready_vblank == 0) {
10660                 if (work->flip_queued_req &&
10661                     !i915_gem_request_completed(work->flip_queued_req))
10662                         return false;
10663
10664                 work->flip_ready_vblank = vblank;
10665         }
10666
10667         if (vblank - work->flip_ready_vblank < 3)
10668                 return false;
10669
10670         /* Potential stall - if we see that the flip has happened,
10671          * assume a missed interrupt. */
10672         if (INTEL_GEN(dev_priv) >= 4)
10673                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
10674         else
10675                 addr = I915_READ(DSPADDR(intel_crtc->plane));
10676
10677         /* There is a potential issue here with a false positive after a flip
10678          * to the same address. We could address this by checking for a
10679          * non-incrementing frame counter.
10680          */
10681         return addr == work->gtt_offset;
10682 }
10683
10684 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
10685 {
10686         struct drm_device *dev = &dev_priv->drm;
10687         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10688         struct intel_flip_work *work;
10689
10690         WARN_ON(!in_interrupt());
10691
10692         if (crtc == NULL)
10693                 return;
10694
10695         spin_lock(&dev->event_lock);
10696         work = crtc->flip_work;
10697
10698         if (work != NULL && !is_mmio_work(work) &&
10699             __pageflip_stall_check_cs(dev_priv, crtc, work)) {
10700                 WARN_ONCE(1,
10701                           "Kicking stuck page flip: queued at %d, now %d\n",
10702                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(crtc));
10703                 page_flip_completed(crtc);
10704                 work = NULL;
10705         }
10706
10707         if (work != NULL && !is_mmio_work(work) &&
10708             intel_crtc_get_vblank_counter(crtc) - work->flip_queued_vblank > 1)
10709                 intel_queue_rps_boost_for_request(work->flip_queued_req);
10710         spin_unlock(&dev->event_lock);
10711 }
10712
10713 __maybe_unused
10714 static int intel_crtc_page_flip(struct drm_crtc *crtc,
10715                                 struct drm_framebuffer *fb,
10716                                 struct drm_pending_vblank_event *event,
10717                                 uint32_t page_flip_flags)
10718 {
10719         struct drm_device *dev = crtc->dev;
10720         struct drm_i915_private *dev_priv = to_i915(dev);
10721         struct drm_framebuffer *old_fb = crtc->primary->fb;
10722         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10723         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10724         struct drm_plane *primary = crtc->primary;
10725         enum pipe pipe = intel_crtc->pipe;
10726         struct intel_flip_work *work;
10727         struct intel_engine_cs *engine;
10728         bool mmio_flip;
10729         struct drm_i915_gem_request *request;
10730         struct i915_vma *vma;
10731         int ret;
10732
10733         /*
10734          * drm_mode_page_flip_ioctl() should already catch this, but double
10735          * check to be safe.  In the future we may enable pageflipping from
10736          * a disabled primary plane.
10737          */
10738         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
10739                 return -EBUSY;
10740
10741         /* Can't change pixel format via MI display flips. */
10742         if (fb->format != crtc->primary->fb->format)
10743                 return -EINVAL;
10744
10745         /*
10746          * TILEOFF/LINOFF registers can't be changed via MI display flips.
10747          * Note that pitch changes could also affect these register.
10748          */
10749         if (INTEL_GEN(dev_priv) > 3 &&
10750             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
10751              fb->pitches[0] != crtc->primary->fb->pitches[0]))
10752                 return -EINVAL;
10753
10754         if (i915_terminally_wedged(&dev_priv->gpu_error))
10755                 goto out_hang;
10756
10757         work = kzalloc(sizeof(*work), GFP_KERNEL);
10758         if (work == NULL)
10759                 return -ENOMEM;
10760
10761         work->event = event;
10762         work->crtc = crtc;
10763         work->old_fb = old_fb;
10764         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
10765
10766         ret = drm_crtc_vblank_get(crtc);
10767         if (ret)
10768                 goto free_work;
10769
10770         /* We borrow the event spin lock for protecting flip_work */
10771         spin_lock_irq(&dev->event_lock);
10772         if (intel_crtc->flip_work) {
10773                 /* Before declaring the flip queue wedged, check if
10774                  * the hardware completed the operation behind our backs.
10775                  */
10776                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
10777                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
10778                         page_flip_completed(intel_crtc);
10779                 } else {
10780                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
10781                         spin_unlock_irq(&dev->event_lock);
10782
10783                         drm_crtc_vblank_put(crtc);
10784                         kfree(work);
10785                         return -EBUSY;
10786                 }
10787         }
10788         intel_crtc->flip_work = work;
10789         spin_unlock_irq(&dev->event_lock);
10790
10791         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
10792                 flush_workqueue(dev_priv->wq);
10793
10794         /* Reference the objects for the scheduled work. */
10795         drm_framebuffer_reference(work->old_fb);
10796
10797         crtc->primary->fb = fb;
10798         update_state_fb(crtc->primary);
10799
10800         work->pending_flip_obj = i915_gem_object_get(obj);
10801
10802         ret = i915_mutex_lock_interruptible(dev);
10803         if (ret)
10804                 goto cleanup;
10805
10806         intel_crtc->reset_count = i915_reset_count(&dev_priv->gpu_error);
10807         if (i915_reset_backoff_or_wedged(&dev_priv->gpu_error)) {
10808                 ret = -EIO;
10809                 goto unlock;
10810         }
10811
10812         atomic_inc(&intel_crtc->unpin_work_count);
10813
10814         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10815                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
10816
10817         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
10818                 engine = dev_priv->engine[BCS];
10819                 if (fb->modifier != old_fb->modifier)
10820                         /* vlv: DISPLAY_FLIP fails to change tiling */
10821                         engine = NULL;
10822         } else if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv)) {
10823                 engine = dev_priv->engine[BCS];
10824         } else if (INTEL_GEN(dev_priv) >= 7) {
10825                 engine = i915_gem_object_last_write_engine(obj);
10826                 if (engine == NULL || engine->id != RCS)
10827                         engine = dev_priv->engine[BCS];
10828         } else {
10829                 engine = dev_priv->engine[RCS];
10830         }
10831
10832         mmio_flip = use_mmio_flip(engine, obj);
10833
10834         vma = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
10835         if (IS_ERR(vma)) {
10836                 ret = PTR_ERR(vma);
10837                 goto cleanup_pending;
10838         }
10839
10840         work->old_vma = to_intel_plane_state(primary->state)->vma;
10841         to_intel_plane_state(primary->state)->vma = vma;
10842
10843         work->gtt_offset = i915_ggtt_offset(vma) + intel_crtc->dspaddr_offset;
10844         work->rotation = crtc->primary->state->rotation;
10845
10846         /*
10847          * There's the potential that the next frame will not be compatible with
10848          * FBC, so we want to call pre_update() before the actual page flip.
10849          * The problem is that pre_update() caches some information about the fb
10850          * object, so we want to do this only after the object is pinned. Let's
10851          * be on the safe side and do this immediately before scheduling the
10852          * flip.
10853          */
10854         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
10855                              to_intel_plane_state(primary->state));
10856
10857         if (mmio_flip) {
10858                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
10859                 queue_work(system_unbound_wq, &work->mmio_work);
10860         } else {
10861                 request = i915_gem_request_alloc(engine,
10862                                                  dev_priv->kernel_context);
10863                 if (IS_ERR(request)) {
10864                         ret = PTR_ERR(request);
10865                         goto cleanup_unpin;
10866                 }
10867
10868                 ret = i915_gem_request_await_object(request, obj, false);
10869                 if (ret)
10870                         goto cleanup_request;
10871
10872                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
10873                                                    page_flip_flags);
10874                 if (ret)
10875                         goto cleanup_request;
10876
10877                 intel_mark_page_flip_active(intel_crtc, work);
10878
10879                 work->flip_queued_req = i915_gem_request_get(request);
10880                 i915_add_request(request);
10881         }
10882
10883         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
10884         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
10885                           to_intel_plane(primary)->frontbuffer_bit);
10886         mutex_unlock(&dev->struct_mutex);
10887
10888         intel_frontbuffer_flip_prepare(to_i915(dev),
10889                                        to_intel_plane(primary)->frontbuffer_bit);
10890
10891         trace_i915_flip_request(intel_crtc->plane, obj);
10892
10893         return 0;
10894
10895 cleanup_request:
10896         i915_add_request(request);
10897 cleanup_unpin:
10898         to_intel_plane_state(primary->state)->vma = work->old_vma;
10899         intel_unpin_fb_vma(vma);
10900 cleanup_pending:
10901         atomic_dec(&intel_crtc->unpin_work_count);
10902 unlock:
10903         mutex_unlock(&dev->struct_mutex);
10904 cleanup:
10905         crtc->primary->fb = old_fb;
10906         update_state_fb(crtc->primary);
10907
10908         i915_gem_object_put(obj);
10909         drm_framebuffer_unreference(work->old_fb);
10910
10911         spin_lock_irq(&dev->event_lock);
10912         intel_crtc->flip_work = NULL;
10913         spin_unlock_irq(&dev->event_lock);
10914
10915         drm_crtc_vblank_put(crtc);
10916 free_work:
10917         kfree(work);
10918
10919         if (ret == -EIO) {
10920                 struct drm_atomic_state *state;
10921                 struct drm_plane_state *plane_state;
10922
10923 out_hang:
10924                 state = drm_atomic_state_alloc(dev);
10925                 if (!state)
10926                         return -ENOMEM;
10927                 state->acquire_ctx = dev->mode_config.acquire_ctx;
10928
10929 retry:
10930                 plane_state = drm_atomic_get_plane_state(state, primary);
10931                 ret = PTR_ERR_OR_ZERO(plane_state);
10932                 if (!ret) {
10933                         drm_atomic_set_fb_for_plane(plane_state, fb);
10934
10935                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
10936                         if (!ret)
10937                                 ret = drm_atomic_commit(state);
10938                 }
10939
10940                 if (ret == -EDEADLK) {
10941                         drm_modeset_backoff(state->acquire_ctx);
10942                         drm_atomic_state_clear(state);
10943                         goto retry;
10944                 }
10945
10946                 drm_atomic_state_put(state);
10947
10948                 if (ret == 0 && event) {
10949                         spin_lock_irq(&dev->event_lock);
10950                         drm_crtc_send_vblank_event(crtc, event);
10951                         spin_unlock_irq(&dev->event_lock);
10952                 }
10953         }
10954         return ret;
10955 }
10956
10957
10958 /**
10959  * intel_wm_need_update - Check whether watermarks need updating
10960  * @plane: drm plane
10961  * @state: new plane state
10962  *
10963  * Check current plane state versus the new one to determine whether
10964  * watermarks need to be recalculated.
10965  *
10966  * Returns true or false.
10967  */
10968 static bool intel_wm_need_update(struct drm_plane *plane,
10969                                  struct drm_plane_state *state)
10970 {
10971         struct intel_plane_state *new = to_intel_plane_state(state);
10972         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10973
10974         /* Update watermarks on tiling or size changes. */
10975         if (new->base.visible != cur->base.visible)
10976                 return true;
10977
10978         if (!cur->base.fb || !new->base.fb)
10979                 return false;
10980
10981         if (cur->base.fb->modifier != new->base.fb->modifier ||
10982             cur->base.rotation != new->base.rotation ||
10983             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10984             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10985             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10986             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10987                 return true;
10988
10989         return false;
10990 }
10991
10992 static bool needs_scaling(struct intel_plane_state *state)
10993 {
10994         int src_w = drm_rect_width(&state->base.src) >> 16;
10995         int src_h = drm_rect_height(&state->base.src) >> 16;
10996         int dst_w = drm_rect_width(&state->base.dst);
10997         int dst_h = drm_rect_height(&state->base.dst);
10998
10999         return (src_w != dst_w || src_h != dst_h);
11000 }
11001
11002 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11003                                     struct drm_plane_state *plane_state)
11004 {
11005         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11006         struct drm_crtc *crtc = crtc_state->crtc;
11007         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11008         struct intel_plane *plane = to_intel_plane(plane_state->plane);
11009         struct drm_device *dev = crtc->dev;
11010         struct drm_i915_private *dev_priv = to_i915(dev);
11011         struct intel_plane_state *old_plane_state =
11012                 to_intel_plane_state(plane->base.state);
11013         bool mode_changed = needs_modeset(crtc_state);
11014         bool was_crtc_enabled = crtc->state->active;
11015         bool is_crtc_enabled = crtc_state->active;
11016         bool turn_off, turn_on, visible, was_visible;
11017         struct drm_framebuffer *fb = plane_state->fb;
11018         int ret;
11019
11020         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
11021                 ret = skl_update_scaler_plane(
11022                         to_intel_crtc_state(crtc_state),
11023                         to_intel_plane_state(plane_state));
11024                 if (ret)
11025                         return ret;
11026         }
11027
11028         was_visible = old_plane_state->base.visible;
11029         visible = plane_state->visible;
11030
11031         if (!was_crtc_enabled && WARN_ON(was_visible))
11032                 was_visible = false;
11033
11034         /*
11035          * Visibility is calculated as if the crtc was on, but
11036          * after scaler setup everything depends on it being off
11037          * when the crtc isn't active.
11038          *
11039          * FIXME this is wrong for watermarks. Watermarks should also
11040          * be computed as if the pipe would be active. Perhaps move
11041          * per-plane wm computation to the .check_plane() hook, and
11042          * only combine the results from all planes in the current place?
11043          */
11044         if (!is_crtc_enabled) {
11045                 plane_state->visible = visible = false;
11046                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
11047         }
11048
11049         if (!was_visible && !visible)
11050                 return 0;
11051
11052         if (fb != old_plane_state->base.fb)
11053                 pipe_config->fb_changed = true;
11054
11055         turn_off = was_visible && (!visible || mode_changed);
11056         turn_on = visible && (!was_visible || mode_changed);
11057
11058         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11059                          intel_crtc->base.base.id, intel_crtc->base.name,
11060                          plane->base.base.id, plane->base.name,
11061                          fb ? fb->base.id : -1);
11062
11063         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11064                          plane->base.base.id, plane->base.name,
11065                          was_visible, visible,
11066                          turn_off, turn_on, mode_changed);
11067
11068         if (turn_on) {
11069                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11070                         pipe_config->update_wm_pre = true;
11071
11072                 /* must disable cxsr around plane enable/disable */
11073                 if (plane->id != PLANE_CURSOR)
11074                         pipe_config->disable_cxsr = true;
11075         } else if (turn_off) {
11076                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11077                         pipe_config->update_wm_post = true;
11078
11079                 /* must disable cxsr around plane enable/disable */
11080                 if (plane->id != PLANE_CURSOR)
11081                         pipe_config->disable_cxsr = true;
11082         } else if (intel_wm_need_update(&plane->base, plane_state)) {
11083                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
11084                         /* FIXME bollocks */
11085                         pipe_config->update_wm_pre = true;
11086                         pipe_config->update_wm_post = true;
11087                 }
11088         }
11089
11090         if (visible || was_visible)
11091                 pipe_config->fb_bits |= plane->frontbuffer_bit;
11092
11093         /*
11094          * WaCxSRDisabledForSpriteScaling:ivb
11095          *
11096          * cstate->update_wm was already set above, so this flag will
11097          * take effect when we commit and program watermarks.
11098          */
11099         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
11100             needs_scaling(to_intel_plane_state(plane_state)) &&
11101             !needs_scaling(old_plane_state))
11102                 pipe_config->disable_lp_wm = true;
11103
11104         return 0;
11105 }
11106
11107 static bool encoders_cloneable(const struct intel_encoder *a,
11108                                const struct intel_encoder *b)
11109 {
11110         /* masks could be asymmetric, so check both ways */
11111         return a == b || (a->cloneable & (1 << b->type) &&
11112                           b->cloneable & (1 << a->type));
11113 }
11114
11115 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11116                                          struct intel_crtc *crtc,
11117                                          struct intel_encoder *encoder)
11118 {
11119         struct intel_encoder *source_encoder;
11120         struct drm_connector *connector;
11121         struct drm_connector_state *connector_state;
11122         int i;
11123
11124         for_each_new_connector_in_state(state, connector, connector_state, i) {
11125                 if (connector_state->crtc != &crtc->base)
11126                         continue;
11127
11128                 source_encoder =
11129                         to_intel_encoder(connector_state->best_encoder);
11130                 if (!encoders_cloneable(encoder, source_encoder))
11131                         return false;
11132         }
11133
11134         return true;
11135 }
11136
11137 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11138                                    struct drm_crtc_state *crtc_state)
11139 {
11140         struct drm_device *dev = crtc->dev;
11141         struct drm_i915_private *dev_priv = to_i915(dev);
11142         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11143         struct intel_crtc_state *pipe_config =
11144                 to_intel_crtc_state(crtc_state);
11145         struct drm_atomic_state *state = crtc_state->state;
11146         int ret;
11147         bool mode_changed = needs_modeset(crtc_state);
11148
11149         if (mode_changed && !crtc_state->active)
11150                 pipe_config->update_wm_post = true;
11151
11152         if (mode_changed && crtc_state->enable &&
11153             dev_priv->display.crtc_compute_clock &&
11154             !WARN_ON(pipe_config->shared_dpll)) {
11155                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11156                                                            pipe_config);
11157                 if (ret)
11158                         return ret;
11159         }
11160
11161         if (crtc_state->color_mgmt_changed) {
11162                 ret = intel_color_check(crtc, crtc_state);
11163                 if (ret)
11164                         return ret;
11165
11166                 /*
11167                  * Changing color management on Intel hardware is
11168                  * handled as part of planes update.
11169                  */
11170                 crtc_state->planes_changed = true;
11171         }
11172
11173         ret = 0;
11174         if (dev_priv->display.compute_pipe_wm) {
11175                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11176                 if (ret) {
11177                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11178                         return ret;
11179                 }
11180         }
11181
11182         if (dev_priv->display.compute_intermediate_wm &&
11183             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11184                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11185                         return 0;
11186
11187                 /*
11188                  * Calculate 'intermediate' watermarks that satisfy both the
11189                  * old state and the new state.  We can program these
11190                  * immediately.
11191                  */
11192                 ret = dev_priv->display.compute_intermediate_wm(dev,
11193                                                                 intel_crtc,
11194                                                                 pipe_config);
11195                 if (ret) {
11196                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11197                         return ret;
11198                 }
11199         } else if (dev_priv->display.compute_intermediate_wm) {
11200                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
11201                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
11202         }
11203
11204         if (INTEL_GEN(dev_priv) >= 9) {
11205                 if (mode_changed)
11206                         ret = skl_update_scaler_crtc(pipe_config);
11207
11208                 if (!ret)
11209                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11210                                                             pipe_config);
11211                 if (!ret)
11212                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11213                                                          pipe_config);
11214         }
11215
11216         return ret;
11217 }
11218
11219 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11220         .atomic_begin = intel_begin_crtc_commit,
11221         .atomic_flush = intel_finish_crtc_commit,
11222         .atomic_check = intel_crtc_atomic_check,
11223 };
11224
11225 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11226 {
11227         struct intel_connector *connector;
11228         struct drm_connector_list_iter conn_iter;
11229
11230         drm_connector_list_iter_begin(dev, &conn_iter);
11231         for_each_intel_connector_iter(connector, &conn_iter) {
11232                 if (connector->base.state->crtc)
11233                         drm_connector_unreference(&connector->base);
11234
11235                 if (connector->base.encoder) {
11236                         connector->base.state->best_encoder =
11237                                 connector->base.encoder;
11238                         connector->base.state->crtc =
11239                                 connector->base.encoder->crtc;
11240
11241                         drm_connector_reference(&connector->base);
11242                 } else {
11243                         connector->base.state->best_encoder = NULL;
11244                         connector->base.state->crtc = NULL;
11245                 }
11246         }
11247         drm_connector_list_iter_end(&conn_iter);
11248 }
11249
11250 static void
11251 connected_sink_compute_bpp(struct intel_connector *connector,
11252                            struct intel_crtc_state *pipe_config)
11253 {
11254         const struct drm_display_info *info = &connector->base.display_info;
11255         int bpp = pipe_config->pipe_bpp;
11256
11257         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11258                       connector->base.base.id,
11259                       connector->base.name);
11260
11261         /* Don't use an invalid EDID bpc value */
11262         if (info->bpc != 0 && info->bpc * 3 < bpp) {
11263                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11264                               bpp, info->bpc * 3);
11265                 pipe_config->pipe_bpp = info->bpc * 3;
11266         }
11267
11268         /* Clamp bpp to 8 on screens without EDID 1.4 */
11269         if (info->bpc == 0 && bpp > 24) {
11270                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11271                               bpp);
11272                 pipe_config->pipe_bpp = 24;
11273         }
11274 }
11275
11276 static int
11277 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11278                           struct intel_crtc_state *pipe_config)
11279 {
11280         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11281         struct drm_atomic_state *state;
11282         struct drm_connector *connector;
11283         struct drm_connector_state *connector_state;
11284         int bpp, i;
11285
11286         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11287             IS_CHERRYVIEW(dev_priv)))
11288                 bpp = 10*3;
11289         else if (INTEL_GEN(dev_priv) >= 5)
11290                 bpp = 12*3;
11291         else
11292                 bpp = 8*3;
11293
11294
11295         pipe_config->pipe_bpp = bpp;
11296
11297         state = pipe_config->base.state;
11298
11299         /* Clamp display bpp to EDID value */
11300         for_each_new_connector_in_state(state, connector, connector_state, i) {
11301                 if (connector_state->crtc != &crtc->base)
11302                         continue;
11303
11304                 connected_sink_compute_bpp(to_intel_connector(connector),
11305                                            pipe_config);
11306         }
11307
11308         return bpp;
11309 }
11310
11311 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11312 {
11313         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11314                         "type: 0x%x flags: 0x%x\n",
11315                 mode->crtc_clock,
11316                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11317                 mode->crtc_hsync_end, mode->crtc_htotal,
11318                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11319                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11320 }
11321
11322 static inline void
11323 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11324                       unsigned int lane_count, struct intel_link_m_n *m_n)
11325 {
11326         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11327                       id, lane_count,
11328                       m_n->gmch_m, m_n->gmch_n,
11329                       m_n->link_m, m_n->link_n, m_n->tu);
11330 }
11331
11332 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11333                                    struct intel_crtc_state *pipe_config,
11334                                    const char *context)
11335 {
11336         struct drm_device *dev = crtc->base.dev;
11337         struct drm_i915_private *dev_priv = to_i915(dev);
11338         struct drm_plane *plane;
11339         struct intel_plane *intel_plane;
11340         struct intel_plane_state *state;
11341         struct drm_framebuffer *fb;
11342
11343         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11344                       crtc->base.base.id, crtc->base.name, context);
11345
11346         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11347                       transcoder_name(pipe_config->cpu_transcoder),
11348                       pipe_config->pipe_bpp, pipe_config->dither);
11349
11350         if (pipe_config->has_pch_encoder)
11351                 intel_dump_m_n_config(pipe_config, "fdi",
11352                                       pipe_config->fdi_lanes,
11353                                       &pipe_config->fdi_m_n);
11354
11355         if (intel_crtc_has_dp_encoder(pipe_config)) {
11356                 intel_dump_m_n_config(pipe_config, "dp m_n",
11357                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11358                 if (pipe_config->has_drrs)
11359                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11360                                               pipe_config->lane_count,
11361                                               &pipe_config->dp_m2_n2);
11362         }
11363
11364         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11365                       pipe_config->has_audio, pipe_config->has_infoframe);
11366
11367         DRM_DEBUG_KMS("requested mode:\n");
11368         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11369         DRM_DEBUG_KMS("adjusted mode:\n");
11370         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11371         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11372         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11373                       pipe_config->port_clock,
11374                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11375                       pipe_config->pixel_rate);
11376
11377         if (INTEL_GEN(dev_priv) >= 9)
11378                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11379                               crtc->num_scalers,
11380                               pipe_config->scaler_state.scaler_users,
11381                               pipe_config->scaler_state.scaler_id);
11382
11383         if (HAS_GMCH_DISPLAY(dev_priv))
11384                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11385                               pipe_config->gmch_pfit.control,
11386                               pipe_config->gmch_pfit.pgm_ratios,
11387                               pipe_config->gmch_pfit.lvds_border_bits);
11388         else
11389                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11390                               pipe_config->pch_pfit.pos,
11391                               pipe_config->pch_pfit.size,
11392                               enableddisabled(pipe_config->pch_pfit.enabled));
11393
11394         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11395                       pipe_config->ips_enabled, pipe_config->double_wide);
11396
11397         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11398
11399         DRM_DEBUG_KMS("planes on this crtc\n");
11400         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11401                 struct drm_format_name_buf format_name;
11402                 intel_plane = to_intel_plane(plane);
11403                 if (intel_plane->pipe != crtc->pipe)
11404                         continue;
11405
11406                 state = to_intel_plane_state(plane->state);
11407                 fb = state->base.fb;
11408                 if (!fb) {
11409                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11410                                       plane->base.id, plane->name, state->scaler_id);
11411                         continue;
11412                 }
11413
11414                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11415                               plane->base.id, plane->name,
11416                               fb->base.id, fb->width, fb->height,
11417                               drm_get_format_name(fb->format->format, &format_name));
11418                 if (INTEL_GEN(dev_priv) >= 9)
11419                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11420                                       state->scaler_id,
11421                                       state->base.src.x1 >> 16,
11422                                       state->base.src.y1 >> 16,
11423                                       drm_rect_width(&state->base.src) >> 16,
11424                                       drm_rect_height(&state->base.src) >> 16,
11425                                       state->base.dst.x1, state->base.dst.y1,
11426                                       drm_rect_width(&state->base.dst),
11427                                       drm_rect_height(&state->base.dst));
11428         }
11429 }
11430
11431 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11432 {
11433         struct drm_device *dev = state->dev;
11434         struct drm_connector *connector;
11435         unsigned int used_ports = 0;
11436         unsigned int used_mst_ports = 0;
11437
11438         /*
11439          * Walk the connector list instead of the encoder
11440          * list to detect the problem on ddi platforms
11441          * where there's just one encoder per digital port.
11442          */
11443         drm_for_each_connector(connector, dev) {
11444                 struct drm_connector_state *connector_state;
11445                 struct intel_encoder *encoder;
11446
11447                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
11448                 if (!connector_state)
11449                         connector_state = connector->state;
11450
11451                 if (!connector_state->best_encoder)
11452                         continue;
11453
11454                 encoder = to_intel_encoder(connector_state->best_encoder);
11455
11456                 WARN_ON(!connector_state->crtc);
11457
11458                 switch (encoder->type) {
11459                         unsigned int port_mask;
11460                 case INTEL_OUTPUT_UNKNOWN:
11461                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11462                                 break;
11463                 case INTEL_OUTPUT_DP:
11464                 case INTEL_OUTPUT_HDMI:
11465                 case INTEL_OUTPUT_EDP:
11466                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
11467
11468                         /* the same port mustn't appear more than once */
11469                         if (used_ports & port_mask)
11470                                 return false;
11471
11472                         used_ports |= port_mask;
11473                         break;
11474                 case INTEL_OUTPUT_DP_MST:
11475                         used_mst_ports |=
11476                                 1 << enc_to_mst(&encoder->base)->primary->port;
11477                         break;
11478                 default:
11479                         break;
11480                 }
11481         }
11482
11483         /* can't mix MST and SST/HDMI on the same port */
11484         if (used_ports & used_mst_ports)
11485                 return false;
11486
11487         return true;
11488 }
11489
11490 static void
11491 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11492 {
11493         struct drm_i915_private *dev_priv =
11494                 to_i915(crtc_state->base.crtc->dev);
11495         struct intel_crtc_scaler_state scaler_state;
11496         struct intel_dpll_hw_state dpll_hw_state;
11497         struct intel_shared_dpll *shared_dpll;
11498         struct intel_crtc_wm_state wm_state;
11499         bool force_thru;
11500
11501         /* FIXME: before the switch to atomic started, a new pipe_config was
11502          * kzalloc'd. Code that depends on any field being zero should be
11503          * fixed, so that the crtc_state can be safely duplicated. For now,
11504          * only fields that are know to not cause problems are preserved. */
11505
11506         scaler_state = crtc_state->scaler_state;
11507         shared_dpll = crtc_state->shared_dpll;
11508         dpll_hw_state = crtc_state->dpll_hw_state;
11509         force_thru = crtc_state->pch_pfit.force_thru;
11510         if (IS_G4X(dev_priv) ||
11511             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11512                 wm_state = crtc_state->wm;
11513
11514         /* Keep base drm_crtc_state intact, only clear our extended struct */
11515         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11516         memset(&crtc_state->base + 1, 0,
11517                sizeof(*crtc_state) - sizeof(crtc_state->base));
11518
11519         crtc_state->scaler_state = scaler_state;
11520         crtc_state->shared_dpll = shared_dpll;
11521         crtc_state->dpll_hw_state = dpll_hw_state;
11522         crtc_state->pch_pfit.force_thru = force_thru;
11523         if (IS_G4X(dev_priv) ||
11524             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11525                 crtc_state->wm = wm_state;
11526 }
11527
11528 static int
11529 intel_modeset_pipe_config(struct drm_crtc *crtc,
11530                           struct intel_crtc_state *pipe_config)
11531 {
11532         struct drm_atomic_state *state = pipe_config->base.state;
11533         struct intel_encoder *encoder;
11534         struct drm_connector *connector;
11535         struct drm_connector_state *connector_state;
11536         int base_bpp, ret = -EINVAL;
11537         int i;
11538         bool retry = true;
11539
11540         clear_intel_crtc_state(pipe_config);
11541
11542         pipe_config->cpu_transcoder =
11543                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11544
11545         /*
11546          * Sanitize sync polarity flags based on requested ones. If neither
11547          * positive or negative polarity is requested, treat this as meaning
11548          * negative polarity.
11549          */
11550         if (!(pipe_config->base.adjusted_mode.flags &
11551               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11552                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11553
11554         if (!(pipe_config->base.adjusted_mode.flags &
11555               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11556                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11557
11558         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11559                                              pipe_config);
11560         if (base_bpp < 0)
11561                 goto fail;
11562
11563         /*
11564          * Determine the real pipe dimensions. Note that stereo modes can
11565          * increase the actual pipe size due to the frame doubling and
11566          * insertion of additional space for blanks between the frame. This
11567          * is stored in the crtc timings. We use the requested mode to do this
11568          * computation to clearly distinguish it from the adjusted mode, which
11569          * can be changed by the connectors in the below retry loop.
11570          */
11571         drm_mode_get_hv_timing(&pipe_config->base.mode,
11572                                &pipe_config->pipe_src_w,
11573                                &pipe_config->pipe_src_h);
11574
11575         for_each_new_connector_in_state(state, connector, connector_state, i) {
11576                 if (connector_state->crtc != crtc)
11577                         continue;
11578
11579                 encoder = to_intel_encoder(connector_state->best_encoder);
11580
11581                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11582                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11583                         goto fail;
11584                 }
11585
11586                 /*
11587                  * Determine output_types before calling the .compute_config()
11588                  * hooks so that the hooks can use this information safely.
11589                  */
11590                 pipe_config->output_types |= 1 << encoder->type;
11591         }
11592
11593 encoder_retry:
11594         /* Ensure the port clock defaults are reset when retrying. */
11595         pipe_config->port_clock = 0;
11596         pipe_config->pixel_multiplier = 1;
11597
11598         /* Fill in default crtc timings, allow encoders to overwrite them. */
11599         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11600                               CRTC_STEREO_DOUBLE);
11601
11602         /* Pass our mode to the connectors and the CRTC to give them a chance to
11603          * adjust it according to limitations or connector properties, and also
11604          * a chance to reject the mode entirely.
11605          */
11606         for_each_new_connector_in_state(state, connector, connector_state, i) {
11607                 if (connector_state->crtc != crtc)
11608                         continue;
11609
11610                 encoder = to_intel_encoder(connector_state->best_encoder);
11611
11612                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11613                         DRM_DEBUG_KMS("Encoder config failure\n");
11614                         goto fail;
11615                 }
11616         }
11617
11618         /* Set default port clock if not overwritten by the encoder. Needs to be
11619          * done afterwards in case the encoder adjusts the mode. */
11620         if (!pipe_config->port_clock)
11621                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11622                         * pipe_config->pixel_multiplier;
11623
11624         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11625         if (ret < 0) {
11626                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11627                 goto fail;
11628         }
11629
11630         if (ret == RETRY) {
11631                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11632                         ret = -EINVAL;
11633                         goto fail;
11634                 }
11635
11636                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11637                 retry = false;
11638                 goto encoder_retry;
11639         }
11640
11641         /* Dithering seems to not pass-through bits correctly when it should, so
11642          * only enable it on 6bpc panels and when its not a compliance
11643          * test requesting 6bpc video pattern.
11644          */
11645         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11646                 !pipe_config->dither_force_disable;
11647         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11648                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11649
11650 fail:
11651         return ret;
11652 }
11653
11654 static void
11655 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
11656 {
11657         struct drm_crtc *crtc;
11658         struct drm_crtc_state *new_crtc_state;
11659         int i;
11660
11661         /* Double check state. */
11662         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11663                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
11664
11665                 /*
11666                  * Update legacy state to satisfy fbc code. This can
11667                  * be removed when fbc uses the atomic state.
11668                  */
11669                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
11670                         struct drm_plane_state *plane_state = crtc->primary->state;
11671
11672                         crtc->primary->fb = plane_state->fb;
11673                         crtc->x = plane_state->src_x >> 16;
11674                         crtc->y = plane_state->src_y >> 16;
11675                 }
11676         }
11677 }
11678
11679 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11680 {
11681         int diff;
11682
11683         if (clock1 == clock2)
11684                 return true;
11685
11686         if (!clock1 || !clock2)
11687                 return false;
11688
11689         diff = abs(clock1 - clock2);
11690
11691         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11692                 return true;
11693
11694         return false;
11695 }
11696
11697 static bool
11698 intel_compare_m_n(unsigned int m, unsigned int n,
11699                   unsigned int m2, unsigned int n2,
11700                   bool exact)
11701 {
11702         if (m == m2 && n == n2)
11703                 return true;
11704
11705         if (exact || !m || !n || !m2 || !n2)
11706                 return false;
11707
11708         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11709
11710         if (n > n2) {
11711                 while (n > n2) {
11712                         m2 <<= 1;
11713                         n2 <<= 1;
11714                 }
11715         } else if (n < n2) {
11716                 while (n < n2) {
11717                         m <<= 1;
11718                         n <<= 1;
11719                 }
11720         }
11721
11722         if (n != n2)
11723                 return false;
11724
11725         return intel_fuzzy_clock_check(m, m2);
11726 }
11727
11728 static bool
11729 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11730                        struct intel_link_m_n *m2_n2,
11731                        bool adjust)
11732 {
11733         if (m_n->tu == m2_n2->tu &&
11734             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11735                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11736             intel_compare_m_n(m_n->link_m, m_n->link_n,
11737                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11738                 if (adjust)
11739                         *m2_n2 = *m_n;
11740
11741                 return true;
11742         }
11743
11744         return false;
11745 }
11746
11747 static void __printf(3, 4)
11748 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11749 {
11750         char *level;
11751         unsigned int category;
11752         struct va_format vaf;
11753         va_list args;
11754
11755         if (adjust) {
11756                 level = KERN_DEBUG;
11757                 category = DRM_UT_KMS;
11758         } else {
11759                 level = KERN_ERR;
11760                 category = DRM_UT_NONE;
11761         }
11762
11763         va_start(args, format);
11764         vaf.fmt = format;
11765         vaf.va = &args;
11766
11767         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
11768
11769         va_end(args);
11770 }
11771
11772 static bool
11773 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11774                           struct intel_crtc_state *current_config,
11775                           struct intel_crtc_state *pipe_config,
11776                           bool adjust)
11777 {
11778         bool ret = true;
11779
11780 #define PIPE_CONF_CHECK_X(name) \
11781         if (current_config->name != pipe_config->name) { \
11782                 pipe_config_err(adjust, __stringify(name), \
11783                           "(expected 0x%08x, found 0x%08x)\n", \
11784                           current_config->name, \
11785                           pipe_config->name); \
11786                 ret = false; \
11787         }
11788
11789 #define PIPE_CONF_CHECK_I(name) \
11790         if (current_config->name != pipe_config->name) { \
11791                 pipe_config_err(adjust, __stringify(name), \
11792                           "(expected %i, found %i)\n", \
11793                           current_config->name, \
11794                           pipe_config->name); \
11795                 ret = false; \
11796         }
11797
11798 #define PIPE_CONF_CHECK_P(name) \
11799         if (current_config->name != pipe_config->name) { \
11800                 pipe_config_err(adjust, __stringify(name), \
11801                           "(expected %p, found %p)\n", \
11802                           current_config->name, \
11803                           pipe_config->name); \
11804                 ret = false; \
11805         }
11806
11807 #define PIPE_CONF_CHECK_M_N(name) \
11808         if (!intel_compare_link_m_n(&current_config->name, \
11809                                     &pipe_config->name,\
11810                                     adjust)) { \
11811                 pipe_config_err(adjust, __stringify(name), \
11812                           "(expected tu %i gmch %i/%i link %i/%i, " \
11813                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11814                           current_config->name.tu, \
11815                           current_config->name.gmch_m, \
11816                           current_config->name.gmch_n, \
11817                           current_config->name.link_m, \
11818                           current_config->name.link_n, \
11819                           pipe_config->name.tu, \
11820                           pipe_config->name.gmch_m, \
11821                           pipe_config->name.gmch_n, \
11822                           pipe_config->name.link_m, \
11823                           pipe_config->name.link_n); \
11824                 ret = false; \
11825         }
11826
11827 /* This is required for BDW+ where there is only one set of registers for
11828  * switching between high and low RR.
11829  * This macro can be used whenever a comparison has to be made between one
11830  * hw state and multiple sw state variables.
11831  */
11832 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11833         if (!intel_compare_link_m_n(&current_config->name, \
11834                                     &pipe_config->name, adjust) && \
11835             !intel_compare_link_m_n(&current_config->alt_name, \
11836                                     &pipe_config->name, adjust)) { \
11837                 pipe_config_err(adjust, __stringify(name), \
11838                           "(expected tu %i gmch %i/%i link %i/%i, " \
11839                           "or tu %i gmch %i/%i link %i/%i, " \
11840                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11841                           current_config->name.tu, \
11842                           current_config->name.gmch_m, \
11843                           current_config->name.gmch_n, \
11844                           current_config->name.link_m, \
11845                           current_config->name.link_n, \
11846                           current_config->alt_name.tu, \
11847                           current_config->alt_name.gmch_m, \
11848                           current_config->alt_name.gmch_n, \
11849                           current_config->alt_name.link_m, \
11850                           current_config->alt_name.link_n, \
11851                           pipe_config->name.tu, \
11852                           pipe_config->name.gmch_m, \
11853                           pipe_config->name.gmch_n, \
11854                           pipe_config->name.link_m, \
11855                           pipe_config->name.link_n); \
11856                 ret = false; \
11857         }
11858
11859 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11860         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11861                 pipe_config_err(adjust, __stringify(name), \
11862                           "(%x) (expected %i, found %i)\n", \
11863                           (mask), \
11864                           current_config->name & (mask), \
11865                           pipe_config->name & (mask)); \
11866                 ret = false; \
11867         }
11868
11869 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11870         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11871                 pipe_config_err(adjust, __stringify(name), \
11872                           "(expected %i, found %i)\n", \
11873                           current_config->name, \
11874                           pipe_config->name); \
11875                 ret = false; \
11876         }
11877
11878 #define PIPE_CONF_QUIRK(quirk)  \
11879         ((current_config->quirks | pipe_config->quirks) & (quirk))
11880
11881         PIPE_CONF_CHECK_I(cpu_transcoder);
11882
11883         PIPE_CONF_CHECK_I(has_pch_encoder);
11884         PIPE_CONF_CHECK_I(fdi_lanes);
11885         PIPE_CONF_CHECK_M_N(fdi_m_n);
11886
11887         PIPE_CONF_CHECK_I(lane_count);
11888         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11889
11890         if (INTEL_GEN(dev_priv) < 8) {
11891                 PIPE_CONF_CHECK_M_N(dp_m_n);
11892
11893                 if (current_config->has_drrs)
11894                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11895         } else
11896                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11897
11898         PIPE_CONF_CHECK_X(output_types);
11899
11900         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11901         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11902         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11903         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11904         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11905         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11906
11907         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11908         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11909         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11910         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11911         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11912         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11913
11914         PIPE_CONF_CHECK_I(pixel_multiplier);
11915         PIPE_CONF_CHECK_I(has_hdmi_sink);
11916         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11917             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11918                 PIPE_CONF_CHECK_I(limited_color_range);
11919
11920         PIPE_CONF_CHECK_I(hdmi_scrambling);
11921         PIPE_CONF_CHECK_I(hdmi_high_tmds_clock_ratio);
11922         PIPE_CONF_CHECK_I(has_infoframe);
11923
11924         PIPE_CONF_CHECK_I(has_audio);
11925
11926         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11927                               DRM_MODE_FLAG_INTERLACE);
11928
11929         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11930                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11931                                       DRM_MODE_FLAG_PHSYNC);
11932                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11933                                       DRM_MODE_FLAG_NHSYNC);
11934                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11935                                       DRM_MODE_FLAG_PVSYNC);
11936                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11937                                       DRM_MODE_FLAG_NVSYNC);
11938         }
11939
11940         PIPE_CONF_CHECK_X(gmch_pfit.control);
11941         /* pfit ratios are autocomputed by the hw on gen4+ */
11942         if (INTEL_GEN(dev_priv) < 4)
11943                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11944         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11945
11946         if (!adjust) {
11947                 PIPE_CONF_CHECK_I(pipe_src_w);
11948                 PIPE_CONF_CHECK_I(pipe_src_h);
11949
11950                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
11951                 if (current_config->pch_pfit.enabled) {
11952                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11953                         PIPE_CONF_CHECK_X(pch_pfit.size);
11954                 }
11955
11956                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11957                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11958         }
11959
11960         /* BDW+ don't expose a synchronous way to read the state */
11961         if (IS_HASWELL(dev_priv))
11962                 PIPE_CONF_CHECK_I(ips_enabled);
11963
11964         PIPE_CONF_CHECK_I(double_wide);
11965
11966         PIPE_CONF_CHECK_P(shared_dpll);
11967         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11968         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11969         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11970         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11971         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11972         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11973         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11974         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11975         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11976
11977         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11978         PIPE_CONF_CHECK_X(dsi_pll.div);
11979
11980         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11981                 PIPE_CONF_CHECK_I(pipe_bpp);
11982
11983         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11984         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11985
11986 #undef PIPE_CONF_CHECK_X
11987 #undef PIPE_CONF_CHECK_I
11988 #undef PIPE_CONF_CHECK_P
11989 #undef PIPE_CONF_CHECK_FLAGS
11990 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11991 #undef PIPE_CONF_QUIRK
11992
11993         return ret;
11994 }
11995
11996 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11997                                            const struct intel_crtc_state *pipe_config)
11998 {
11999         if (pipe_config->has_pch_encoder) {
12000                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12001                                                             &pipe_config->fdi_m_n);
12002                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12003
12004                 /*
12005                  * FDI already provided one idea for the dotclock.
12006                  * Yell if the encoder disagrees.
12007                  */
12008                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12009                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12010                      fdi_dotclock, dotclock);
12011         }
12012 }
12013
12014 static void verify_wm_state(struct drm_crtc *crtc,
12015                             struct drm_crtc_state *new_state)
12016 {
12017         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12018         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12019         struct skl_pipe_wm hw_wm, *sw_wm;
12020         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12021         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12022         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12023         const enum pipe pipe = intel_crtc->pipe;
12024         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12025
12026         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12027                 return;
12028
12029         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
12030         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12031
12032         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12033         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12034
12035         /* planes */
12036         for_each_universal_plane(dev_priv, pipe, plane) {
12037                 hw_plane_wm = &hw_wm.planes[plane];
12038                 sw_plane_wm = &sw_wm->planes[plane];
12039
12040                 /* Watermarks */
12041                 for (level = 0; level <= max_level; level++) {
12042                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12043                                                 &sw_plane_wm->wm[level]))
12044                                 continue;
12045
12046                         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",
12047                                   pipe_name(pipe), plane + 1, level,
12048                                   sw_plane_wm->wm[level].plane_en,
12049                                   sw_plane_wm->wm[level].plane_res_b,
12050                                   sw_plane_wm->wm[level].plane_res_l,
12051                                   hw_plane_wm->wm[level].plane_en,
12052                                   hw_plane_wm->wm[level].plane_res_b,
12053                                   hw_plane_wm->wm[level].plane_res_l);
12054                 }
12055
12056                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12057                                          &sw_plane_wm->trans_wm)) {
12058                         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",
12059                                   pipe_name(pipe), plane + 1,
12060                                   sw_plane_wm->trans_wm.plane_en,
12061                                   sw_plane_wm->trans_wm.plane_res_b,
12062                                   sw_plane_wm->trans_wm.plane_res_l,
12063                                   hw_plane_wm->trans_wm.plane_en,
12064                                   hw_plane_wm->trans_wm.plane_res_b,
12065                                   hw_plane_wm->trans_wm.plane_res_l);
12066                 }
12067
12068                 /* DDB */
12069                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
12070                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
12071
12072                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12073                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12074                                   pipe_name(pipe), plane + 1,
12075                                   sw_ddb_entry->start, sw_ddb_entry->end,
12076                                   hw_ddb_entry->start, hw_ddb_entry->end);
12077                 }
12078         }
12079
12080         /*
12081          * cursor
12082          * If the cursor plane isn't active, we may not have updated it's ddb
12083          * allocation. In that case since the ddb allocation will be updated
12084          * once the plane becomes visible, we can skip this check
12085          */
12086         if (1) {
12087                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
12088                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12089
12090                 /* Watermarks */
12091                 for (level = 0; level <= max_level; level++) {
12092                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12093                                                 &sw_plane_wm->wm[level]))
12094                                 continue;
12095
12096                         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",
12097                                   pipe_name(pipe), level,
12098                                   sw_plane_wm->wm[level].plane_en,
12099                                   sw_plane_wm->wm[level].plane_res_b,
12100                                   sw_plane_wm->wm[level].plane_res_l,
12101                                   hw_plane_wm->wm[level].plane_en,
12102                                   hw_plane_wm->wm[level].plane_res_b,
12103                                   hw_plane_wm->wm[level].plane_res_l);
12104                 }
12105
12106                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12107                                          &sw_plane_wm->trans_wm)) {
12108                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12109                                   pipe_name(pipe),
12110                                   sw_plane_wm->trans_wm.plane_en,
12111                                   sw_plane_wm->trans_wm.plane_res_b,
12112                                   sw_plane_wm->trans_wm.plane_res_l,
12113                                   hw_plane_wm->trans_wm.plane_en,
12114                                   hw_plane_wm->trans_wm.plane_res_b,
12115                                   hw_plane_wm->trans_wm.plane_res_l);
12116                 }
12117
12118                 /* DDB */
12119                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12120                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12121
12122                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12123                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12124                                   pipe_name(pipe),
12125                                   sw_ddb_entry->start, sw_ddb_entry->end,
12126                                   hw_ddb_entry->start, hw_ddb_entry->end);
12127                 }
12128         }
12129 }
12130
12131 static void
12132 verify_connector_state(struct drm_device *dev,
12133                        struct drm_atomic_state *state,
12134                        struct drm_crtc *crtc)
12135 {
12136         struct drm_connector *connector;
12137         struct drm_connector_state *new_conn_state;
12138         int i;
12139
12140         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12141                 struct drm_encoder *encoder = connector->encoder;
12142                 struct drm_crtc_state *crtc_state = NULL;
12143
12144                 if (new_conn_state->crtc != crtc)
12145                         continue;
12146
12147                 if (crtc)
12148                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12149
12150                 intel_connector_verify_state(crtc_state, new_conn_state);
12151
12152                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12153                      "connector's atomic encoder doesn't match legacy encoder\n");
12154         }
12155 }
12156
12157 static void
12158 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12159 {
12160         struct intel_encoder *encoder;
12161         struct drm_connector *connector;
12162         struct drm_connector_state *old_conn_state, *new_conn_state;
12163         int i;
12164
12165         for_each_intel_encoder(dev, encoder) {
12166                 bool enabled = false, found = false;
12167                 enum pipe pipe;
12168
12169                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12170                               encoder->base.base.id,
12171                               encoder->base.name);
12172
12173                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12174                                                    new_conn_state, i) {
12175                         if (old_conn_state->best_encoder == &encoder->base)
12176                                 found = true;
12177
12178                         if (new_conn_state->best_encoder != &encoder->base)
12179                                 continue;
12180                         found = enabled = true;
12181
12182                         I915_STATE_WARN(new_conn_state->crtc !=
12183                                         encoder->base.crtc,
12184                              "connector's crtc doesn't match encoder crtc\n");
12185                 }
12186
12187                 if (!found)
12188                         continue;
12189
12190                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12191                      "encoder's enabled state mismatch "
12192                      "(expected %i, found %i)\n",
12193                      !!encoder->base.crtc, enabled);
12194
12195                 if (!encoder->base.crtc) {
12196                         bool active;
12197
12198                         active = encoder->get_hw_state(encoder, &pipe);
12199                         I915_STATE_WARN(active,
12200                              "encoder detached but still enabled on pipe %c.\n",
12201                              pipe_name(pipe));
12202                 }
12203         }
12204 }
12205
12206 static void
12207 verify_crtc_state(struct drm_crtc *crtc,
12208                   struct drm_crtc_state *old_crtc_state,
12209                   struct drm_crtc_state *new_crtc_state)
12210 {
12211         struct drm_device *dev = crtc->dev;
12212         struct drm_i915_private *dev_priv = to_i915(dev);
12213         struct intel_encoder *encoder;
12214         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12215         struct intel_crtc_state *pipe_config, *sw_config;
12216         struct drm_atomic_state *old_state;
12217         bool active;
12218
12219         old_state = old_crtc_state->state;
12220         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12221         pipe_config = to_intel_crtc_state(old_crtc_state);
12222         memset(pipe_config, 0, sizeof(*pipe_config));
12223         pipe_config->base.crtc = crtc;
12224         pipe_config->base.state = old_state;
12225
12226         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12227
12228         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12229
12230         /* hw state is inconsistent with the pipe quirk */
12231         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12232             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12233                 active = new_crtc_state->active;
12234
12235         I915_STATE_WARN(new_crtc_state->active != active,
12236              "crtc active state doesn't match with hw state "
12237              "(expected %i, found %i)\n", new_crtc_state->active, active);
12238
12239         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12240              "transitional active state does not match atomic hw state "
12241              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12242
12243         for_each_encoder_on_crtc(dev, crtc, encoder) {
12244                 enum pipe pipe;
12245
12246                 active = encoder->get_hw_state(encoder, &pipe);
12247                 I915_STATE_WARN(active != new_crtc_state->active,
12248                         "[ENCODER:%i] active %i with crtc active %i\n",
12249                         encoder->base.base.id, active, new_crtc_state->active);
12250
12251                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12252                                 "Encoder connected to wrong pipe %c\n",
12253                                 pipe_name(pipe));
12254
12255                 if (active) {
12256                         pipe_config->output_types |= 1 << encoder->type;
12257                         encoder->get_config(encoder, pipe_config);
12258                 }
12259         }
12260
12261         intel_crtc_compute_pixel_rate(pipe_config);
12262
12263         if (!new_crtc_state->active)
12264                 return;
12265
12266         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12267
12268         sw_config = to_intel_crtc_state(new_crtc_state);
12269         if (!intel_pipe_config_compare(dev_priv, sw_config,
12270                                        pipe_config, false)) {
12271                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12272                 intel_dump_pipe_config(intel_crtc, pipe_config,
12273                                        "[hw state]");
12274                 intel_dump_pipe_config(intel_crtc, sw_config,
12275                                        "[sw state]");
12276         }
12277 }
12278
12279 static void
12280 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12281                          struct intel_shared_dpll *pll,
12282                          struct drm_crtc *crtc,
12283                          struct drm_crtc_state *new_state)
12284 {
12285         struct intel_dpll_hw_state dpll_hw_state;
12286         unsigned crtc_mask;
12287         bool active;
12288
12289         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12290
12291         DRM_DEBUG_KMS("%s\n", pll->name);
12292
12293         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12294
12295         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12296                 I915_STATE_WARN(!pll->on && pll->active_mask,
12297                      "pll in active use but not on in sw tracking\n");
12298                 I915_STATE_WARN(pll->on && !pll->active_mask,
12299                      "pll is on but not used by any active crtc\n");
12300                 I915_STATE_WARN(pll->on != active,
12301                      "pll on state mismatch (expected %i, found %i)\n",
12302                      pll->on, active);
12303         }
12304
12305         if (!crtc) {
12306                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12307                                 "more active pll users than references: %x vs %x\n",
12308                                 pll->active_mask, pll->state.crtc_mask);
12309
12310                 return;
12311         }
12312
12313         crtc_mask = 1 << drm_crtc_index(crtc);
12314
12315         if (new_state->active)
12316                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12317                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12318                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12319         else
12320                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12321                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12322                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12323
12324         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12325                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12326                         crtc_mask, pll->state.crtc_mask);
12327
12328         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12329                                           &dpll_hw_state,
12330                                           sizeof(dpll_hw_state)),
12331                         "pll hw state mismatch\n");
12332 }
12333
12334 static void
12335 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12336                          struct drm_crtc_state *old_crtc_state,
12337                          struct drm_crtc_state *new_crtc_state)
12338 {
12339         struct drm_i915_private *dev_priv = to_i915(dev);
12340         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12341         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12342
12343         if (new_state->shared_dpll)
12344                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12345
12346         if (old_state->shared_dpll &&
12347             old_state->shared_dpll != new_state->shared_dpll) {
12348                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
12349                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12350
12351                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12352                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12353                                 pipe_name(drm_crtc_index(crtc)));
12354                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12355                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12356                                 pipe_name(drm_crtc_index(crtc)));
12357         }
12358 }
12359
12360 static void
12361 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12362                           struct drm_atomic_state *state,
12363                           struct drm_crtc_state *old_state,
12364                           struct drm_crtc_state *new_state)
12365 {
12366         if (!needs_modeset(new_state) &&
12367             !to_intel_crtc_state(new_state)->update_pipe)
12368                 return;
12369
12370         verify_wm_state(crtc, new_state);
12371         verify_connector_state(crtc->dev, state, crtc);
12372         verify_crtc_state(crtc, old_state, new_state);
12373         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12374 }
12375
12376 static void
12377 verify_disabled_dpll_state(struct drm_device *dev)
12378 {
12379         struct drm_i915_private *dev_priv = to_i915(dev);
12380         int i;
12381
12382         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12383                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12384 }
12385
12386 static void
12387 intel_modeset_verify_disabled(struct drm_device *dev,
12388                               struct drm_atomic_state *state)
12389 {
12390         verify_encoder_state(dev, state);
12391         verify_connector_state(dev, state, NULL);
12392         verify_disabled_dpll_state(dev);
12393 }
12394
12395 static void update_scanline_offset(struct intel_crtc *crtc)
12396 {
12397         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12398
12399         /*
12400          * The scanline counter increments at the leading edge of hsync.
12401          *
12402          * On most platforms it starts counting from vtotal-1 on the
12403          * first active line. That means the scanline counter value is
12404          * always one less than what we would expect. Ie. just after
12405          * start of vblank, which also occurs at start of hsync (on the
12406          * last active line), the scanline counter will read vblank_start-1.
12407          *
12408          * On gen2 the scanline counter starts counting from 1 instead
12409          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12410          * to keep the value positive), instead of adding one.
12411          *
12412          * On HSW+ the behaviour of the scanline counter depends on the output
12413          * type. For DP ports it behaves like most other platforms, but on HDMI
12414          * there's an extra 1 line difference. So we need to add two instead of
12415          * one to the value.
12416          *
12417          * On VLV/CHV DSI the scanline counter would appear to increment
12418          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12419          * that means we can't tell whether we're in vblank or not while
12420          * we're on that particular line. We must still set scanline_offset
12421          * to 1 so that the vblank timestamps come out correct when we query
12422          * the scanline counter from within the vblank interrupt handler.
12423          * However if queried just before the start of vblank we'll get an
12424          * answer that's slightly in the future.
12425          */
12426         if (IS_GEN2(dev_priv)) {
12427                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12428                 int vtotal;
12429
12430                 vtotal = adjusted_mode->crtc_vtotal;
12431                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12432                         vtotal /= 2;
12433
12434                 crtc->scanline_offset = vtotal - 1;
12435         } else if (HAS_DDI(dev_priv) &&
12436                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12437                 crtc->scanline_offset = 2;
12438         } else
12439                 crtc->scanline_offset = 1;
12440 }
12441
12442 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12443 {
12444         struct drm_device *dev = state->dev;
12445         struct drm_i915_private *dev_priv = to_i915(dev);
12446         struct drm_crtc *crtc;
12447         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12448         int i;
12449
12450         if (!dev_priv->display.crtc_compute_clock)
12451                 return;
12452
12453         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12454                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12455                 struct intel_shared_dpll *old_dpll =
12456                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12457
12458                 if (!needs_modeset(new_crtc_state))
12459                         continue;
12460
12461                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12462
12463                 if (!old_dpll)
12464                         continue;
12465
12466                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12467         }
12468 }
12469
12470 /*
12471  * This implements the workaround described in the "notes" section of the mode
12472  * set sequence documentation. When going from no pipes or single pipe to
12473  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12474  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12475  */
12476 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12477 {
12478         struct drm_crtc_state *crtc_state;
12479         struct intel_crtc *intel_crtc;
12480         struct drm_crtc *crtc;
12481         struct intel_crtc_state *first_crtc_state = NULL;
12482         struct intel_crtc_state *other_crtc_state = NULL;
12483         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12484         int i;
12485
12486         /* look at all crtc's that are going to be enabled in during modeset */
12487         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12488                 intel_crtc = to_intel_crtc(crtc);
12489
12490                 if (!crtc_state->active || !needs_modeset(crtc_state))
12491                         continue;
12492
12493                 if (first_crtc_state) {
12494                         other_crtc_state = to_intel_crtc_state(crtc_state);
12495                         break;
12496                 } else {
12497                         first_crtc_state = to_intel_crtc_state(crtc_state);
12498                         first_pipe = intel_crtc->pipe;
12499                 }
12500         }
12501
12502         /* No workaround needed? */
12503         if (!first_crtc_state)
12504                 return 0;
12505
12506         /* w/a possibly needed, check how many crtc's are already enabled. */
12507         for_each_intel_crtc(state->dev, intel_crtc) {
12508                 struct intel_crtc_state *pipe_config;
12509
12510                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12511                 if (IS_ERR(pipe_config))
12512                         return PTR_ERR(pipe_config);
12513
12514                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12515
12516                 if (!pipe_config->base.active ||
12517                     needs_modeset(&pipe_config->base))
12518                         continue;
12519
12520                 /* 2 or more enabled crtcs means no need for w/a */
12521                 if (enabled_pipe != INVALID_PIPE)
12522                         return 0;
12523
12524                 enabled_pipe = intel_crtc->pipe;
12525         }
12526
12527         if (enabled_pipe != INVALID_PIPE)
12528                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12529         else if (other_crtc_state)
12530                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12531
12532         return 0;
12533 }
12534
12535 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12536 {
12537         struct drm_crtc *crtc;
12538
12539         /* Add all pipes to the state */
12540         for_each_crtc(state->dev, crtc) {
12541                 struct drm_crtc_state *crtc_state;
12542
12543                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12544                 if (IS_ERR(crtc_state))
12545                         return PTR_ERR(crtc_state);
12546         }
12547
12548         return 0;
12549 }
12550
12551 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12552 {
12553         struct drm_crtc *crtc;
12554
12555         /*
12556          * Add all pipes to the state, and force
12557          * a modeset on all the active ones.
12558          */
12559         for_each_crtc(state->dev, crtc) {
12560                 struct drm_crtc_state *crtc_state;
12561                 int ret;
12562
12563                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12564                 if (IS_ERR(crtc_state))
12565                         return PTR_ERR(crtc_state);
12566
12567                 if (!crtc_state->active || needs_modeset(crtc_state))
12568                         continue;
12569
12570                 crtc_state->mode_changed = true;
12571
12572                 ret = drm_atomic_add_affected_connectors(state, crtc);
12573                 if (ret)
12574                         return ret;
12575
12576                 ret = drm_atomic_add_affected_planes(state, crtc);
12577                 if (ret)
12578                         return ret;
12579         }
12580
12581         return 0;
12582 }
12583
12584 static int intel_modeset_checks(struct drm_atomic_state *state)
12585 {
12586         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12587         struct drm_i915_private *dev_priv = to_i915(state->dev);
12588         struct drm_crtc *crtc;
12589         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12590         int ret = 0, i;
12591
12592         if (!check_digital_port_conflicts(state)) {
12593                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12594                 return -EINVAL;
12595         }
12596
12597         intel_state->modeset = true;
12598         intel_state->active_crtcs = dev_priv->active_crtcs;
12599         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12600         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12601
12602         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12603                 if (new_crtc_state->active)
12604                         intel_state->active_crtcs |= 1 << i;
12605                 else
12606                         intel_state->active_crtcs &= ~(1 << i);
12607
12608                 if (old_crtc_state->active != new_crtc_state->active)
12609                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12610         }
12611
12612         /*
12613          * See if the config requires any additional preparation, e.g.
12614          * to adjust global state with pipes off.  We need to do this
12615          * here so we can get the modeset_pipe updated config for the new
12616          * mode set on this crtc.  For other crtcs we need to use the
12617          * adjusted_mode bits in the crtc directly.
12618          */
12619         if (dev_priv->display.modeset_calc_cdclk) {
12620                 ret = dev_priv->display.modeset_calc_cdclk(state);
12621                 if (ret < 0)
12622                         return ret;
12623
12624                 /*
12625                  * Writes to dev_priv->cdclk.logical must protected by
12626                  * holding all the crtc locks, even if we don't end up
12627                  * touching the hardware
12628                  */
12629                 if (!intel_cdclk_state_compare(&dev_priv->cdclk.logical,
12630                                                &intel_state->cdclk.logical)) {
12631                         ret = intel_lock_all_pipes(state);
12632                         if (ret < 0)
12633                                 return ret;
12634                 }
12635
12636                 /* All pipes must be switched off while we change the cdclk. */
12637                 if (!intel_cdclk_state_compare(&dev_priv->cdclk.actual,
12638                                                &intel_state->cdclk.actual)) {
12639                         ret = intel_modeset_all_pipes(state);
12640                         if (ret < 0)
12641                                 return ret;
12642                 }
12643
12644                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12645                               intel_state->cdclk.logical.cdclk,
12646                               intel_state->cdclk.actual.cdclk);
12647         } else {
12648                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12649         }
12650
12651         intel_modeset_clear_plls(state);
12652
12653         if (IS_HASWELL(dev_priv))
12654                 return haswell_mode_set_planes_workaround(state);
12655
12656         return 0;
12657 }
12658
12659 /*
12660  * Handle calculation of various watermark data at the end of the atomic check
12661  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12662  * handlers to ensure that all derived state has been updated.
12663  */
12664 static int calc_watermark_data(struct drm_atomic_state *state)
12665 {
12666         struct drm_device *dev = state->dev;
12667         struct drm_i915_private *dev_priv = to_i915(dev);
12668
12669         /* Is there platform-specific watermark information to calculate? */
12670         if (dev_priv->display.compute_global_watermarks)
12671                 return dev_priv->display.compute_global_watermarks(state);
12672
12673         return 0;
12674 }
12675
12676 /**
12677  * intel_atomic_check - validate state object
12678  * @dev: drm device
12679  * @state: state to validate
12680  */
12681 static int intel_atomic_check(struct drm_device *dev,
12682                               struct drm_atomic_state *state)
12683 {
12684         struct drm_i915_private *dev_priv = to_i915(dev);
12685         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12686         struct drm_crtc *crtc;
12687         struct drm_crtc_state *old_crtc_state, *crtc_state;
12688         int ret, i;
12689         bool any_ms = false;
12690
12691         ret = drm_atomic_helper_check_modeset(dev, state);
12692         if (ret)
12693                 return ret;
12694
12695         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12696                 struct intel_crtc_state *pipe_config =
12697                         to_intel_crtc_state(crtc_state);
12698
12699                 /* Catch I915_MODE_FLAG_INHERITED */
12700                 if (crtc_state->mode.private_flags != old_crtc_state->mode.private_flags)
12701                         crtc_state->mode_changed = true;
12702
12703                 if (!needs_modeset(crtc_state))
12704                         continue;
12705
12706                 if (!crtc_state->enable) {
12707                         any_ms = true;
12708                         continue;
12709                 }
12710
12711                 /* FIXME: For only active_changed we shouldn't need to do any
12712                  * state recomputation at all. */
12713
12714                 ret = drm_atomic_add_affected_connectors(state, crtc);
12715                 if (ret)
12716                         return ret;
12717
12718                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12719                 if (ret) {
12720                         intel_dump_pipe_config(to_intel_crtc(crtc),
12721                                                pipe_config, "[failed]");
12722                         return ret;
12723                 }
12724
12725                 if (i915.fastboot &&
12726                     intel_pipe_config_compare(dev_priv,
12727                                         to_intel_crtc_state(old_crtc_state),
12728                                         pipe_config, true)) {
12729                         crtc_state->mode_changed = false;
12730                         pipe_config->update_pipe = true;
12731                 }
12732
12733                 if (needs_modeset(crtc_state))
12734                         any_ms = true;
12735
12736                 ret = drm_atomic_add_affected_planes(state, crtc);
12737                 if (ret)
12738                         return ret;
12739
12740                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12741                                        needs_modeset(crtc_state) ?
12742                                        "[modeset]" : "[fastset]");
12743         }
12744
12745         if (any_ms) {
12746                 ret = intel_modeset_checks(state);
12747
12748                 if (ret)
12749                         return ret;
12750         } else {
12751                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12752         }
12753
12754         ret = drm_atomic_helper_check_planes(dev, state);
12755         if (ret)
12756                 return ret;
12757
12758         intel_fbc_choose_crtc(dev_priv, state);
12759         return calc_watermark_data(state);
12760 }
12761
12762 static int intel_atomic_prepare_commit(struct drm_device *dev,
12763                                        struct drm_atomic_state *state)
12764 {
12765         struct drm_i915_private *dev_priv = to_i915(dev);
12766         struct drm_crtc_state *crtc_state;
12767         struct drm_crtc *crtc;
12768         int i, ret;
12769
12770         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12771                 if (state->legacy_cursor_update)
12772                         continue;
12773
12774                 ret = intel_crtc_wait_for_pending_flips(crtc);
12775                 if (ret)
12776                         return ret;
12777
12778                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
12779                         flush_workqueue(dev_priv->wq);
12780         }
12781
12782         ret = mutex_lock_interruptible(&dev->struct_mutex);
12783         if (ret)
12784                 return ret;
12785
12786         ret = drm_atomic_helper_prepare_planes(dev, state);
12787         mutex_unlock(&dev->struct_mutex);
12788
12789         return ret;
12790 }
12791
12792 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12793 {
12794         struct drm_device *dev = crtc->base.dev;
12795
12796         if (!dev->max_vblank_count)
12797                 return drm_accurate_vblank_count(&crtc->base);
12798
12799         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12800 }
12801
12802 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
12803                                           struct drm_i915_private *dev_priv,
12804                                           unsigned crtc_mask)
12805 {
12806         unsigned last_vblank_count[I915_MAX_PIPES];
12807         enum pipe pipe;
12808         int ret;
12809
12810         if (!crtc_mask)
12811                 return;
12812
12813         for_each_pipe(dev_priv, pipe) {
12814                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
12815                                                                   pipe);
12816
12817                 if (!((1 << pipe) & crtc_mask))
12818                         continue;
12819
12820                 ret = drm_crtc_vblank_get(&crtc->base);
12821                 if (WARN_ON(ret != 0)) {
12822                         crtc_mask &= ~(1 << pipe);
12823                         continue;
12824                 }
12825
12826                 last_vblank_count[pipe] = drm_crtc_vblank_count(&crtc->base);
12827         }
12828
12829         for_each_pipe(dev_priv, pipe) {
12830                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
12831                                                                   pipe);
12832                 long lret;
12833
12834                 if (!((1 << pipe) & crtc_mask))
12835                         continue;
12836
12837                 lret = wait_event_timeout(dev->vblank[pipe].queue,
12838                                 last_vblank_count[pipe] !=
12839                                         drm_crtc_vblank_count(&crtc->base),
12840                                 msecs_to_jiffies(50));
12841
12842                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
12843
12844                 drm_crtc_vblank_put(&crtc->base);
12845         }
12846 }
12847
12848 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
12849 {
12850         /* fb updated, need to unpin old fb */
12851         if (crtc_state->fb_changed)
12852                 return true;
12853
12854         /* wm changes, need vblank before final wm's */
12855         if (crtc_state->update_wm_post)
12856                 return true;
12857
12858         if (crtc_state->wm.need_postvbl_update)
12859                 return true;
12860
12861         return false;
12862 }
12863
12864 static void intel_update_crtc(struct drm_crtc *crtc,
12865                               struct drm_atomic_state *state,
12866                               struct drm_crtc_state *old_crtc_state,
12867                               struct drm_crtc_state *new_crtc_state,
12868                               unsigned int *crtc_vblank_mask)
12869 {
12870         struct drm_device *dev = crtc->dev;
12871         struct drm_i915_private *dev_priv = to_i915(dev);
12872         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12873         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12874         bool modeset = needs_modeset(new_crtc_state);
12875
12876         if (modeset) {
12877                 update_scanline_offset(intel_crtc);
12878                 dev_priv->display.crtc_enable(pipe_config, state);
12879         } else {
12880                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12881                                        pipe_config);
12882         }
12883
12884         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12885                 intel_fbc_enable(
12886                     intel_crtc, pipe_config,
12887                     to_intel_plane_state(crtc->primary->state));
12888         }
12889
12890         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12891
12892         if (needs_vblank_wait(pipe_config))
12893                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
12894 }
12895
12896 static void intel_update_crtcs(struct drm_atomic_state *state,
12897                                unsigned int *crtc_vblank_mask)
12898 {
12899         struct drm_crtc *crtc;
12900         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12901         int i;
12902
12903         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12904                 if (!new_crtc_state->active)
12905                         continue;
12906
12907                 intel_update_crtc(crtc, state, old_crtc_state,
12908                                   new_crtc_state, crtc_vblank_mask);
12909         }
12910 }
12911
12912 static void skl_update_crtcs(struct drm_atomic_state *state,
12913                              unsigned int *crtc_vblank_mask)
12914 {
12915         struct drm_i915_private *dev_priv = to_i915(state->dev);
12916         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12917         struct drm_crtc *crtc;
12918         struct intel_crtc *intel_crtc;
12919         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12920         struct intel_crtc_state *cstate;
12921         unsigned int updated = 0;
12922         bool progress;
12923         enum pipe pipe;
12924         int i;
12925
12926         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12927
12928         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12929                 /* ignore allocations for crtc's that have been turned off. */
12930                 if (new_crtc_state->active)
12931                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12932
12933         /*
12934          * Whenever the number of active pipes changes, we need to make sure we
12935          * update the pipes in the right order so that their ddb allocations
12936          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12937          * cause pipe underruns and other bad stuff.
12938          */
12939         do {
12940                 progress = false;
12941
12942                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12943                         bool vbl_wait = false;
12944                         unsigned int cmask = drm_crtc_mask(crtc);
12945
12946                         intel_crtc = to_intel_crtc(crtc);
12947                         cstate = to_intel_crtc_state(crtc->state);
12948                         pipe = intel_crtc->pipe;
12949
12950                         if (updated & cmask || !cstate->base.active)
12951                                 continue;
12952
12953                         if (skl_ddb_allocation_overlaps(entries, &cstate->wm.skl.ddb, i))
12954                                 continue;
12955
12956                         updated |= cmask;
12957                         entries[i] = &cstate->wm.skl.ddb;
12958
12959                         /*
12960                          * If this is an already active pipe, it's DDB changed,
12961                          * and this isn't the last pipe that needs updating
12962                          * then we need to wait for a vblank to pass for the
12963                          * new ddb allocation to take effect.
12964                          */
12965                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12966                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12967                             !new_crtc_state->active_changed &&
12968                             intel_state->wm_results.dirty_pipes != updated)
12969                                 vbl_wait = true;
12970
12971                         intel_update_crtc(crtc, state, old_crtc_state,
12972                                           new_crtc_state, crtc_vblank_mask);
12973
12974                         if (vbl_wait)
12975                                 intel_wait_for_vblank(dev_priv, pipe);
12976
12977                         progress = true;
12978                 }
12979         } while (progress);
12980 }
12981
12982 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12983 {
12984         struct intel_atomic_state *state, *next;
12985         struct llist_node *freed;
12986
12987         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12988         llist_for_each_entry_safe(state, next, freed, freed)
12989                 drm_atomic_state_put(&state->base);
12990 }
12991
12992 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12993 {
12994         struct drm_i915_private *dev_priv =
12995                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12996
12997         intel_atomic_helper_free_state(dev_priv);
12998 }
12999
13000 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13001 {
13002         struct drm_device *dev = state->dev;
13003         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13004         struct drm_i915_private *dev_priv = to_i915(dev);
13005         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13006         struct drm_crtc *crtc;
13007         struct intel_crtc_state *intel_cstate;
13008         bool hw_check = intel_state->modeset;
13009         u64 put_domains[I915_MAX_PIPES] = {};
13010         unsigned crtc_vblank_mask = 0;
13011         int i;
13012
13013         drm_atomic_helper_wait_for_dependencies(state);
13014
13015         if (intel_state->modeset)
13016                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13017
13018         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13019                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13020
13021                 if (needs_modeset(new_crtc_state) ||
13022                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13023                         hw_check = true;
13024
13025                         put_domains[to_intel_crtc(crtc)->pipe] =
13026                                 modeset_get_crtc_power_domains(crtc,
13027                                         to_intel_crtc_state(new_crtc_state));
13028                 }
13029
13030                 if (!needs_modeset(new_crtc_state))
13031                         continue;
13032
13033                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
13034                                        to_intel_crtc_state(new_crtc_state));
13035
13036                 if (old_crtc_state->active) {
13037                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13038                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
13039                         intel_crtc->active = false;
13040                         intel_fbc_disable(intel_crtc);
13041                         intel_disable_shared_dpll(intel_crtc);
13042
13043                         /*
13044                          * Underruns don't always raise
13045                          * interrupts, so check manually.
13046                          */
13047                         intel_check_cpu_fifo_underruns(dev_priv);
13048                         intel_check_pch_fifo_underruns(dev_priv);
13049
13050                         if (!crtc->state->active) {
13051                                 /*
13052                                  * Make sure we don't call initial_watermarks
13053                                  * for ILK-style watermark updates.
13054                                  *
13055                                  * No clue what this is supposed to achieve.
13056                                  */
13057                                 if (INTEL_GEN(dev_priv) >= 9)
13058                                         dev_priv->display.initial_watermarks(intel_state,
13059                                                                              to_intel_crtc_state(crtc->state));
13060                         }
13061                 }
13062         }
13063
13064         /* Only after disabling all output pipelines that will be changed can we
13065          * update the the output configuration. */
13066         intel_modeset_update_crtc_state(state);
13067
13068         if (intel_state->modeset) {
13069                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13070
13071                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
13072
13073                 /*
13074                  * SKL workaround: bspec recommends we disable the SAGV when we
13075                  * have more then one pipe enabled
13076                  */
13077                 if (!intel_can_enable_sagv(state))
13078                         intel_disable_sagv(dev_priv);
13079
13080                 intel_modeset_verify_disabled(dev, state);
13081         }
13082
13083         /* Complete the events for pipes that have now been disabled */
13084         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13085                 bool modeset = needs_modeset(new_crtc_state);
13086
13087                 /* Complete events for now disable pipes here. */
13088                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13089                         spin_lock_irq(&dev->event_lock);
13090                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13091                         spin_unlock_irq(&dev->event_lock);
13092
13093                         new_crtc_state->event = NULL;
13094                 }
13095         }
13096
13097         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13098         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
13099
13100         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13101          * already, but still need the state for the delayed optimization. To
13102          * fix this:
13103          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13104          * - schedule that vblank worker _before_ calling hw_done
13105          * - at the start of commit_tail, cancel it _synchrously
13106          * - switch over to the vblank wait helper in the core after that since
13107          *   we don't need out special handling any more.
13108          */
13109         if (!state->legacy_cursor_update)
13110                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13111
13112         /*
13113          * Now that the vblank has passed, we can go ahead and program the
13114          * optimal watermarks on platforms that need two-step watermark
13115          * programming.
13116          *
13117          * TODO: Move this (and other cleanup) to an async worker eventually.
13118          */
13119         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13120                 intel_cstate = to_intel_crtc_state(new_crtc_state);
13121
13122                 if (dev_priv->display.optimize_watermarks)
13123                         dev_priv->display.optimize_watermarks(intel_state,
13124                                                               intel_cstate);
13125         }
13126
13127         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13128                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13129
13130                 if (put_domains[i])
13131                         modeset_put_power_domains(dev_priv, put_domains[i]);
13132
13133                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13134         }
13135
13136         if (intel_state->modeset && intel_can_enable_sagv(state))
13137                 intel_enable_sagv(dev_priv);
13138
13139         drm_atomic_helper_commit_hw_done(state);
13140
13141         if (intel_state->modeset) {
13142                 /* As one of the primary mmio accessors, KMS has a high
13143                  * likelihood of triggering bugs in unclaimed access. After we
13144                  * finish modesetting, see if an error has been flagged, and if
13145                  * so enable debugging for the next modeset - and hope we catch
13146                  * the culprit.
13147                  */
13148                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13149                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13150         }
13151
13152         mutex_lock(&dev->struct_mutex);
13153         drm_atomic_helper_cleanup_planes(dev, state);
13154         mutex_unlock(&dev->struct_mutex);
13155
13156         drm_atomic_helper_commit_cleanup_done(state);
13157
13158         drm_atomic_state_put(state);
13159
13160         intel_atomic_helper_free_state(dev_priv);
13161 }
13162
13163 static void intel_atomic_commit_work(struct work_struct *work)
13164 {
13165         struct drm_atomic_state *state =
13166                 container_of(work, struct drm_atomic_state, commit_work);
13167
13168         intel_atomic_commit_tail(state);
13169 }
13170
13171 static int __i915_sw_fence_call
13172 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13173                           enum i915_sw_fence_notify notify)
13174 {
13175         struct intel_atomic_state *state =
13176                 container_of(fence, struct intel_atomic_state, commit_ready);
13177
13178         switch (notify) {
13179         case FENCE_COMPLETE:
13180                 if (state->base.commit_work.func)
13181                         queue_work(system_unbound_wq, &state->base.commit_work);
13182                 break;
13183
13184         case FENCE_FREE:
13185                 {
13186                         struct intel_atomic_helper *helper =
13187                                 &to_i915(state->base.dev)->atomic_helper;
13188
13189                         if (llist_add(&state->freed, &helper->free_list))
13190                                 schedule_work(&helper->free_work);
13191                         break;
13192                 }
13193         }
13194
13195         return NOTIFY_DONE;
13196 }
13197
13198 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13199 {
13200         struct drm_plane_state *old_plane_state, *new_plane_state;
13201         struct drm_plane *plane;
13202         int i;
13203
13204         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13205                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13206                                   intel_fb_obj(new_plane_state->fb),
13207                                   to_intel_plane(plane)->frontbuffer_bit);
13208 }
13209
13210 /**
13211  * intel_atomic_commit - commit validated state object
13212  * @dev: DRM device
13213  * @state: the top-level driver state object
13214  * @nonblock: nonblocking commit
13215  *
13216  * This function commits a top-level state object that has been validated
13217  * with drm_atomic_helper_check().
13218  *
13219  * RETURNS
13220  * Zero for success or -errno.
13221  */
13222 static int intel_atomic_commit(struct drm_device *dev,
13223                                struct drm_atomic_state *state,
13224                                bool nonblock)
13225 {
13226         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13227         struct drm_i915_private *dev_priv = to_i915(dev);
13228         int ret = 0;
13229
13230         ret = drm_atomic_helper_setup_commit(state, nonblock);
13231         if (ret)
13232                 return ret;
13233
13234         drm_atomic_state_get(state);
13235         i915_sw_fence_init(&intel_state->commit_ready,
13236                            intel_atomic_commit_ready);
13237
13238         ret = intel_atomic_prepare_commit(dev, state);
13239         if (ret) {
13240                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13241                 i915_sw_fence_commit(&intel_state->commit_ready);
13242                 return ret;
13243         }
13244
13245         /*
13246          * The intel_legacy_cursor_update() fast path takes care
13247          * of avoiding the vblank waits for simple cursor
13248          * movement and flips. For cursor on/off and size changes,
13249          * we want to perform the vblank waits so that watermark
13250          * updates happen during the correct frames. Gen9+ have
13251          * double buffered watermarks and so shouldn't need this.
13252          *
13253          * Do this after drm_atomic_helper_setup_commit() and
13254          * intel_atomic_prepare_commit() because we still want
13255          * to skip the flip and fb cleanup waits. Although that
13256          * does risk yanking the mapping from under the display
13257          * engine.
13258          *
13259          * FIXME doing watermarks and fb cleanup from a vblank worker
13260          * (assuming we had any) would solve these problems.
13261          */
13262         if (INTEL_GEN(dev_priv) < 9)
13263                 state->legacy_cursor_update = false;
13264
13265         drm_atomic_helper_swap_state(state, true);
13266         dev_priv->wm.distrust_bios_wm = false;
13267         intel_shared_dpll_swap_state(state);
13268         intel_atomic_track_fbs(state);
13269
13270         if (intel_state->modeset) {
13271                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13272                        sizeof(intel_state->min_pixclk));
13273                 dev_priv->active_crtcs = intel_state->active_crtcs;
13274                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
13275                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
13276         }
13277
13278         drm_atomic_state_get(state);
13279         INIT_WORK(&state->commit_work,
13280                   nonblock ? intel_atomic_commit_work : NULL);
13281
13282         i915_sw_fence_commit(&intel_state->commit_ready);
13283         if (!nonblock) {
13284                 i915_sw_fence_wait(&intel_state->commit_ready);
13285                 intel_atomic_commit_tail(state);
13286         }
13287
13288         return 0;
13289 }
13290
13291 static const struct drm_crtc_funcs intel_crtc_funcs = {
13292         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13293         .set_config = drm_atomic_helper_set_config,
13294         .set_property = drm_atomic_helper_crtc_set_property,
13295         .destroy = intel_crtc_destroy,
13296         .page_flip = drm_atomic_helper_page_flip,
13297         .atomic_duplicate_state = intel_crtc_duplicate_state,
13298         .atomic_destroy_state = intel_crtc_destroy_state,
13299         .set_crc_source = intel_crtc_set_crc_source,
13300 };
13301
13302 /**
13303  * intel_prepare_plane_fb - Prepare fb for usage on plane
13304  * @plane: drm plane to prepare for
13305  * @fb: framebuffer to prepare for presentation
13306  *
13307  * Prepares a framebuffer for usage on a display plane.  Generally this
13308  * involves pinning the underlying object and updating the frontbuffer tracking
13309  * bits.  Some older platforms need special physical address handling for
13310  * cursor planes.
13311  *
13312  * Must be called with struct_mutex held.
13313  *
13314  * Returns 0 on success, negative error code on failure.
13315  */
13316 int
13317 intel_prepare_plane_fb(struct drm_plane *plane,
13318                        struct drm_plane_state *new_state)
13319 {
13320         struct intel_atomic_state *intel_state =
13321                 to_intel_atomic_state(new_state->state);
13322         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13323         struct drm_framebuffer *fb = new_state->fb;
13324         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13325         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13326         int ret;
13327
13328         if (obj) {
13329                 if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13330                     INTEL_INFO(dev_priv)->cursor_needs_physical) {
13331                         const int align = intel_cursor_alignment(dev_priv);
13332
13333                         ret = i915_gem_object_attach_phys(obj, align);
13334                         if (ret) {
13335                                 DRM_DEBUG_KMS("failed to attach phys object\n");
13336                                 return ret;
13337                         }
13338                 } else {
13339                         struct i915_vma *vma;
13340
13341                         vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13342                         if (IS_ERR(vma)) {
13343                                 DRM_DEBUG_KMS("failed to pin object\n");
13344                                 return PTR_ERR(vma);
13345                         }
13346
13347                         to_intel_plane_state(new_state)->vma = vma;
13348                 }
13349         }
13350
13351         if (!obj && !old_obj)
13352                 return 0;
13353
13354         if (old_obj) {
13355                 struct drm_crtc_state *crtc_state =
13356                         drm_atomic_get_existing_crtc_state(new_state->state,
13357                                                            plane->state->crtc);
13358
13359                 /* Big Hammer, we also need to ensure that any pending
13360                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13361                  * current scanout is retired before unpinning the old
13362                  * framebuffer. Note that we rely on userspace rendering
13363                  * into the buffer attached to the pipe they are waiting
13364                  * on. If not, userspace generates a GPU hang with IPEHR
13365                  * point to the MI_WAIT_FOR_EVENT.
13366                  *
13367                  * This should only fail upon a hung GPU, in which case we
13368                  * can safely continue.
13369                  */
13370                 if (needs_modeset(crtc_state)) {
13371                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13372                                                               old_obj->resv, NULL,
13373                                                               false, 0,
13374                                                               GFP_KERNEL);
13375                         if (ret < 0)
13376                                 return ret;
13377                 }
13378         }
13379
13380         if (new_state->fence) { /* explicit fencing */
13381                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13382                                                     new_state->fence,
13383                                                     I915_FENCE_TIMEOUT,
13384                                                     GFP_KERNEL);
13385                 if (ret < 0)
13386                         return ret;
13387         }
13388
13389         if (!obj)
13390                 return 0;
13391
13392         if (!new_state->fence) { /* implicit fencing */
13393                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13394                                                       obj->resv, NULL,
13395                                                       false, I915_FENCE_TIMEOUT,
13396                                                       GFP_KERNEL);
13397                 if (ret < 0)
13398                         return ret;
13399
13400                 i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
13401         }
13402
13403         return 0;
13404 }
13405
13406 /**
13407  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13408  * @plane: drm plane to clean up for
13409  * @fb: old framebuffer that was on plane
13410  *
13411  * Cleans up a framebuffer that has just been removed from a plane.
13412  *
13413  * Must be called with struct_mutex held.
13414  */
13415 void
13416 intel_cleanup_plane_fb(struct drm_plane *plane,
13417                        struct drm_plane_state *old_state)
13418 {
13419         struct i915_vma *vma;
13420
13421         /* Should only be called after a successful intel_prepare_plane_fb()! */
13422         vma = fetch_and_zero(&to_intel_plane_state(old_state)->vma);
13423         if (vma)
13424                 intel_unpin_fb_vma(vma);
13425 }
13426
13427 int
13428 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13429 {
13430         struct drm_i915_private *dev_priv;
13431         int max_scale;
13432         int crtc_clock, max_dotclk;
13433
13434         if (!intel_crtc || !crtc_state->base.enable)
13435                 return DRM_PLANE_HELPER_NO_SCALING;
13436
13437         dev_priv = to_i915(intel_crtc->base.dev);
13438
13439         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13440         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13441
13442         if (IS_GEMINILAKE(dev_priv))
13443                 max_dotclk *= 2;
13444
13445         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13446                 return DRM_PLANE_HELPER_NO_SCALING;
13447
13448         /*
13449          * skl max scale is lower of:
13450          *    close to 3 but not 3, -1 is for that purpose
13451          *            or
13452          *    cdclk/crtc_clock
13453          */
13454         max_scale = min((1 << 16) * 3 - 1,
13455                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
13456
13457         return max_scale;
13458 }
13459
13460 static int
13461 intel_check_primary_plane(struct intel_plane *plane,
13462                           struct intel_crtc_state *crtc_state,
13463                           struct intel_plane_state *state)
13464 {
13465         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13466         struct drm_crtc *crtc = state->base.crtc;
13467         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13468         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13469         bool can_position = false;
13470         int ret;
13471
13472         if (INTEL_GEN(dev_priv) >= 9) {
13473                 /* use scaler when colorkey is not required */
13474                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13475                         min_scale = 1;
13476                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13477                 }
13478                 can_position = true;
13479         }
13480
13481         ret = drm_plane_helper_check_state(&state->base,
13482                                            &state->clip,
13483                                            min_scale, max_scale,
13484                                            can_position, true);
13485         if (ret)
13486                 return ret;
13487
13488         if (!state->base.fb)
13489                 return 0;
13490
13491         if (INTEL_GEN(dev_priv) >= 9) {
13492                 ret = skl_check_plane_surface(state);
13493                 if (ret)
13494                         return ret;
13495
13496                 state->ctl = skl_plane_ctl(crtc_state, state);
13497         } else {
13498                 ret = i9xx_check_plane_surface(state);
13499                 if (ret)
13500                         return ret;
13501
13502                 state->ctl = i9xx_plane_ctl(crtc_state, state);
13503         }
13504
13505         return 0;
13506 }
13507
13508 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13509                                     struct drm_crtc_state *old_crtc_state)
13510 {
13511         struct drm_device *dev = crtc->dev;
13512         struct drm_i915_private *dev_priv = to_i915(dev);
13513         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13514         struct intel_crtc_state *intel_cstate =
13515                 to_intel_crtc_state(crtc->state);
13516         struct intel_crtc_state *old_intel_cstate =
13517                 to_intel_crtc_state(old_crtc_state);
13518         struct intel_atomic_state *old_intel_state =
13519                 to_intel_atomic_state(old_crtc_state->state);
13520         bool modeset = needs_modeset(crtc->state);
13521
13522         if (!modeset &&
13523             (intel_cstate->base.color_mgmt_changed ||
13524              intel_cstate->update_pipe)) {
13525                 intel_color_set_csc(crtc->state);
13526                 intel_color_load_luts(crtc->state);
13527         }
13528
13529         /* Perform vblank evasion around commit operation */
13530         intel_pipe_update_start(intel_crtc);
13531
13532         if (modeset)
13533                 goto out;
13534
13535         if (intel_cstate->update_pipe)
13536                 intel_update_pipe_config(intel_crtc, old_intel_cstate);
13537         else if (INTEL_GEN(dev_priv) >= 9)
13538                 skl_detach_scalers(intel_crtc);
13539
13540 out:
13541         if (dev_priv->display.atomic_update_watermarks)
13542                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13543                                                            intel_cstate);
13544 }
13545
13546 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13547                                      struct drm_crtc_state *old_crtc_state)
13548 {
13549         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13550
13551         intel_pipe_update_end(intel_crtc, NULL);
13552 }
13553
13554 /**
13555  * intel_plane_destroy - destroy a plane
13556  * @plane: plane to destroy
13557  *
13558  * Common destruction function for all types of planes (primary, cursor,
13559  * sprite).
13560  */
13561 void intel_plane_destroy(struct drm_plane *plane)
13562 {
13563         drm_plane_cleanup(plane);
13564         kfree(to_intel_plane(plane));
13565 }
13566
13567 const struct drm_plane_funcs intel_plane_funcs = {
13568         .update_plane = drm_atomic_helper_update_plane,
13569         .disable_plane = drm_atomic_helper_disable_plane,
13570         .destroy = intel_plane_destroy,
13571         .set_property = drm_atomic_helper_plane_set_property,
13572         .atomic_get_property = intel_plane_atomic_get_property,
13573         .atomic_set_property = intel_plane_atomic_set_property,
13574         .atomic_duplicate_state = intel_plane_duplicate_state,
13575         .atomic_destroy_state = intel_plane_destroy_state,
13576 };
13577
13578 static int
13579 intel_legacy_cursor_update(struct drm_plane *plane,
13580                            struct drm_crtc *crtc,
13581                            struct drm_framebuffer *fb,
13582                            int crtc_x, int crtc_y,
13583                            unsigned int crtc_w, unsigned int crtc_h,
13584                            uint32_t src_x, uint32_t src_y,
13585                            uint32_t src_w, uint32_t src_h,
13586                            struct drm_modeset_acquire_ctx *ctx)
13587 {
13588         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13589         int ret;
13590         struct drm_plane_state *old_plane_state, *new_plane_state;
13591         struct intel_plane *intel_plane = to_intel_plane(plane);
13592         struct drm_framebuffer *old_fb;
13593         struct drm_crtc_state *crtc_state = crtc->state;
13594         struct i915_vma *old_vma;
13595
13596         /*
13597          * When crtc is inactive or there is a modeset pending,
13598          * wait for it to complete in the slowpath
13599          */
13600         if (!crtc_state->active || needs_modeset(crtc_state) ||
13601             to_intel_crtc_state(crtc_state)->update_pipe)
13602                 goto slow;
13603
13604         old_plane_state = plane->state;
13605
13606         /*
13607          * If any parameters change that may affect watermarks,
13608          * take the slowpath. Only changing fb or position should be
13609          * in the fastpath.
13610          */
13611         if (old_plane_state->crtc != crtc ||
13612             old_plane_state->src_w != src_w ||
13613             old_plane_state->src_h != src_h ||
13614             old_plane_state->crtc_w != crtc_w ||
13615             old_plane_state->crtc_h != crtc_h ||
13616             !old_plane_state->fb != !fb)
13617                 goto slow;
13618
13619         new_plane_state = intel_plane_duplicate_state(plane);
13620         if (!new_plane_state)
13621                 return -ENOMEM;
13622
13623         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13624
13625         new_plane_state->src_x = src_x;
13626         new_plane_state->src_y = src_y;
13627         new_plane_state->src_w = src_w;
13628         new_plane_state->src_h = src_h;
13629         new_plane_state->crtc_x = crtc_x;
13630         new_plane_state->crtc_y = crtc_y;
13631         new_plane_state->crtc_w = crtc_w;
13632         new_plane_state->crtc_h = crtc_h;
13633
13634         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13635                                                   to_intel_plane_state(new_plane_state));
13636         if (ret)
13637                 goto out_free;
13638
13639         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13640         if (ret)
13641                 goto out_free;
13642
13643         if (INTEL_INFO(dev_priv)->cursor_needs_physical) {
13644                 int align = intel_cursor_alignment(dev_priv);
13645
13646                 ret = i915_gem_object_attach_phys(intel_fb_obj(fb), align);
13647                 if (ret) {
13648                         DRM_DEBUG_KMS("failed to attach phys object\n");
13649                         goto out_unlock;
13650                 }
13651         } else {
13652                 struct i915_vma *vma;
13653
13654                 vma = intel_pin_and_fence_fb_obj(fb, new_plane_state->rotation);
13655                 if (IS_ERR(vma)) {
13656                         DRM_DEBUG_KMS("failed to pin object\n");
13657
13658                         ret = PTR_ERR(vma);
13659                         goto out_unlock;
13660                 }
13661
13662                 to_intel_plane_state(new_plane_state)->vma = vma;
13663         }
13664
13665         old_fb = old_plane_state->fb;
13666         old_vma = to_intel_plane_state(old_plane_state)->vma;
13667
13668         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13669                           intel_plane->frontbuffer_bit);
13670
13671         /* Swap plane state */
13672         new_plane_state->fence = old_plane_state->fence;
13673         *to_intel_plane_state(old_plane_state) = *to_intel_plane_state(new_plane_state);
13674         new_plane_state->fence = NULL;
13675         new_plane_state->fb = old_fb;
13676         to_intel_plane_state(new_plane_state)->vma = old_vma;
13677
13678         if (plane->state->visible) {
13679                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13680                 intel_plane->update_plane(intel_plane,
13681                                           to_intel_crtc_state(crtc->state),
13682                                           to_intel_plane_state(plane->state));
13683         } else {
13684                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13685                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13686         }
13687
13688         intel_cleanup_plane_fb(plane, new_plane_state);
13689
13690 out_unlock:
13691         mutex_unlock(&dev_priv->drm.struct_mutex);
13692 out_free:
13693         intel_plane_destroy_state(plane, new_plane_state);
13694         return ret;
13695
13696 slow:
13697         return drm_atomic_helper_update_plane(plane, crtc, fb,
13698                                               crtc_x, crtc_y, crtc_w, crtc_h,
13699                                               src_x, src_y, src_w, src_h, ctx);
13700 }
13701
13702 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13703         .update_plane = intel_legacy_cursor_update,
13704         .disable_plane = drm_atomic_helper_disable_plane,
13705         .destroy = intel_plane_destroy,
13706         .set_property = drm_atomic_helper_plane_set_property,
13707         .atomic_get_property = intel_plane_atomic_get_property,
13708         .atomic_set_property = intel_plane_atomic_set_property,
13709         .atomic_duplicate_state = intel_plane_duplicate_state,
13710         .atomic_destroy_state = intel_plane_destroy_state,
13711 };
13712
13713 static struct intel_plane *
13714 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13715 {
13716         struct intel_plane *primary = NULL;
13717         struct intel_plane_state *state = NULL;
13718         const uint32_t *intel_primary_formats;
13719         unsigned int supported_rotations;
13720         unsigned int num_formats;
13721         int ret;
13722
13723         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13724         if (!primary) {
13725                 ret = -ENOMEM;
13726                 goto fail;
13727         }
13728
13729         state = intel_create_plane_state(&primary->base);
13730         if (!state) {
13731                 ret = -ENOMEM;
13732                 goto fail;
13733         }
13734
13735         primary->base.state = &state->base;
13736
13737         primary->can_scale = false;
13738         primary->max_downscale = 1;
13739         if (INTEL_GEN(dev_priv) >= 9) {
13740                 primary->can_scale = true;
13741                 state->scaler_id = -1;
13742         }
13743         primary->pipe = pipe;
13744         /*
13745          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13746          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13747          */
13748         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13749                 primary->plane = (enum plane) !pipe;
13750         else
13751                 primary->plane = (enum plane) pipe;
13752         primary->id = PLANE_PRIMARY;
13753         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13754         primary->check_plane = intel_check_primary_plane;
13755
13756         if (INTEL_GEN(dev_priv) >= 9) {
13757                 intel_primary_formats = skl_primary_formats;
13758                 num_formats = ARRAY_SIZE(skl_primary_formats);
13759
13760                 primary->update_plane = skylake_update_primary_plane;
13761                 primary->disable_plane = skylake_disable_primary_plane;
13762         } else if (INTEL_GEN(dev_priv) >= 4) {
13763                 intel_primary_formats = i965_primary_formats;
13764                 num_formats = ARRAY_SIZE(i965_primary_formats);
13765
13766                 primary->update_plane = i9xx_update_primary_plane;
13767                 primary->disable_plane = i9xx_disable_primary_plane;
13768         } else {
13769                 intel_primary_formats = i8xx_primary_formats;
13770                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13771
13772                 primary->update_plane = i9xx_update_primary_plane;
13773                 primary->disable_plane = i9xx_disable_primary_plane;
13774         }
13775
13776         if (INTEL_GEN(dev_priv) >= 9)
13777                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13778                                                0, &intel_plane_funcs,
13779                                                intel_primary_formats, num_formats,
13780                                                DRM_PLANE_TYPE_PRIMARY,
13781                                                "plane 1%c", pipe_name(pipe));
13782         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13783                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13784                                                0, &intel_plane_funcs,
13785                                                intel_primary_formats, num_formats,
13786                                                DRM_PLANE_TYPE_PRIMARY,
13787                                                "primary %c", pipe_name(pipe));
13788         else
13789                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13790                                                0, &intel_plane_funcs,
13791                                                intel_primary_formats, num_formats,
13792                                                DRM_PLANE_TYPE_PRIMARY,
13793                                                "plane %c", plane_name(primary->plane));
13794         if (ret)
13795                 goto fail;
13796
13797         if (INTEL_GEN(dev_priv) >= 9) {
13798                 supported_rotations =
13799                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13800                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13801         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13802                 supported_rotations =
13803                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13804                         DRM_MODE_REFLECT_X;
13805         } else if (INTEL_GEN(dev_priv) >= 4) {
13806                 supported_rotations =
13807                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13808         } else {
13809                 supported_rotations = DRM_MODE_ROTATE_0;
13810         }
13811
13812         if (INTEL_GEN(dev_priv) >= 4)
13813                 drm_plane_create_rotation_property(&primary->base,
13814                                                    DRM_MODE_ROTATE_0,
13815                                                    supported_rotations);
13816
13817         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13818
13819         return primary;
13820
13821 fail:
13822         kfree(state);
13823         kfree(primary);
13824
13825         return ERR_PTR(ret);
13826 }
13827
13828 static struct intel_plane *
13829 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13830                           enum pipe pipe)
13831 {
13832         struct intel_plane *cursor = NULL;
13833         struct intel_plane_state *state = NULL;
13834         int ret;
13835
13836         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13837         if (!cursor) {
13838                 ret = -ENOMEM;
13839                 goto fail;
13840         }
13841
13842         state = intel_create_plane_state(&cursor->base);
13843         if (!state) {
13844                 ret = -ENOMEM;
13845                 goto fail;
13846         }
13847
13848         cursor->base.state = &state->base;
13849
13850         cursor->can_scale = false;
13851         cursor->max_downscale = 1;
13852         cursor->pipe = pipe;
13853         cursor->plane = pipe;
13854         cursor->id = PLANE_CURSOR;
13855         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13856
13857         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13858                 cursor->update_plane = i845_update_cursor;
13859                 cursor->disable_plane = i845_disable_cursor;
13860                 cursor->check_plane = i845_check_cursor;
13861         } else {
13862                 cursor->update_plane = i9xx_update_cursor;
13863                 cursor->disable_plane = i9xx_disable_cursor;
13864                 cursor->check_plane = i9xx_check_cursor;
13865         }
13866
13867         cursor->cursor.base = ~0;
13868         cursor->cursor.cntl = ~0;
13869
13870         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13871                 cursor->cursor.size = ~0;
13872
13873         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13874                                        0, &intel_cursor_plane_funcs,
13875                                        intel_cursor_formats,
13876                                        ARRAY_SIZE(intel_cursor_formats),
13877                                        DRM_PLANE_TYPE_CURSOR,
13878                                        "cursor %c", pipe_name(pipe));
13879         if (ret)
13880                 goto fail;
13881
13882         if (INTEL_GEN(dev_priv) >= 4)
13883                 drm_plane_create_rotation_property(&cursor->base,
13884                                                    DRM_MODE_ROTATE_0,
13885                                                    DRM_MODE_ROTATE_0 |
13886                                                    DRM_MODE_ROTATE_180);
13887
13888         if (INTEL_GEN(dev_priv) >= 9)
13889                 state->scaler_id = -1;
13890
13891         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13892
13893         return cursor;
13894
13895 fail:
13896         kfree(state);
13897         kfree(cursor);
13898
13899         return ERR_PTR(ret);
13900 }
13901
13902 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13903                                     struct intel_crtc_state *crtc_state)
13904 {
13905         struct intel_crtc_scaler_state *scaler_state =
13906                 &crtc_state->scaler_state;
13907         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13908         int i;
13909
13910         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13911         if (!crtc->num_scalers)
13912                 return;
13913
13914         for (i = 0; i < crtc->num_scalers; i++) {
13915                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13916
13917                 scaler->in_use = 0;
13918                 scaler->mode = PS_SCALER_MODE_DYN;
13919         }
13920
13921         scaler_state->scaler_id = -1;
13922 }
13923
13924 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13925 {
13926         struct intel_crtc *intel_crtc;
13927         struct intel_crtc_state *crtc_state = NULL;
13928         struct intel_plane *primary = NULL;
13929         struct intel_plane *cursor = NULL;
13930         int sprite, ret;
13931
13932         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13933         if (!intel_crtc)
13934                 return -ENOMEM;
13935
13936         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13937         if (!crtc_state) {
13938                 ret = -ENOMEM;
13939                 goto fail;
13940         }
13941         intel_crtc->config = crtc_state;
13942         intel_crtc->base.state = &crtc_state->base;
13943         crtc_state->base.crtc = &intel_crtc->base;
13944
13945         primary = intel_primary_plane_create(dev_priv, pipe);
13946         if (IS_ERR(primary)) {
13947                 ret = PTR_ERR(primary);
13948                 goto fail;
13949         }
13950         intel_crtc->plane_ids_mask |= BIT(primary->id);
13951
13952         for_each_sprite(dev_priv, pipe, sprite) {
13953                 struct intel_plane *plane;
13954
13955                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13956                 if (IS_ERR(plane)) {
13957                         ret = PTR_ERR(plane);
13958                         goto fail;
13959                 }
13960                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13961         }
13962
13963         cursor = intel_cursor_plane_create(dev_priv, pipe);
13964         if (IS_ERR(cursor)) {
13965                 ret = PTR_ERR(cursor);
13966                 goto fail;
13967         }
13968         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13969
13970         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13971                                         &primary->base, &cursor->base,
13972                                         &intel_crtc_funcs,
13973                                         "pipe %c", pipe_name(pipe));
13974         if (ret)
13975                 goto fail;
13976
13977         intel_crtc->pipe = pipe;
13978         intel_crtc->plane = primary->plane;
13979
13980         /* initialize shared scalers */
13981         intel_crtc_init_scalers(intel_crtc, crtc_state);
13982
13983         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13984                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13985         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = intel_crtc;
13986         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
13987
13988         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13989
13990         intel_color_init(&intel_crtc->base);
13991
13992         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13993
13994         return 0;
13995
13996 fail:
13997         /*
13998          * drm_mode_config_cleanup() will free up any
13999          * crtcs/planes already initialized.
14000          */
14001         kfree(crtc_state);
14002         kfree(intel_crtc);
14003
14004         return ret;
14005 }
14006
14007 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14008 {
14009         struct drm_device *dev = connector->base.dev;
14010
14011         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14012
14013         if (!connector->base.state->crtc)
14014                 return INVALID_PIPE;
14015
14016         return to_intel_crtc(connector->base.state->crtc)->pipe;
14017 }
14018
14019 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14020                                 struct drm_file *file)
14021 {
14022         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14023         struct drm_crtc *drmmode_crtc;
14024         struct intel_crtc *crtc;
14025
14026         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14027         if (!drmmode_crtc)
14028                 return -ENOENT;
14029
14030         crtc = to_intel_crtc(drmmode_crtc);
14031         pipe_from_crtc_id->pipe = crtc->pipe;
14032
14033         return 0;
14034 }
14035
14036 static int intel_encoder_clones(struct intel_encoder *encoder)
14037 {
14038         struct drm_device *dev = encoder->base.dev;
14039         struct intel_encoder *source_encoder;
14040         int index_mask = 0;
14041         int entry = 0;
14042
14043         for_each_intel_encoder(dev, source_encoder) {
14044                 if (encoders_cloneable(encoder, source_encoder))
14045                         index_mask |= (1 << entry);
14046
14047                 entry++;
14048         }
14049
14050         return index_mask;
14051 }
14052
14053 static bool has_edp_a(struct drm_i915_private *dev_priv)
14054 {
14055         if (!IS_MOBILE(dev_priv))
14056                 return false;
14057
14058         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14059                 return false;
14060
14061         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14062                 return false;
14063
14064         return true;
14065 }
14066
14067 static bool intel_crt_present(struct drm_i915_private *dev_priv)
14068 {
14069         if (INTEL_GEN(dev_priv) >= 9)
14070                 return false;
14071
14072         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14073                 return false;
14074
14075         if (IS_CHERRYVIEW(dev_priv))
14076                 return false;
14077
14078         if (HAS_PCH_LPT_H(dev_priv) &&
14079             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14080                 return false;
14081
14082         /* DDI E can't be used if DDI A requires 4 lanes */
14083         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14084                 return false;
14085
14086         if (!dev_priv->vbt.int_crt_support)
14087                 return false;
14088
14089         return true;
14090 }
14091
14092 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14093 {
14094         int pps_num;
14095         int pps_idx;
14096
14097         if (HAS_DDI(dev_priv))
14098                 return;
14099         /*
14100          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14101          * everywhere where registers can be write protected.
14102          */
14103         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14104                 pps_num = 2;
14105         else
14106                 pps_num = 1;
14107
14108         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14109                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14110
14111                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14112                 I915_WRITE(PP_CONTROL(pps_idx), val);
14113         }
14114 }
14115
14116 static void intel_pps_init(struct drm_i915_private *dev_priv)
14117 {
14118         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14119                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14120         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14121                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14122         else
14123                 dev_priv->pps_mmio_base = PPS_BASE;
14124
14125         intel_pps_unlock_regs_wa(dev_priv);
14126 }
14127
14128 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14129 {
14130         struct intel_encoder *encoder;
14131         bool dpd_is_edp = false;
14132
14133         intel_pps_init(dev_priv);
14134
14135         /*
14136          * intel_edp_init_connector() depends on this completing first, to
14137          * prevent the registeration of both eDP and LVDS and the incorrect
14138          * sharing of the PPS.
14139          */
14140         intel_lvds_init(dev_priv);
14141
14142         if (intel_crt_present(dev_priv))
14143                 intel_crt_init(dev_priv);
14144
14145         if (IS_GEN9_LP(dev_priv)) {
14146                 /*
14147                  * FIXME: Broxton doesn't support port detection via the
14148                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14149                  * detect the ports.
14150                  */
14151                 intel_ddi_init(dev_priv, PORT_A);
14152                 intel_ddi_init(dev_priv, PORT_B);
14153                 intel_ddi_init(dev_priv, PORT_C);
14154
14155                 intel_dsi_init(dev_priv);
14156         } else if (HAS_DDI(dev_priv)) {
14157                 int found;
14158
14159                 /*
14160                  * Haswell uses DDI functions to detect digital outputs.
14161                  * On SKL pre-D0 the strap isn't connected, so we assume
14162                  * it's there.
14163                  */
14164                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14165                 /* WaIgnoreDDIAStrap: skl */
14166                 if (found || IS_GEN9_BC(dev_priv))
14167                         intel_ddi_init(dev_priv, PORT_A);
14168
14169                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14170                  * register */
14171                 found = I915_READ(SFUSE_STRAP);
14172
14173                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14174                         intel_ddi_init(dev_priv, PORT_B);
14175                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14176                         intel_ddi_init(dev_priv, PORT_C);
14177                 if (found & SFUSE_STRAP_DDID_DETECTED)
14178                         intel_ddi_init(dev_priv, PORT_D);
14179                 /*
14180                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14181                  */
14182                 if (IS_GEN9_BC(dev_priv) &&
14183                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14184                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14185                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14186                         intel_ddi_init(dev_priv, PORT_E);
14187
14188         } else if (HAS_PCH_SPLIT(dev_priv)) {
14189                 int found;
14190                 dpd_is_edp = intel_dp_is_edp(dev_priv, PORT_D);
14191
14192                 if (has_edp_a(dev_priv))
14193                         intel_dp_init(dev_priv, DP_A, PORT_A);
14194
14195                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14196                         /* PCH SDVOB multiplex with HDMIB */
14197                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14198                         if (!found)
14199                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14200                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14201                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14202                 }
14203
14204                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14205                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14206
14207                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14208                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14209
14210                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14211                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14212
14213                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14214                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14215         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14216                 bool has_edp, has_port;
14217
14218                 /*
14219                  * The DP_DETECTED bit is the latched state of the DDC
14220                  * SDA pin at boot. However since eDP doesn't require DDC
14221                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14222                  * eDP ports may have been muxed to an alternate function.
14223                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14224                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14225                  * detect eDP ports.
14226                  *
14227                  * Sadly the straps seem to be missing sometimes even for HDMI
14228                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14229                  * and VBT for the presence of the port. Additionally we can't
14230                  * trust the port type the VBT declares as we've seen at least
14231                  * HDMI ports that the VBT claim are DP or eDP.
14232                  */
14233                 has_edp = intel_dp_is_edp(dev_priv, PORT_B);
14234                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14235                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14236                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14237                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14238                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14239
14240                 has_edp = intel_dp_is_edp(dev_priv, PORT_C);
14241                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14242                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14243                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14244                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14245                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14246
14247                 if (IS_CHERRYVIEW(dev_priv)) {
14248                         /*
14249                          * eDP not supported on port D,
14250                          * so no need to worry about it
14251                          */
14252                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14253                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14254                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14255                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14256                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14257                 }
14258
14259                 intel_dsi_init(dev_priv);
14260         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14261                 bool found = false;
14262
14263                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14264                         DRM_DEBUG_KMS("probing SDVOB\n");
14265                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14266                         if (!found && IS_G4X(dev_priv)) {
14267                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14268                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14269                         }
14270
14271                         if (!found && IS_G4X(dev_priv))
14272                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14273                 }
14274
14275                 /* Before G4X SDVOC doesn't have its own detect register */
14276
14277                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14278                         DRM_DEBUG_KMS("probing SDVOC\n");
14279                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14280                 }
14281
14282                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14283
14284                         if (IS_G4X(dev_priv)) {
14285                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14286                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14287                         }
14288                         if (IS_G4X(dev_priv))
14289                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14290                 }
14291
14292                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14293                         intel_dp_init(dev_priv, DP_D, PORT_D);
14294         } else if (IS_GEN2(dev_priv))
14295                 intel_dvo_init(dev_priv);
14296
14297         if (SUPPORTS_TV(dev_priv))
14298                 intel_tv_init(dev_priv);
14299
14300         intel_psr_init(dev_priv);
14301
14302         for_each_intel_encoder(&dev_priv->drm, encoder) {
14303                 encoder->base.possible_crtcs = encoder->crtc_mask;
14304                 encoder->base.possible_clones =
14305                         intel_encoder_clones(encoder);
14306         }
14307
14308         intel_init_pch_refclk(dev_priv);
14309
14310         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14311 }
14312
14313 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14314 {
14315         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14316
14317         drm_framebuffer_cleanup(fb);
14318
14319         i915_gem_object_lock(intel_fb->obj);
14320         WARN_ON(!intel_fb->obj->framebuffer_references--);
14321         i915_gem_object_unlock(intel_fb->obj);
14322
14323         i915_gem_object_put(intel_fb->obj);
14324
14325         kfree(intel_fb);
14326 }
14327
14328 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14329                                                 struct drm_file *file,
14330                                                 unsigned int *handle)
14331 {
14332         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14333         struct drm_i915_gem_object *obj = intel_fb->obj;
14334
14335         if (obj->userptr.mm) {
14336                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14337                 return -EINVAL;
14338         }
14339
14340         return drm_gem_handle_create(file, &obj->base, handle);
14341 }
14342
14343 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14344                                         struct drm_file *file,
14345                                         unsigned flags, unsigned color,
14346                                         struct drm_clip_rect *clips,
14347                                         unsigned num_clips)
14348 {
14349         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14350
14351         i915_gem_object_flush_if_display(obj);
14352         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14353
14354         return 0;
14355 }
14356
14357 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14358         .destroy = intel_user_framebuffer_destroy,
14359         .create_handle = intel_user_framebuffer_create_handle,
14360         .dirty = intel_user_framebuffer_dirty,
14361 };
14362
14363 static
14364 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14365                          uint64_t fb_modifier, uint32_t pixel_format)
14366 {
14367         u32 gen = INTEL_GEN(dev_priv);
14368
14369         if (gen >= 9) {
14370                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14371
14372                 /* "The stride in bytes must not exceed the of the size of 8K
14373                  *  pixels and 32K bytes."
14374                  */
14375                 return min(8192 * cpp, 32768);
14376         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
14377                 return 32*1024;
14378         } else if (gen >= 4) {
14379                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14380                         return 16*1024;
14381                 else
14382                         return 32*1024;
14383         } else if (gen >= 3) {
14384                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14385                         return 8*1024;
14386                 else
14387                         return 16*1024;
14388         } else {
14389                 /* XXX DSPC is limited to 4k tiled */
14390                 return 8*1024;
14391         }
14392 }
14393
14394 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14395                                   struct drm_i915_gem_object *obj,
14396                                   struct drm_mode_fb_cmd2 *mode_cmd)
14397 {
14398         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14399         struct drm_format_name_buf format_name;
14400         u32 pitch_limit, stride_alignment;
14401         unsigned int tiling, stride;
14402         int ret = -EINVAL;
14403
14404         i915_gem_object_lock(obj);
14405         obj->framebuffer_references++;
14406         tiling = i915_gem_object_get_tiling(obj);
14407         stride = i915_gem_object_get_stride(obj);
14408         i915_gem_object_unlock(obj);
14409
14410         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14411                 /*
14412                  * If there's a fence, enforce that
14413                  * the fb modifier and tiling mode match.
14414                  */
14415                 if (tiling != I915_TILING_NONE &&
14416                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14417                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14418                         goto err;
14419                 }
14420         } else {
14421                 if (tiling == I915_TILING_X) {
14422                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14423                 } else if (tiling == I915_TILING_Y) {
14424                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14425                         goto err;
14426                 }
14427         }
14428
14429         /* Passed in modifier sanity checking. */
14430         switch (mode_cmd->modifier[0]) {
14431         case I915_FORMAT_MOD_Y_TILED:
14432         case I915_FORMAT_MOD_Yf_TILED:
14433                 if (INTEL_GEN(dev_priv) < 9) {
14434                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14435                                       mode_cmd->modifier[0]);
14436                         goto err;
14437                 }
14438         case DRM_FORMAT_MOD_LINEAR:
14439         case I915_FORMAT_MOD_X_TILED:
14440                 break;
14441         default:
14442                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14443                               mode_cmd->modifier[0]);
14444                 goto err;
14445         }
14446
14447         /*
14448          * gen2/3 display engine uses the fence if present,
14449          * so the tiling mode must match the fb modifier exactly.
14450          */
14451         if (INTEL_INFO(dev_priv)->gen < 4 &&
14452             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14453                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14454                 goto err;
14455         }
14456
14457         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14458                                            mode_cmd->pixel_format);
14459         if (mode_cmd->pitches[0] > pitch_limit) {
14460                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14461                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14462                               "tiled" : "linear",
14463                               mode_cmd->pitches[0], pitch_limit);
14464                 goto err;
14465         }
14466
14467         /*
14468          * If there's a fence, enforce that
14469          * the fb pitch and fence stride match.
14470          */
14471         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14472                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14473                               mode_cmd->pitches[0], stride);
14474                 goto err;
14475         }
14476
14477         /* Reject formats not supported by any plane early. */
14478         switch (mode_cmd->pixel_format) {
14479         case DRM_FORMAT_C8:
14480         case DRM_FORMAT_RGB565:
14481         case DRM_FORMAT_XRGB8888:
14482         case DRM_FORMAT_ARGB8888:
14483                 break;
14484         case DRM_FORMAT_XRGB1555:
14485                 if (INTEL_GEN(dev_priv) > 3) {
14486                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14487                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14488                         goto err;
14489                 }
14490                 break;
14491         case DRM_FORMAT_ABGR8888:
14492                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14493                     INTEL_GEN(dev_priv) < 9) {
14494                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14495                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14496                         goto err;
14497                 }
14498                 break;
14499         case DRM_FORMAT_XBGR8888:
14500         case DRM_FORMAT_XRGB2101010:
14501         case DRM_FORMAT_XBGR2101010:
14502                 if (INTEL_GEN(dev_priv) < 4) {
14503                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14504                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14505                         goto err;
14506                 }
14507                 break;
14508         case DRM_FORMAT_ABGR2101010:
14509                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14510                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14511                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14512                         goto err;
14513                 }
14514                 break;
14515         case DRM_FORMAT_YUYV:
14516         case DRM_FORMAT_UYVY:
14517         case DRM_FORMAT_YVYU:
14518         case DRM_FORMAT_VYUY:
14519                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14520                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14521                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14522                         goto err;
14523                 }
14524                 break;
14525         default:
14526                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14527                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14528                 goto err;
14529         }
14530
14531         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14532         if (mode_cmd->offsets[0] != 0)
14533                 goto err;
14534
14535         drm_helper_mode_fill_fb_struct(&dev_priv->drm,
14536                                        &intel_fb->base, mode_cmd);
14537
14538         stride_alignment = intel_fb_stride_alignment(&intel_fb->base, 0);
14539         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14540                 DRM_DEBUG_KMS("pitch (%d) must be at least %u byte aligned\n",
14541                               mode_cmd->pitches[0], stride_alignment);
14542                 goto err;
14543         }
14544
14545         intel_fb->obj = obj;
14546
14547         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
14548         if (ret)
14549                 goto err;
14550
14551         ret = drm_framebuffer_init(obj->base.dev,
14552                                    &intel_fb->base,
14553                                    &intel_fb_funcs);
14554         if (ret) {
14555                 DRM_ERROR("framebuffer init failed %d\n", ret);
14556                 goto err;
14557         }
14558
14559         return 0;
14560
14561 err:
14562         i915_gem_object_lock(obj);
14563         obj->framebuffer_references--;
14564         i915_gem_object_unlock(obj);
14565         return ret;
14566 }
14567
14568 static struct drm_framebuffer *
14569 intel_user_framebuffer_create(struct drm_device *dev,
14570                               struct drm_file *filp,
14571                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14572 {
14573         struct drm_framebuffer *fb;
14574         struct drm_i915_gem_object *obj;
14575         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14576
14577         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14578         if (!obj)
14579                 return ERR_PTR(-ENOENT);
14580
14581         fb = intel_framebuffer_create(obj, &mode_cmd);
14582         if (IS_ERR(fb))
14583                 i915_gem_object_put(obj);
14584
14585         return fb;
14586 }
14587
14588 static void intel_atomic_state_free(struct drm_atomic_state *state)
14589 {
14590         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14591
14592         drm_atomic_state_default_release(state);
14593
14594         i915_sw_fence_fini(&intel_state->commit_ready);
14595
14596         kfree(state);
14597 }
14598
14599 static const struct drm_mode_config_funcs intel_mode_funcs = {
14600         .fb_create = intel_user_framebuffer_create,
14601         .output_poll_changed = intel_fbdev_output_poll_changed,
14602         .atomic_check = intel_atomic_check,
14603         .atomic_commit = intel_atomic_commit,
14604         .atomic_state_alloc = intel_atomic_state_alloc,
14605         .atomic_state_clear = intel_atomic_state_clear,
14606         .atomic_state_free = intel_atomic_state_free,
14607 };
14608
14609 /**
14610  * intel_init_display_hooks - initialize the display modesetting hooks
14611  * @dev_priv: device private
14612  */
14613 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14614 {
14615         intel_init_cdclk_hooks(dev_priv);
14616
14617         if (INTEL_INFO(dev_priv)->gen >= 9) {
14618                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14619                 dev_priv->display.get_initial_plane_config =
14620                         skylake_get_initial_plane_config;
14621                 dev_priv->display.crtc_compute_clock =
14622                         haswell_crtc_compute_clock;
14623                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14624                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14625         } else if (HAS_DDI(dev_priv)) {
14626                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14627                 dev_priv->display.get_initial_plane_config =
14628                         ironlake_get_initial_plane_config;
14629                 dev_priv->display.crtc_compute_clock =
14630                         haswell_crtc_compute_clock;
14631                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14632                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14633         } else if (HAS_PCH_SPLIT(dev_priv)) {
14634                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14635                 dev_priv->display.get_initial_plane_config =
14636                         ironlake_get_initial_plane_config;
14637                 dev_priv->display.crtc_compute_clock =
14638                         ironlake_crtc_compute_clock;
14639                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14640                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14641         } else if (IS_CHERRYVIEW(dev_priv)) {
14642                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14643                 dev_priv->display.get_initial_plane_config =
14644                         i9xx_get_initial_plane_config;
14645                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14646                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14647                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14648         } else if (IS_VALLEYVIEW(dev_priv)) {
14649                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14650                 dev_priv->display.get_initial_plane_config =
14651                         i9xx_get_initial_plane_config;
14652                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14653                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14654                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14655         } else if (IS_G4X(dev_priv)) {
14656                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14657                 dev_priv->display.get_initial_plane_config =
14658                         i9xx_get_initial_plane_config;
14659                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14660                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14661                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14662         } else if (IS_PINEVIEW(dev_priv)) {
14663                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14664                 dev_priv->display.get_initial_plane_config =
14665                         i9xx_get_initial_plane_config;
14666                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14667                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14668                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14669         } else if (!IS_GEN2(dev_priv)) {
14670                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14671                 dev_priv->display.get_initial_plane_config =
14672                         i9xx_get_initial_plane_config;
14673                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14674                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14675                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14676         } else {
14677                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14678                 dev_priv->display.get_initial_plane_config =
14679                         i9xx_get_initial_plane_config;
14680                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14681                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14682                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14683         }
14684
14685         if (IS_GEN5(dev_priv)) {
14686                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14687         } else if (IS_GEN6(dev_priv)) {
14688                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14689         } else if (IS_IVYBRIDGE(dev_priv)) {
14690                 /* FIXME: detect B0+ stepping and use auto training */
14691                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14692         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14693                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14694         }
14695
14696         if (dev_priv->info.gen >= 9)
14697                 dev_priv->display.update_crtcs = skl_update_crtcs;
14698         else
14699                 dev_priv->display.update_crtcs = intel_update_crtcs;
14700
14701         switch (INTEL_INFO(dev_priv)->gen) {
14702         case 2:
14703                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14704                 break;
14705
14706         case 3:
14707                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14708                 break;
14709
14710         case 4:
14711         case 5:
14712                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14713                 break;
14714
14715         case 6:
14716                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14717                 break;
14718         case 7:
14719         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14720                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14721                 break;
14722         case 9:
14723                 /* Drop through - unsupported since execlist only. */
14724         default:
14725                 /* Default just returns -ENODEV to indicate unsupported */
14726                 dev_priv->display.queue_flip = intel_default_queue_flip;
14727         }
14728 }
14729
14730 /*
14731  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14732  * resume, or other times.  This quirk makes sure that's the case for
14733  * affected systems.
14734  */
14735 static void quirk_pipea_force(struct drm_device *dev)
14736 {
14737         struct drm_i915_private *dev_priv = to_i915(dev);
14738
14739         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14740         DRM_INFO("applying pipe a force quirk\n");
14741 }
14742
14743 static void quirk_pipeb_force(struct drm_device *dev)
14744 {
14745         struct drm_i915_private *dev_priv = to_i915(dev);
14746
14747         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14748         DRM_INFO("applying pipe b force quirk\n");
14749 }
14750
14751 /*
14752  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14753  */
14754 static void quirk_ssc_force_disable(struct drm_device *dev)
14755 {
14756         struct drm_i915_private *dev_priv = to_i915(dev);
14757         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14758         DRM_INFO("applying lvds SSC disable quirk\n");
14759 }
14760
14761 /*
14762  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14763  * brightness value
14764  */
14765 static void quirk_invert_brightness(struct drm_device *dev)
14766 {
14767         struct drm_i915_private *dev_priv = to_i915(dev);
14768         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14769         DRM_INFO("applying inverted panel brightness quirk\n");
14770 }
14771
14772 /* Some VBT's incorrectly indicate no backlight is present */
14773 static void quirk_backlight_present(struct drm_device *dev)
14774 {
14775         struct drm_i915_private *dev_priv = to_i915(dev);
14776         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14777         DRM_INFO("applying backlight present quirk\n");
14778 }
14779
14780 struct intel_quirk {
14781         int device;
14782         int subsystem_vendor;
14783         int subsystem_device;
14784         void (*hook)(struct drm_device *dev);
14785 };
14786
14787 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14788 struct intel_dmi_quirk {
14789         void (*hook)(struct drm_device *dev);
14790         const struct dmi_system_id (*dmi_id_list)[];
14791 };
14792
14793 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14794 {
14795         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14796         return 1;
14797 }
14798
14799 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14800         {
14801                 .dmi_id_list = &(const struct dmi_system_id[]) {
14802                         {
14803                                 .callback = intel_dmi_reverse_brightness,
14804                                 .ident = "NCR Corporation",
14805                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14806                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14807                                 },
14808                         },
14809                         { }  /* terminating entry */
14810                 },
14811                 .hook = quirk_invert_brightness,
14812         },
14813 };
14814
14815 static struct intel_quirk intel_quirks[] = {
14816         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14817         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14818
14819         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14820         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14821
14822         /* 830 needs to leave pipe A & dpll A up */
14823         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14824
14825         /* 830 needs to leave pipe B & dpll B up */
14826         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14827
14828         /* Lenovo U160 cannot use SSC on LVDS */
14829         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14830
14831         /* Sony Vaio Y cannot use SSC on LVDS */
14832         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14833
14834         /* Acer Aspire 5734Z must invert backlight brightness */
14835         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14836
14837         /* Acer/eMachines G725 */
14838         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14839
14840         /* Acer/eMachines e725 */
14841         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14842
14843         /* Acer/Packard Bell NCL20 */
14844         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14845
14846         /* Acer Aspire 4736Z */
14847         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14848
14849         /* Acer Aspire 5336 */
14850         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14851
14852         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14853         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14854
14855         /* Acer C720 Chromebook (Core i3 4005U) */
14856         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14857
14858         /* Apple Macbook 2,1 (Core 2 T7400) */
14859         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14860
14861         /* Apple Macbook 4,1 */
14862         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14863
14864         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14865         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14866
14867         /* HP Chromebook 14 (Celeron 2955U) */
14868         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14869
14870         /* Dell Chromebook 11 */
14871         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14872
14873         /* Dell Chromebook 11 (2015 version) */
14874         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14875 };
14876
14877 static void intel_init_quirks(struct drm_device *dev)
14878 {
14879         struct pci_dev *d = dev->pdev;
14880         int i;
14881
14882         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14883                 struct intel_quirk *q = &intel_quirks[i];
14884
14885                 if (d->device == q->device &&
14886                     (d->subsystem_vendor == q->subsystem_vendor ||
14887                      q->subsystem_vendor == PCI_ANY_ID) &&
14888                     (d->subsystem_device == q->subsystem_device ||
14889                      q->subsystem_device == PCI_ANY_ID))
14890                         q->hook(dev);
14891         }
14892         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14893                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14894                         intel_dmi_quirks[i].hook(dev);
14895         }
14896 }
14897
14898 /* Disable the VGA plane that we never use */
14899 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14900 {
14901         struct pci_dev *pdev = dev_priv->drm.pdev;
14902         u8 sr1;
14903         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14904
14905         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14906         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14907         outb(SR01, VGA_SR_INDEX);
14908         sr1 = inb(VGA_SR_DATA);
14909         outb(sr1 | 1<<5, VGA_SR_DATA);
14910         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14911         udelay(300);
14912
14913         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14914         POSTING_READ(vga_reg);
14915 }
14916
14917 void intel_modeset_init_hw(struct drm_device *dev)
14918 {
14919         struct drm_i915_private *dev_priv = to_i915(dev);
14920
14921         intel_update_cdclk(dev_priv);
14922         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14923
14924         intel_init_clock_gating(dev_priv);
14925 }
14926
14927 /*
14928  * Calculate what we think the watermarks should be for the state we've read
14929  * out of the hardware and then immediately program those watermarks so that
14930  * we ensure the hardware settings match our internal state.
14931  *
14932  * We can calculate what we think WM's should be by creating a duplicate of the
14933  * current state (which was constructed during hardware readout) and running it
14934  * through the atomic check code to calculate new watermark values in the
14935  * state object.
14936  */
14937 static void sanitize_watermarks(struct drm_device *dev)
14938 {
14939         struct drm_i915_private *dev_priv = to_i915(dev);
14940         struct drm_atomic_state *state;
14941         struct intel_atomic_state *intel_state;
14942         struct drm_crtc *crtc;
14943         struct drm_crtc_state *cstate;
14944         struct drm_modeset_acquire_ctx ctx;
14945         int ret;
14946         int i;
14947
14948         /* Only supported on platforms that use atomic watermark design */
14949         if (!dev_priv->display.optimize_watermarks)
14950                 return;
14951
14952         /*
14953          * We need to hold connection_mutex before calling duplicate_state so
14954          * that the connector loop is protected.
14955          */
14956         drm_modeset_acquire_init(&ctx, 0);
14957 retry:
14958         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14959         if (ret == -EDEADLK) {
14960                 drm_modeset_backoff(&ctx);
14961                 goto retry;
14962         } else if (WARN_ON(ret)) {
14963                 goto fail;
14964         }
14965
14966         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14967         if (WARN_ON(IS_ERR(state)))
14968                 goto fail;
14969
14970         intel_state = to_intel_atomic_state(state);
14971
14972         /*
14973          * Hardware readout is the only time we don't want to calculate
14974          * intermediate watermarks (since we don't trust the current
14975          * watermarks).
14976          */
14977         if (!HAS_GMCH_DISPLAY(dev_priv))
14978                 intel_state->skip_intermediate_wm = true;
14979
14980         ret = intel_atomic_check(dev, state);
14981         if (ret) {
14982                 /*
14983                  * If we fail here, it means that the hardware appears to be
14984                  * programmed in a way that shouldn't be possible, given our
14985                  * understanding of watermark requirements.  This might mean a
14986                  * mistake in the hardware readout code or a mistake in the
14987                  * watermark calculations for a given platform.  Raise a WARN
14988                  * so that this is noticeable.
14989                  *
14990                  * If this actually happens, we'll have to just leave the
14991                  * BIOS-programmed watermarks untouched and hope for the best.
14992                  */
14993                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14994                 goto put_state;
14995         }
14996
14997         /* Write calculated watermark values back */
14998         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14999                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15000
15001                 cs->wm.need_postvbl_update = true;
15002                 dev_priv->display.optimize_watermarks(intel_state, cs);
15003         }
15004
15005 put_state:
15006         drm_atomic_state_put(state);
15007 fail:
15008         drm_modeset_drop_locks(&ctx);
15009         drm_modeset_acquire_fini(&ctx);
15010 }
15011
15012 int intel_modeset_init(struct drm_device *dev)
15013 {
15014         struct drm_i915_private *dev_priv = to_i915(dev);
15015         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15016         enum pipe pipe;
15017         struct intel_crtc *crtc;
15018
15019         drm_mode_config_init(dev);
15020
15021         dev->mode_config.min_width = 0;
15022         dev->mode_config.min_height = 0;
15023
15024         dev->mode_config.preferred_depth = 24;
15025         dev->mode_config.prefer_shadow = 1;
15026
15027         dev->mode_config.allow_fb_modifiers = true;
15028
15029         dev->mode_config.funcs = &intel_mode_funcs;
15030
15031         init_llist_head(&dev_priv->atomic_helper.free_list);
15032         INIT_WORK(&dev_priv->atomic_helper.free_work,
15033                   intel_atomic_helper_free_state_worker);
15034
15035         intel_init_quirks(dev);
15036
15037         intel_init_pm(dev_priv);
15038
15039         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15040                 return 0;
15041
15042         /*
15043          * There may be no VBT; and if the BIOS enabled SSC we can
15044          * just keep using it to avoid unnecessary flicker.  Whereas if the
15045          * BIOS isn't using it, don't assume it will work even if the VBT
15046          * indicates as much.
15047          */
15048         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15049                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15050                                             DREF_SSC1_ENABLE);
15051
15052                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15053                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15054                                      bios_lvds_use_ssc ? "en" : "dis",
15055                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15056                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15057                 }
15058         }
15059
15060         if (IS_GEN2(dev_priv)) {
15061                 dev->mode_config.max_width = 2048;
15062                 dev->mode_config.max_height = 2048;
15063         } else if (IS_GEN3(dev_priv)) {
15064                 dev->mode_config.max_width = 4096;
15065                 dev->mode_config.max_height = 4096;
15066         } else {
15067                 dev->mode_config.max_width = 8192;
15068                 dev->mode_config.max_height = 8192;
15069         }
15070
15071         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15072                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15073                 dev->mode_config.cursor_height = 1023;
15074         } else if (IS_GEN2(dev_priv)) {
15075                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15076                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15077         } else {
15078                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15079                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15080         }
15081
15082         dev->mode_config.fb_base = ggtt->mappable_base;
15083
15084         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15085                       INTEL_INFO(dev_priv)->num_pipes,
15086                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15087
15088         for_each_pipe(dev_priv, pipe) {
15089                 int ret;
15090
15091                 ret = intel_crtc_init(dev_priv, pipe);
15092                 if (ret) {
15093                         drm_mode_config_cleanup(dev);
15094                         return ret;
15095                 }
15096         }
15097
15098         intel_shared_dpll_init(dev);
15099
15100         intel_update_czclk(dev_priv);
15101         intel_modeset_init_hw(dev);
15102
15103         if (dev_priv->max_cdclk_freq == 0)
15104                 intel_update_max_cdclk(dev_priv);
15105
15106         /* Just disable it once at startup */
15107         i915_disable_vga(dev_priv);
15108         intel_setup_outputs(dev_priv);
15109
15110         drm_modeset_lock_all(dev);
15111         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15112         drm_modeset_unlock_all(dev);
15113
15114         for_each_intel_crtc(dev, crtc) {
15115                 struct intel_initial_plane_config plane_config = {};
15116
15117                 if (!crtc->active)
15118                         continue;
15119
15120                 /*
15121                  * Note that reserving the BIOS fb up front prevents us
15122                  * from stuffing other stolen allocations like the ring
15123                  * on top.  This prevents some ugliness at boot time, and
15124                  * can even allow for smooth boot transitions if the BIOS
15125                  * fb is large enough for the active pipe configuration.
15126                  */
15127                 dev_priv->display.get_initial_plane_config(crtc,
15128                                                            &plane_config);
15129
15130                 /*
15131                  * If the fb is shared between multiple heads, we'll
15132                  * just get the first one.
15133                  */
15134                 intel_find_initial_plane_obj(crtc, &plane_config);
15135         }
15136
15137         /*
15138          * Make sure hardware watermarks really match the state we read out.
15139          * Note that we need to do this after reconstructing the BIOS fb's
15140          * since the watermark calculation done here will use pstate->fb.
15141          */
15142         if (!HAS_GMCH_DISPLAY(dev_priv))
15143                 sanitize_watermarks(dev);
15144
15145         return 0;
15146 }
15147
15148 static void intel_enable_pipe_a(struct drm_device *dev,
15149                                 struct drm_modeset_acquire_ctx *ctx)
15150 {
15151         struct intel_connector *connector;
15152         struct drm_connector_list_iter conn_iter;
15153         struct drm_connector *crt = NULL;
15154         struct intel_load_detect_pipe load_detect_temp;
15155         int ret;
15156
15157         /* We can't just switch on the pipe A, we need to set things up with a
15158          * proper mode and output configuration. As a gross hack, enable pipe A
15159          * by enabling the load detect pipe once. */
15160         drm_connector_list_iter_begin(dev, &conn_iter);
15161         for_each_intel_connector_iter(connector, &conn_iter) {
15162                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15163                         crt = &connector->base;
15164                         break;
15165                 }
15166         }
15167         drm_connector_list_iter_end(&conn_iter);
15168
15169         if (!crt)
15170                 return;
15171
15172         ret = intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx);
15173         WARN(ret < 0, "All modeset mutexes are locked, but intel_get_load_detect_pipe failed\n");
15174
15175         if (ret > 0)
15176                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15177 }
15178
15179 static bool
15180 intel_check_plane_mapping(struct intel_crtc *crtc)
15181 {
15182         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15183         u32 val;
15184
15185         if (INTEL_INFO(dev_priv)->num_pipes == 1)
15186                 return true;
15187
15188         val = I915_READ(DSPCNTR(!crtc->plane));
15189
15190         if ((val & DISPLAY_PLANE_ENABLE) &&
15191             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15192                 return false;
15193
15194         return true;
15195 }
15196
15197 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15198 {
15199         struct drm_device *dev = crtc->base.dev;
15200         struct intel_encoder *encoder;
15201
15202         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15203                 return true;
15204
15205         return false;
15206 }
15207
15208 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15209 {
15210         struct drm_device *dev = encoder->base.dev;
15211         struct intel_connector *connector;
15212
15213         for_each_connector_on_encoder(dev, &encoder->base, connector)
15214                 return connector;
15215
15216         return NULL;
15217 }
15218
15219 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15220                               enum transcoder pch_transcoder)
15221 {
15222         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15223                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
15224 }
15225
15226 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15227                                 struct drm_modeset_acquire_ctx *ctx)
15228 {
15229         struct drm_device *dev = crtc->base.dev;
15230         struct drm_i915_private *dev_priv = to_i915(dev);
15231         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15232
15233         /* Clear any frame start delays used for debugging left by the BIOS */
15234         if (!transcoder_is_dsi(cpu_transcoder)) {
15235                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15236
15237                 I915_WRITE(reg,
15238                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15239         }
15240
15241         /* restore vblank interrupts to correct state */
15242         drm_crtc_vblank_reset(&crtc->base);
15243         if (crtc->active) {
15244                 struct intel_plane *plane;
15245
15246                 drm_crtc_vblank_on(&crtc->base);
15247
15248                 /* Disable everything but the primary plane */
15249                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15250                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15251                                 continue;
15252
15253                         trace_intel_disable_plane(&plane->base, crtc);
15254                         plane->disable_plane(plane, crtc);
15255                 }
15256         }
15257
15258         /* We need to sanitize the plane -> pipe mapping first because this will
15259          * disable the crtc (and hence change the state) if it is wrong. Note
15260          * that gen4+ has a fixed plane -> pipe mapping.  */
15261         if (INTEL_GEN(dev_priv) < 4 && !intel_check_plane_mapping(crtc)) {
15262                 bool plane;
15263
15264                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
15265                               crtc->base.base.id, crtc->base.name);
15266
15267                 /* Pipe has the wrong plane attached and the plane is active.
15268                  * Temporarily change the plane mapping and disable everything
15269                  * ...  */
15270                 plane = crtc->plane;
15271                 crtc->base.primary->state->visible = true;
15272                 crtc->plane = !plane;
15273                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15274                 crtc->plane = plane;
15275         }
15276
15277         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15278             crtc->pipe == PIPE_A && !crtc->active) {
15279                 /* BIOS forgot to enable pipe A, this mostly happens after
15280                  * resume. Force-enable the pipe to fix this, the update_dpms
15281                  * call below we restore the pipe to the right state, but leave
15282                  * the required bits on. */
15283                 intel_enable_pipe_a(dev, ctx);
15284         }
15285
15286         /* Adjust the state of the output pipe according to whether we
15287          * have active connectors/encoders. */
15288         if (crtc->active && !intel_crtc_has_encoders(crtc))
15289                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15290
15291         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15292                 /*
15293                  * We start out with underrun reporting disabled to avoid races.
15294                  * For correct bookkeeping mark this on active crtcs.
15295                  *
15296                  * Also on gmch platforms we dont have any hardware bits to
15297                  * disable the underrun reporting. Which means we need to start
15298                  * out with underrun reporting disabled also on inactive pipes,
15299                  * since otherwise we'll complain about the garbage we read when
15300                  * e.g. coming up after runtime pm.
15301                  *
15302                  * No protection against concurrent access is required - at
15303                  * worst a fifo underrun happens which also sets this to false.
15304                  */
15305                 crtc->cpu_fifo_underrun_disabled = true;
15306                 /*
15307                  * We track the PCH trancoder underrun reporting state
15308                  * within the crtc. With crtc for pipe A housing the underrun
15309                  * reporting state for PCH transcoder A, crtc for pipe B housing
15310                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15311                  * and marking underrun reporting as disabled for the non-existing
15312                  * PCH transcoders B and C would prevent enabling the south
15313                  * error interrupt (see cpt_can_enable_serr_int()).
15314                  */
15315                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
15316                         crtc->pch_fifo_underrun_disabled = true;
15317         }
15318 }
15319
15320 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15321 {
15322         struct intel_connector *connector;
15323
15324         /* We need to check both for a crtc link (meaning that the
15325          * encoder is active and trying to read from a pipe) and the
15326          * pipe itself being active. */
15327         bool has_active_crtc = encoder->base.crtc &&
15328                 to_intel_crtc(encoder->base.crtc)->active;
15329
15330         connector = intel_encoder_find_connector(encoder);
15331         if (connector && !has_active_crtc) {
15332                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15333                               encoder->base.base.id,
15334                               encoder->base.name);
15335
15336                 /* Connector is active, but has no active pipe. This is
15337                  * fallout from our resume register restoring. Disable
15338                  * the encoder manually again. */
15339                 if (encoder->base.crtc) {
15340                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15341
15342                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15343                                       encoder->base.base.id,
15344                                       encoder->base.name);
15345                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15346                         if (encoder->post_disable)
15347                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15348                 }
15349                 encoder->base.crtc = NULL;
15350
15351                 /* Inconsistent output/port/pipe state happens presumably due to
15352                  * a bug in one of the get_hw_state functions. Or someplace else
15353                  * in our code, like the register restore mess on resume. Clamp
15354                  * things to off as a safer default. */
15355
15356                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15357                 connector->base.encoder = NULL;
15358         }
15359         /* Enabled encoders without active connectors will be fixed in
15360          * the crtc fixup. */
15361 }
15362
15363 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15364 {
15365         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15366
15367         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15368                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15369                 i915_disable_vga(dev_priv);
15370         }
15371 }
15372
15373 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15374 {
15375         /* This function can be called both from intel_modeset_setup_hw_state or
15376          * at a very early point in our resume sequence, where the power well
15377          * structures are not yet restored. Since this function is at a very
15378          * paranoid "someone might have enabled VGA while we were not looking"
15379          * level, just check if the power well is enabled instead of trying to
15380          * follow the "don't touch the power well if we don't need it" policy
15381          * the rest of the driver uses. */
15382         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15383                 return;
15384
15385         i915_redisable_vga_power_on(dev_priv);
15386
15387         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15388 }
15389
15390 static bool primary_get_hw_state(struct intel_plane *plane)
15391 {
15392         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15393
15394         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15395 }
15396
15397 /* FIXME read out full plane state for all planes */
15398 static void readout_plane_state(struct intel_crtc *crtc)
15399 {
15400         struct intel_plane *primary = to_intel_plane(crtc->base.primary);
15401         bool visible;
15402
15403         visible = crtc->active && primary_get_hw_state(primary);
15404
15405         intel_set_plane_visible(to_intel_crtc_state(crtc->base.state),
15406                                 to_intel_plane_state(primary->base.state),
15407                                 visible);
15408 }
15409
15410 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15411 {
15412         struct drm_i915_private *dev_priv = to_i915(dev);
15413         enum pipe pipe;
15414         struct intel_crtc *crtc;
15415         struct intel_encoder *encoder;
15416         struct intel_connector *connector;
15417         struct drm_connector_list_iter conn_iter;
15418         int i;
15419
15420         dev_priv->active_crtcs = 0;
15421
15422         for_each_intel_crtc(dev, crtc) {
15423                 struct intel_crtc_state *crtc_state =
15424                         to_intel_crtc_state(crtc->base.state);
15425
15426                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15427                 memset(crtc_state, 0, sizeof(*crtc_state));
15428                 crtc_state->base.crtc = &crtc->base;
15429
15430                 crtc_state->base.active = crtc_state->base.enable =
15431                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15432
15433                 crtc->base.enabled = crtc_state->base.enable;
15434                 crtc->active = crtc_state->base.active;
15435
15436                 if (crtc_state->base.active)
15437                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15438
15439                 readout_plane_state(crtc);
15440
15441                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15442                               crtc->base.base.id, crtc->base.name,
15443                               enableddisabled(crtc_state->base.active));
15444         }
15445
15446         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15447                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15448
15449                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15450                                                   &pll->state.hw_state);
15451                 pll->state.crtc_mask = 0;
15452                 for_each_intel_crtc(dev, crtc) {
15453                         struct intel_crtc_state *crtc_state =
15454                                 to_intel_crtc_state(crtc->base.state);
15455
15456                         if (crtc_state->base.active &&
15457                             crtc_state->shared_dpll == pll)
15458                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15459                 }
15460                 pll->active_mask = pll->state.crtc_mask;
15461
15462                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15463                               pll->name, pll->state.crtc_mask, pll->on);
15464         }
15465
15466         for_each_intel_encoder(dev, encoder) {
15467                 pipe = 0;
15468
15469                 if (encoder->get_hw_state(encoder, &pipe)) {
15470                         struct intel_crtc_state *crtc_state;
15471
15472                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15473                         crtc_state = to_intel_crtc_state(crtc->base.state);
15474
15475                         encoder->base.crtc = &crtc->base;
15476                         crtc_state->output_types |= 1 << encoder->type;
15477                         encoder->get_config(encoder, crtc_state);
15478                 } else {
15479                         encoder->base.crtc = NULL;
15480                 }
15481
15482                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15483                               encoder->base.base.id, encoder->base.name,
15484                               enableddisabled(encoder->base.crtc),
15485                               pipe_name(pipe));
15486         }
15487
15488         drm_connector_list_iter_begin(dev, &conn_iter);
15489         for_each_intel_connector_iter(connector, &conn_iter) {
15490                 if (connector->get_hw_state(connector)) {
15491                         connector->base.dpms = DRM_MODE_DPMS_ON;
15492
15493                         encoder = connector->encoder;
15494                         connector->base.encoder = &encoder->base;
15495
15496                         if (encoder->base.crtc &&
15497                             encoder->base.crtc->state->active) {
15498                                 /*
15499                                  * This has to be done during hardware readout
15500                                  * because anything calling .crtc_disable may
15501                                  * rely on the connector_mask being accurate.
15502                                  */
15503                                 encoder->base.crtc->state->connector_mask |=
15504                                         1 << drm_connector_index(&connector->base);
15505                                 encoder->base.crtc->state->encoder_mask |=
15506                                         1 << drm_encoder_index(&encoder->base);
15507                         }
15508
15509                 } else {
15510                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15511                         connector->base.encoder = NULL;
15512                 }
15513                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15514                               connector->base.base.id, connector->base.name,
15515                               enableddisabled(connector->base.encoder));
15516         }
15517         drm_connector_list_iter_end(&conn_iter);
15518
15519         for_each_intel_crtc(dev, crtc) {
15520                 struct intel_crtc_state *crtc_state =
15521                         to_intel_crtc_state(crtc->base.state);
15522                 int pixclk = 0;
15523
15524                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15525                 if (crtc_state->base.active) {
15526                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15527                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15528                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15529
15530                         /*
15531                          * The initial mode needs to be set in order to keep
15532                          * the atomic core happy. It wants a valid mode if the
15533                          * crtc's enabled, so we do the above call.
15534                          *
15535                          * But we don't set all the derived state fully, hence
15536                          * set a flag to indicate that a full recalculation is
15537                          * needed on the next commit.
15538                          */
15539                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15540
15541                         intel_crtc_compute_pixel_rate(crtc_state);
15542
15543                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv) ||
15544                             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15545                                 pixclk = crtc_state->pixel_rate;
15546                         else
15547                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15548
15549                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15550                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
15551                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15552
15553                         drm_calc_timestamping_constants(&crtc->base,
15554                                                         &crtc_state->base.adjusted_mode);
15555                         update_scanline_offset(crtc);
15556                 }
15557
15558                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15559
15560                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15561         }
15562 }
15563
15564 static void
15565 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15566 {
15567         struct intel_encoder *encoder;
15568
15569         for_each_intel_encoder(&dev_priv->drm, encoder) {
15570                 u64 get_domains;
15571                 enum intel_display_power_domain domain;
15572
15573                 if (!encoder->get_power_domains)
15574                         continue;
15575
15576                 get_domains = encoder->get_power_domains(encoder);
15577                 for_each_power_domain(domain, get_domains)
15578                         intel_display_power_get(dev_priv, domain);
15579         }
15580 }
15581
15582 /* Scan out the current hw modeset state,
15583  * and sanitizes it to the current state
15584  */
15585 static void
15586 intel_modeset_setup_hw_state(struct drm_device *dev,
15587                              struct drm_modeset_acquire_ctx *ctx)
15588 {
15589         struct drm_i915_private *dev_priv = to_i915(dev);
15590         enum pipe pipe;
15591         struct intel_crtc *crtc;
15592         struct intel_encoder *encoder;
15593         int i;
15594
15595         intel_modeset_readout_hw_state(dev);
15596
15597         /* HW state is read out, now we need to sanitize this mess. */
15598         get_encoder_power_domains(dev_priv);
15599
15600         for_each_intel_encoder(dev, encoder) {
15601                 intel_sanitize_encoder(encoder);
15602         }
15603
15604         for_each_pipe(dev_priv, pipe) {
15605                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15606
15607                 intel_sanitize_crtc(crtc, ctx);
15608                 intel_dump_pipe_config(crtc, crtc->config,
15609                                        "[setup_hw_state]");
15610         }
15611
15612         intel_modeset_update_connector_atomic_state(dev);
15613
15614         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15615                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15616
15617                 if (!pll->on || pll->active_mask)
15618                         continue;
15619
15620                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15621
15622                 pll->funcs.disable(dev_priv, pll);
15623                 pll->on = false;
15624         }
15625
15626         if (IS_G4X(dev_priv)) {
15627                 g4x_wm_get_hw_state(dev);
15628                 g4x_wm_sanitize(dev_priv);
15629         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15630                 vlv_wm_get_hw_state(dev);
15631                 vlv_wm_sanitize(dev_priv);
15632         } else if (IS_GEN9(dev_priv)) {
15633                 skl_wm_get_hw_state(dev);
15634         } else if (HAS_PCH_SPLIT(dev_priv)) {
15635                 ilk_wm_get_hw_state(dev);
15636         }
15637
15638         for_each_intel_crtc(dev, crtc) {
15639                 u64 put_domains;
15640
15641                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15642                 if (WARN_ON(put_domains))
15643                         modeset_put_power_domains(dev_priv, put_domains);
15644         }
15645         intel_display_set_init_power(dev_priv, false);
15646
15647         intel_power_domains_verify_state(dev_priv);
15648
15649         intel_fbc_init_pipe_state(dev_priv);
15650 }
15651
15652 void intel_display_resume(struct drm_device *dev)
15653 {
15654         struct drm_i915_private *dev_priv = to_i915(dev);
15655         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15656         struct drm_modeset_acquire_ctx ctx;
15657         int ret;
15658
15659         dev_priv->modeset_restore_state = NULL;
15660         if (state)
15661                 state->acquire_ctx = &ctx;
15662
15663         drm_modeset_acquire_init(&ctx, 0);
15664
15665         while (1) {
15666                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15667                 if (ret != -EDEADLK)
15668                         break;
15669
15670                 drm_modeset_backoff(&ctx);
15671         }
15672
15673         if (!ret)
15674                 ret = __intel_display_resume(dev, state, &ctx);
15675
15676         drm_modeset_drop_locks(&ctx);
15677         drm_modeset_acquire_fini(&ctx);
15678
15679         if (ret)
15680                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15681         if (state)
15682                 drm_atomic_state_put(state);
15683 }
15684
15685 void intel_modeset_gem_init(struct drm_device *dev)
15686 {
15687         struct drm_i915_private *dev_priv = to_i915(dev);
15688
15689         intel_init_gt_powersave(dev_priv);
15690
15691         intel_setup_overlay(dev_priv);
15692 }
15693
15694 int intel_connector_register(struct drm_connector *connector)
15695 {
15696         struct intel_connector *intel_connector = to_intel_connector(connector);
15697         int ret;
15698
15699         ret = intel_backlight_device_register(intel_connector);
15700         if (ret)
15701                 goto err;
15702
15703         return 0;
15704
15705 err:
15706         return ret;
15707 }
15708
15709 void intel_connector_unregister(struct drm_connector *connector)
15710 {
15711         struct intel_connector *intel_connector = to_intel_connector(connector);
15712
15713         intel_backlight_device_unregister(intel_connector);
15714         intel_panel_destroy_backlight(connector);
15715 }
15716
15717 void intel_modeset_cleanup(struct drm_device *dev)
15718 {
15719         struct drm_i915_private *dev_priv = to_i915(dev);
15720
15721         flush_work(&dev_priv->atomic_helper.free_work);
15722         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15723
15724         intel_disable_gt_powersave(dev_priv);
15725
15726         /*
15727          * Interrupts and polling as the first thing to avoid creating havoc.
15728          * Too much stuff here (turning of connectors, ...) would
15729          * experience fancy races otherwise.
15730          */
15731         intel_irq_uninstall(dev_priv);
15732
15733         /*
15734          * Due to the hpd irq storm handling the hotplug work can re-arm the
15735          * poll handlers. Hence disable polling after hpd handling is shut down.
15736          */
15737         drm_kms_helper_poll_fini(dev);
15738
15739         intel_unregister_dsm_handler();
15740
15741         intel_fbc_global_disable(dev_priv);
15742
15743         /* flush any delayed tasks or pending work */
15744         flush_scheduled_work();
15745
15746         drm_mode_config_cleanup(dev);
15747
15748         intel_cleanup_overlay(dev_priv);
15749
15750         intel_cleanup_gt_powersave(dev_priv);
15751
15752         intel_teardown_gmbus(dev_priv);
15753 }
15754
15755 void intel_connector_attach_encoder(struct intel_connector *connector,
15756                                     struct intel_encoder *encoder)
15757 {
15758         connector->encoder = encoder;
15759         drm_mode_connector_attach_encoder(&connector->base,
15760                                           &encoder->base);
15761 }
15762
15763 /*
15764  * set vga decode state - true == enable VGA decode
15765  */
15766 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15767 {
15768         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15769         u16 gmch_ctrl;
15770
15771         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15772                 DRM_ERROR("failed to read control word\n");
15773                 return -EIO;
15774         }
15775
15776         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15777                 return 0;
15778
15779         if (state)
15780                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15781         else
15782                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15783
15784         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15785                 DRM_ERROR("failed to write control word\n");
15786                 return -EIO;
15787         }
15788
15789         return 0;
15790 }
15791
15792 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15793
15794 struct intel_display_error_state {
15795
15796         u32 power_well_driver;
15797
15798         int num_transcoders;
15799
15800         struct intel_cursor_error_state {
15801                 u32 control;
15802                 u32 position;
15803                 u32 base;
15804                 u32 size;
15805         } cursor[I915_MAX_PIPES];
15806
15807         struct intel_pipe_error_state {
15808                 bool power_domain_on;
15809                 u32 source;
15810                 u32 stat;
15811         } pipe[I915_MAX_PIPES];
15812
15813         struct intel_plane_error_state {
15814                 u32 control;
15815                 u32 stride;
15816                 u32 size;
15817                 u32 pos;
15818                 u32 addr;
15819                 u32 surface;
15820                 u32 tile_offset;
15821         } plane[I915_MAX_PIPES];
15822
15823         struct intel_transcoder_error_state {
15824                 bool power_domain_on;
15825                 enum transcoder cpu_transcoder;
15826
15827                 u32 conf;
15828
15829                 u32 htotal;
15830                 u32 hblank;
15831                 u32 hsync;
15832                 u32 vtotal;
15833                 u32 vblank;
15834                 u32 vsync;
15835         } transcoder[4];
15836 };
15837
15838 struct intel_display_error_state *
15839 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15840 {
15841         struct intel_display_error_state *error;
15842         int transcoders[] = {
15843                 TRANSCODER_A,
15844                 TRANSCODER_B,
15845                 TRANSCODER_C,
15846                 TRANSCODER_EDP,
15847         };
15848         int i;
15849
15850         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15851                 return NULL;
15852
15853         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15854         if (error == NULL)
15855                 return NULL;
15856
15857         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15858                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15859
15860         for_each_pipe(dev_priv, i) {
15861                 error->pipe[i].power_domain_on =
15862                         __intel_display_power_is_enabled(dev_priv,
15863                                                          POWER_DOMAIN_PIPE(i));
15864                 if (!error->pipe[i].power_domain_on)
15865                         continue;
15866
15867                 error->cursor[i].control = I915_READ(CURCNTR(i));
15868                 error->cursor[i].position = I915_READ(CURPOS(i));
15869                 error->cursor[i].base = I915_READ(CURBASE(i));
15870
15871                 error->plane[i].control = I915_READ(DSPCNTR(i));
15872                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15873                 if (INTEL_GEN(dev_priv) <= 3) {
15874                         error->plane[i].size = I915_READ(DSPSIZE(i));
15875                         error->plane[i].pos = I915_READ(DSPPOS(i));
15876                 }
15877                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15878                         error->plane[i].addr = I915_READ(DSPADDR(i));
15879                 if (INTEL_GEN(dev_priv) >= 4) {
15880                         error->plane[i].surface = I915_READ(DSPSURF(i));
15881                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15882                 }
15883
15884                 error->pipe[i].source = I915_READ(PIPESRC(i));
15885
15886                 if (HAS_GMCH_DISPLAY(dev_priv))
15887                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15888         }
15889
15890         /* Note: this does not include DSI transcoders. */
15891         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15892         if (HAS_DDI(dev_priv))
15893                 error->num_transcoders++; /* Account for eDP. */
15894
15895         for (i = 0; i < error->num_transcoders; i++) {
15896                 enum transcoder cpu_transcoder = transcoders[i];
15897
15898                 error->transcoder[i].power_domain_on =
15899                         __intel_display_power_is_enabled(dev_priv,
15900                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15901                 if (!error->transcoder[i].power_domain_on)
15902                         continue;
15903
15904                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15905
15906                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15907                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15908                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15909                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15910                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15911                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15912                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15913         }
15914
15915         return error;
15916 }
15917
15918 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15919
15920 void
15921 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15922                                 struct intel_display_error_state *error)
15923 {
15924         struct drm_i915_private *dev_priv = m->i915;
15925         int i;
15926
15927         if (!error)
15928                 return;
15929
15930         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15931         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15932                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15933                            error->power_well_driver);
15934         for_each_pipe(dev_priv, i) {
15935                 err_printf(m, "Pipe [%d]:\n", i);
15936                 err_printf(m, "  Power: %s\n",
15937                            onoff(error->pipe[i].power_domain_on));
15938                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15939                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15940
15941                 err_printf(m, "Plane [%d]:\n", i);
15942                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15943                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15944                 if (INTEL_GEN(dev_priv) <= 3) {
15945                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15946                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15947                 }
15948                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15949                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15950                 if (INTEL_GEN(dev_priv) >= 4) {
15951                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15952                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15953                 }
15954
15955                 err_printf(m, "Cursor [%d]:\n", i);
15956                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15957                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15958                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15959         }
15960
15961         for (i = 0; i < error->num_transcoders; i++) {
15962                 err_printf(m, "CPU transcoder: %s\n",
15963                            transcoder_name(error->transcoder[i].cpu_transcoder));
15964                 err_printf(m, "  Power: %s\n",
15965                            onoff(error->transcoder[i].power_domain_on));
15966                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15967                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15968                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15969                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15970                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15971                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15972                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15973         }
15974 }
15975
15976 #endif