]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/intel_display.c
drm/i915: Fix deadlock witha the pipe A quirk during resume
[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
1554         assert_pipe_disabled(dev_priv, crtc->pipe);
1555
1556         /* PLL is protected by panel, make sure we can write it */
1557         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1558                 assert_panel_unlocked(dev_priv, crtc->pipe);
1559
1560         /* Enable DVO 2x clock on both PLLs if necessary */
1561         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1562                 /*
1563                  * It appears to be important that we don't enable this
1564                  * for the current pipe before otherwise configuring the
1565                  * PLL. No idea how this should be handled if multiple
1566                  * DVO outputs are enabled simultaneosly.
1567                  */
1568                 dpll |= DPLL_DVO_2X_MODE;
1569                 I915_WRITE(DPLL(!crtc->pipe),
1570                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1571         }
1572
1573         /*
1574          * Apparently we need to have VGA mode enabled prior to changing
1575          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1576          * dividers, even though the register value does change.
1577          */
1578         I915_WRITE(reg, 0);
1579
1580         I915_WRITE(reg, dpll);
1581
1582         /* Wait for the clocks to stabilize. */
1583         POSTING_READ(reg);
1584         udelay(150);
1585
1586         if (INTEL_GEN(dev_priv) >= 4) {
1587                 I915_WRITE(DPLL_MD(crtc->pipe),
1588                            crtc->config->dpll_hw_state.dpll_md);
1589         } else {
1590                 /* The pixel multiplier can only be updated once the
1591                  * DPLL is enabled and the clocks are stable.
1592                  *
1593                  * So write it again.
1594                  */
1595                 I915_WRITE(reg, dpll);
1596         }
1597
1598         /* We do this three times for luck */
1599         I915_WRITE(reg, dpll);
1600         POSTING_READ(reg);
1601         udelay(150); /* wait for warmup */
1602         I915_WRITE(reg, dpll);
1603         POSTING_READ(reg);
1604         udelay(150); /* wait for warmup */
1605         I915_WRITE(reg, dpll);
1606         POSTING_READ(reg);
1607         udelay(150); /* wait for warmup */
1608 }
1609
1610 /**
1611  * i9xx_disable_pll - disable a PLL
1612  * @dev_priv: i915 private structure
1613  * @pipe: pipe PLL to disable
1614  *
1615  * Disable the PLL for @pipe, making sure the pipe is off first.
1616  *
1617  * Note!  This is for pre-ILK only.
1618  */
1619 static void i9xx_disable_pll(struct intel_crtc *crtc)
1620 {
1621         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1622         enum pipe pipe = crtc->pipe;
1623
1624         /* Disable DVO 2x clock on both PLLs if necessary */
1625         if (IS_I830(dev_priv) &&
1626             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1627             !intel_num_dvo_pipes(dev_priv)) {
1628                 I915_WRITE(DPLL(PIPE_B),
1629                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1630                 I915_WRITE(DPLL(PIPE_A),
1631                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1632         }
1633
1634         /* Don't disable pipe or pipe PLLs if needed */
1635         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1636             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1637                 return;
1638
1639         /* Make sure the pipe isn't still relying on us */
1640         assert_pipe_disabled(dev_priv, pipe);
1641
1642         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1643         POSTING_READ(DPLL(pipe));
1644 }
1645
1646 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1647 {
1648         u32 val;
1649
1650         /* Make sure the pipe isn't still relying on us */
1651         assert_pipe_disabled(dev_priv, pipe);
1652
1653         val = DPLL_INTEGRATED_REF_CLK_VLV |
1654                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1655         if (pipe != PIPE_A)
1656                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1657
1658         I915_WRITE(DPLL(pipe), val);
1659         POSTING_READ(DPLL(pipe));
1660 }
1661
1662 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1663 {
1664         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1665         u32 val;
1666
1667         /* Make sure the pipe isn't still relying on us */
1668         assert_pipe_disabled(dev_priv, pipe);
1669
1670         val = DPLL_SSC_REF_CLK_CHV |
1671                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1672         if (pipe != PIPE_A)
1673                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1674
1675         I915_WRITE(DPLL(pipe), val);
1676         POSTING_READ(DPLL(pipe));
1677
1678         mutex_lock(&dev_priv->sb_lock);
1679
1680         /* Disable 10bit clock to display controller */
1681         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1682         val &= ~DPIO_DCLKP_EN;
1683         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1684
1685         mutex_unlock(&dev_priv->sb_lock);
1686 }
1687
1688 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1689                          struct intel_digital_port *dport,
1690                          unsigned int expected_mask)
1691 {
1692         u32 port_mask;
1693         i915_reg_t dpll_reg;
1694
1695         switch (dport->port) {
1696         case PORT_B:
1697                 port_mask = DPLL_PORTB_READY_MASK;
1698                 dpll_reg = DPLL(0);
1699                 break;
1700         case PORT_C:
1701                 port_mask = DPLL_PORTC_READY_MASK;
1702                 dpll_reg = DPLL(0);
1703                 expected_mask <<= 4;
1704                 break;
1705         case PORT_D:
1706                 port_mask = DPLL_PORTD_READY_MASK;
1707                 dpll_reg = DPIO_PHY_STATUS;
1708                 break;
1709         default:
1710                 BUG();
1711         }
1712
1713         if (intel_wait_for_register(dev_priv,
1714                                     dpll_reg, port_mask, expected_mask,
1715                                     1000))
1716                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1717                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1718 }
1719
1720 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1721                                            enum pipe pipe)
1722 {
1723         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1724                                                                 pipe);
1725         i915_reg_t reg;
1726         uint32_t val, pipeconf_val;
1727
1728         /* Make sure PCH DPLL is enabled */
1729         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1730
1731         /* FDI must be feeding us bits for PCH ports */
1732         assert_fdi_tx_enabled(dev_priv, pipe);
1733         assert_fdi_rx_enabled(dev_priv, pipe);
1734
1735         if (HAS_PCH_CPT(dev_priv)) {
1736                 /* Workaround: Set the timing override bit before enabling the
1737                  * pch transcoder. */
1738                 reg = TRANS_CHICKEN2(pipe);
1739                 val = I915_READ(reg);
1740                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1741                 I915_WRITE(reg, val);
1742         }
1743
1744         reg = PCH_TRANSCONF(pipe);
1745         val = I915_READ(reg);
1746         pipeconf_val = I915_READ(PIPECONF(pipe));
1747
1748         if (HAS_PCH_IBX(dev_priv)) {
1749                 /*
1750                  * Make the BPC in transcoder be consistent with
1751                  * that in pipeconf reg. For HDMI we must use 8bpc
1752                  * here for both 8bpc and 12bpc.
1753                  */
1754                 val &= ~PIPECONF_BPC_MASK;
1755                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1756                         val |= PIPECONF_8BPC;
1757                 else
1758                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1759         }
1760
1761         val &= ~TRANS_INTERLACE_MASK;
1762         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1763                 if (HAS_PCH_IBX(dev_priv) &&
1764                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1765                         val |= TRANS_LEGACY_INTERLACED_ILK;
1766                 else
1767                         val |= TRANS_INTERLACED;
1768         else
1769                 val |= TRANS_PROGRESSIVE;
1770
1771         I915_WRITE(reg, val | TRANS_ENABLE);
1772         if (intel_wait_for_register(dev_priv,
1773                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1774                                     100))
1775                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1776 }
1777
1778 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1779                                       enum transcoder cpu_transcoder)
1780 {
1781         u32 val, pipeconf_val;
1782
1783         /* FDI must be feeding us bits for PCH ports */
1784         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1785         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1786
1787         /* Workaround: set timing override bit. */
1788         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1789         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1790         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1791
1792         val = TRANS_ENABLE;
1793         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1794
1795         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1796             PIPECONF_INTERLACED_ILK)
1797                 val |= TRANS_INTERLACED;
1798         else
1799                 val |= TRANS_PROGRESSIVE;
1800
1801         I915_WRITE(LPT_TRANSCONF, val);
1802         if (intel_wait_for_register(dev_priv,
1803                                     LPT_TRANSCONF,
1804                                     TRANS_STATE_ENABLE,
1805                                     TRANS_STATE_ENABLE,
1806                                     100))
1807                 DRM_ERROR("Failed to enable PCH transcoder\n");
1808 }
1809
1810 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1811                                             enum pipe pipe)
1812 {
1813         i915_reg_t reg;
1814         uint32_t val;
1815
1816         /* FDI relies on the transcoder */
1817         assert_fdi_tx_disabled(dev_priv, pipe);
1818         assert_fdi_rx_disabled(dev_priv, pipe);
1819
1820         /* Ports must be off as well */
1821         assert_pch_ports_disabled(dev_priv, pipe);
1822
1823         reg = PCH_TRANSCONF(pipe);
1824         val = I915_READ(reg);
1825         val &= ~TRANS_ENABLE;
1826         I915_WRITE(reg, val);
1827         /* wait for PCH transcoder off, transcoder state */
1828         if (intel_wait_for_register(dev_priv,
1829                                     reg, TRANS_STATE_ENABLE, 0,
1830                                     50))
1831                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1832
1833         if (HAS_PCH_CPT(dev_priv)) {
1834                 /* Workaround: Clear the timing override chicken bit again. */
1835                 reg = TRANS_CHICKEN2(pipe);
1836                 val = I915_READ(reg);
1837                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1838                 I915_WRITE(reg, val);
1839         }
1840 }
1841
1842 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1843 {
1844         u32 val;
1845
1846         val = I915_READ(LPT_TRANSCONF);
1847         val &= ~TRANS_ENABLE;
1848         I915_WRITE(LPT_TRANSCONF, val);
1849         /* wait for PCH transcoder off, transcoder state */
1850         if (intel_wait_for_register(dev_priv,
1851                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1852                                     50))
1853                 DRM_ERROR("Failed to disable PCH transcoder\n");
1854
1855         /* Workaround: clear timing override bit. */
1856         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1857         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1858         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1859 }
1860
1861 enum transcoder intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1862 {
1863         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1864
1865         WARN_ON(!crtc->config->has_pch_encoder);
1866
1867         if (HAS_PCH_LPT(dev_priv))
1868                 return TRANSCODER_A;
1869         else
1870                 return (enum transcoder) crtc->pipe;
1871 }
1872
1873 /**
1874  * intel_enable_pipe - enable a pipe, asserting requirements
1875  * @crtc: crtc responsible for the pipe
1876  *
1877  * Enable @crtc's pipe, making sure that various hardware specific requirements
1878  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1879  */
1880 static void intel_enable_pipe(struct intel_crtc *crtc)
1881 {
1882         struct drm_device *dev = crtc->base.dev;
1883         struct drm_i915_private *dev_priv = to_i915(dev);
1884         enum pipe pipe = crtc->pipe;
1885         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1886         i915_reg_t reg;
1887         u32 val;
1888
1889         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1890
1891         assert_planes_disabled(dev_priv, pipe);
1892         assert_cursor_disabled(dev_priv, pipe);
1893         assert_sprites_disabled(dev_priv, pipe);
1894
1895         /*
1896          * A pipe without a PLL won't actually be able to drive bits from
1897          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1898          * need the check.
1899          */
1900         if (HAS_GMCH_DISPLAY(dev_priv)) {
1901                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1902                         assert_dsi_pll_enabled(dev_priv);
1903                 else
1904                         assert_pll_enabled(dev_priv, pipe);
1905         } else {
1906                 if (crtc->config->has_pch_encoder) {
1907                         /* if driving the PCH, we need FDI enabled */
1908                         assert_fdi_rx_pll_enabled(dev_priv,
1909                                                   (enum pipe) intel_crtc_pch_transcoder(crtc));
1910                         assert_fdi_tx_pll_enabled(dev_priv,
1911                                                   (enum pipe) cpu_transcoder);
1912                 }
1913                 /* FIXME: assert CPU port conditions for SNB+ */
1914         }
1915
1916         reg = PIPECONF(cpu_transcoder);
1917         val = I915_READ(reg);
1918         if (val & PIPECONF_ENABLE) {
1919                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1920                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1921                 return;
1922         }
1923
1924         I915_WRITE(reg, val | PIPECONF_ENABLE);
1925         POSTING_READ(reg);
1926
1927         /*
1928          * Until the pipe starts DSL will read as 0, which would cause
1929          * an apparent vblank timestamp jump, which messes up also the
1930          * frame count when it's derived from the timestamps. So let's
1931          * wait for the pipe to start properly before we call
1932          * drm_crtc_vblank_on()
1933          */
1934         if (dev->max_vblank_count == 0 &&
1935             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1936                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1937 }
1938
1939 /**
1940  * intel_disable_pipe - disable a pipe, asserting requirements
1941  * @crtc: crtc whose pipes is to be disabled
1942  *
1943  * Disable the pipe of @crtc, making sure that various hardware
1944  * specific requirements are met, if applicable, e.g. plane
1945  * disabled, panel fitter off, etc.
1946  *
1947  * Will wait until the pipe has shut down before returning.
1948  */
1949 static void intel_disable_pipe(struct intel_crtc *crtc)
1950 {
1951         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1952         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1953         enum pipe pipe = crtc->pipe;
1954         i915_reg_t reg;
1955         u32 val;
1956
1957         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1958
1959         /*
1960          * Make sure planes won't keep trying to pump pixels to us,
1961          * or we might hang the display.
1962          */
1963         assert_planes_disabled(dev_priv, pipe);
1964         assert_cursor_disabled(dev_priv, pipe);
1965         assert_sprites_disabled(dev_priv, pipe);
1966
1967         reg = PIPECONF(cpu_transcoder);
1968         val = I915_READ(reg);
1969         if ((val & PIPECONF_ENABLE) == 0)
1970                 return;
1971
1972         /*
1973          * Double wide has implications for planes
1974          * so best keep it disabled when not needed.
1975          */
1976         if (crtc->config->double_wide)
1977                 val &= ~PIPECONF_DOUBLE_WIDE;
1978
1979         /* Don't disable pipe or pipe PLLs if needed */
1980         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
1981             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1982                 val &= ~PIPECONF_ENABLE;
1983
1984         I915_WRITE(reg, val);
1985         if ((val & PIPECONF_ENABLE) == 0)
1986                 intel_wait_for_pipe_off(crtc);
1987 }
1988
1989 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1990 {
1991         return IS_GEN2(dev_priv) ? 2048 : 4096;
1992 }
1993
1994 static unsigned int
1995 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1996 {
1997         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1998         unsigned int cpp = fb->format->cpp[plane];
1999
2000         switch (fb->modifier) {
2001         case DRM_FORMAT_MOD_LINEAR:
2002                 return cpp;
2003         case I915_FORMAT_MOD_X_TILED:
2004                 if (IS_GEN2(dev_priv))
2005                         return 128;
2006                 else
2007                         return 512;
2008         case I915_FORMAT_MOD_Y_TILED:
2009                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2010                         return 128;
2011                 else
2012                         return 512;
2013         case I915_FORMAT_MOD_Yf_TILED:
2014                 switch (cpp) {
2015                 case 1:
2016                         return 64;
2017                 case 2:
2018                 case 4:
2019                         return 128;
2020                 case 8:
2021                 case 16:
2022                         return 256;
2023                 default:
2024                         MISSING_CASE(cpp);
2025                         return cpp;
2026                 }
2027                 break;
2028         default:
2029                 MISSING_CASE(fb->modifier);
2030                 return cpp;
2031         }
2032 }
2033
2034 static unsigned int
2035 intel_tile_height(const struct drm_framebuffer *fb, int plane)
2036 {
2037         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
2038                 return 1;
2039         else
2040                 return intel_tile_size(to_i915(fb->dev)) /
2041                         intel_tile_width_bytes(fb, plane);
2042 }
2043
2044 /* Return the tile dimensions in pixel units */
2045 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
2046                             unsigned int *tile_width,
2047                             unsigned int *tile_height)
2048 {
2049         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
2050         unsigned int cpp = fb->format->cpp[plane];
2051
2052         *tile_width = tile_width_bytes / cpp;
2053         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
2054 }
2055
2056 unsigned int
2057 intel_fb_align_height(const struct drm_framebuffer *fb,
2058                       int plane, unsigned int height)
2059 {
2060         unsigned int tile_height = intel_tile_height(fb, plane);
2061
2062         return ALIGN(height, tile_height);
2063 }
2064
2065 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2066 {
2067         unsigned int size = 0;
2068         int i;
2069
2070         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2071                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2072
2073         return size;
2074 }
2075
2076 static void
2077 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2078                         const struct drm_framebuffer *fb,
2079                         unsigned int rotation)
2080 {
2081         view->type = I915_GGTT_VIEW_NORMAL;
2082         if (drm_rotation_90_or_270(rotation)) {
2083                 view->type = I915_GGTT_VIEW_ROTATED;
2084                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2085         }
2086 }
2087
2088 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2089 {
2090         if (IS_I830(dev_priv))
2091                 return 16 * 1024;
2092         else if (IS_I85X(dev_priv))
2093                 return 256;
2094         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2095                 return 32;
2096         else
2097                 return 4 * 1024;
2098 }
2099
2100 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2101 {
2102         if (INTEL_INFO(dev_priv)->gen >= 9)
2103                 return 256 * 1024;
2104         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2105                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2106                 return 128 * 1024;
2107         else if (INTEL_INFO(dev_priv)->gen >= 4)
2108                 return 4 * 1024;
2109         else
2110                 return 0;
2111 }
2112
2113 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2114                                          int plane)
2115 {
2116         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2117
2118         /* AUX_DIST needs only 4K alignment */
2119         if (fb->format->format == DRM_FORMAT_NV12 && plane == 1)
2120                 return 4096;
2121
2122         switch (fb->modifier) {
2123         case DRM_FORMAT_MOD_LINEAR:
2124                 return intel_linear_alignment(dev_priv);
2125         case I915_FORMAT_MOD_X_TILED:
2126                 if (INTEL_GEN(dev_priv) >= 9)
2127                         return 256 * 1024;
2128                 return 0;
2129         case I915_FORMAT_MOD_Y_TILED:
2130         case I915_FORMAT_MOD_Yf_TILED:
2131                 return 1 * 1024 * 1024;
2132         default:
2133                 MISSING_CASE(fb->modifier);
2134                 return 0;
2135         }
2136 }
2137
2138 struct i915_vma *
2139 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2140 {
2141         struct drm_device *dev = fb->dev;
2142         struct drm_i915_private *dev_priv = to_i915(dev);
2143         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2144         struct i915_ggtt_view view;
2145         struct i915_vma *vma;
2146         u32 alignment;
2147
2148         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2149
2150         alignment = intel_surf_alignment(fb, 0);
2151
2152         intel_fill_fb_ggtt_view(&view, fb, rotation);
2153
2154         /* Note that the w/a also requires 64 PTE of padding following the
2155          * bo. We currently fill all unused PTE with the shadow page and so
2156          * we should always have valid PTE following the scanout preventing
2157          * the VT-d warning.
2158          */
2159         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2160                 alignment = 256 * 1024;
2161
2162         /*
2163          * Global gtt pte registers are special registers which actually forward
2164          * writes to a chunk of system memory. Which means that there is no risk
2165          * that the register values disappear as soon as we call
2166          * intel_runtime_pm_put(), so it is correct to wrap only the
2167          * pin/unpin/fence and not more.
2168          */
2169         intel_runtime_pm_get(dev_priv);
2170
2171         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2172         if (IS_ERR(vma))
2173                 goto err;
2174
2175         if (i915_vma_is_map_and_fenceable(vma)) {
2176                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2177                  * fence, whereas 965+ only requires a fence if using
2178                  * framebuffer compression.  For simplicity, we always, when
2179                  * possible, install a fence as the cost is not that onerous.
2180                  *
2181                  * If we fail to fence the tiled scanout, then either the
2182                  * modeset will reject the change (which is highly unlikely as
2183                  * the affected systems, all but one, do not have unmappable
2184                  * space) or we will not be able to enable full powersaving
2185                  * techniques (also likely not to apply due to various limits
2186                  * FBC and the like impose on the size of the buffer, which
2187                  * presumably we violated anyway with this unmappable buffer).
2188                  * Anyway, it is presumably better to stumble onwards with
2189                  * something and try to run the system in a "less than optimal"
2190                  * mode that matches the user configuration.
2191                  */
2192                 if (i915_vma_get_fence(vma) == 0)
2193                         i915_vma_pin_fence(vma);
2194         }
2195
2196         i915_vma_get(vma);
2197 err:
2198         intel_runtime_pm_put(dev_priv);
2199         return vma;
2200 }
2201
2202 void intel_unpin_fb_vma(struct i915_vma *vma)
2203 {
2204         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2205
2206         i915_vma_unpin_fence(vma);
2207         i915_gem_object_unpin_from_display_plane(vma);
2208         i915_vma_put(vma);
2209 }
2210
2211 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2212                           unsigned int rotation)
2213 {
2214         if (drm_rotation_90_or_270(rotation))
2215                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2216         else
2217                 return fb->pitches[plane];
2218 }
2219
2220 /*
2221  * Convert the x/y offsets into a linear offset.
2222  * Only valid with 0/180 degree rotation, which is fine since linear
2223  * offset is only used with linear buffers on pre-hsw and tiled buffers
2224  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2225  */
2226 u32 intel_fb_xy_to_linear(int x, int y,
2227                           const struct intel_plane_state *state,
2228                           int plane)
2229 {
2230         const struct drm_framebuffer *fb = state->base.fb;
2231         unsigned int cpp = fb->format->cpp[plane];
2232         unsigned int pitch = fb->pitches[plane];
2233
2234         return y * pitch + x * cpp;
2235 }
2236
2237 /*
2238  * Add the x/y offsets derived from fb->offsets[] to the user
2239  * specified plane src x/y offsets. The resulting x/y offsets
2240  * specify the start of scanout from the beginning of the gtt mapping.
2241  */
2242 void intel_add_fb_offsets(int *x, int *y,
2243                           const struct intel_plane_state *state,
2244                           int plane)
2245
2246 {
2247         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2248         unsigned int rotation = state->base.rotation;
2249
2250         if (drm_rotation_90_or_270(rotation)) {
2251                 *x += intel_fb->rotated[plane].x;
2252                 *y += intel_fb->rotated[plane].y;
2253         } else {
2254                 *x += intel_fb->normal[plane].x;
2255                 *y += intel_fb->normal[plane].y;
2256         }
2257 }
2258
2259 /*
2260  * Input tile dimensions and pitch must already be
2261  * rotated to match x and y, and in pixel units.
2262  */
2263 static u32 _intel_adjust_tile_offset(int *x, int *y,
2264                                      unsigned int tile_width,
2265                                      unsigned int tile_height,
2266                                      unsigned int tile_size,
2267                                      unsigned int pitch_tiles,
2268                                      u32 old_offset,
2269                                      u32 new_offset)
2270 {
2271         unsigned int pitch_pixels = pitch_tiles * tile_width;
2272         unsigned int tiles;
2273
2274         WARN_ON(old_offset & (tile_size - 1));
2275         WARN_ON(new_offset & (tile_size - 1));
2276         WARN_ON(new_offset > old_offset);
2277
2278         tiles = (old_offset - new_offset) / tile_size;
2279
2280         *y += tiles / pitch_tiles * tile_height;
2281         *x += tiles % pitch_tiles * tile_width;
2282
2283         /* minimize x in case it got needlessly big */
2284         *y += *x / pitch_pixels * tile_height;
2285         *x %= pitch_pixels;
2286
2287         return new_offset;
2288 }
2289
2290 /*
2291  * Adjust the tile offset by moving the difference into
2292  * the x/y offsets.
2293  */
2294 static u32 intel_adjust_tile_offset(int *x, int *y,
2295                                     const struct intel_plane_state *state, int plane,
2296                                     u32 old_offset, u32 new_offset)
2297 {
2298         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2299         const struct drm_framebuffer *fb = state->base.fb;
2300         unsigned int cpp = fb->format->cpp[plane];
2301         unsigned int rotation = state->base.rotation;
2302         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2303
2304         WARN_ON(new_offset > old_offset);
2305
2306         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2307                 unsigned int tile_size, tile_width, tile_height;
2308                 unsigned int pitch_tiles;
2309
2310                 tile_size = intel_tile_size(dev_priv);
2311                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2312
2313                 if (drm_rotation_90_or_270(rotation)) {
2314                         pitch_tiles = pitch / tile_height;
2315                         swap(tile_width, tile_height);
2316                 } else {
2317                         pitch_tiles = pitch / (tile_width * cpp);
2318                 }
2319
2320                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2321                                           tile_size, pitch_tiles,
2322                                           old_offset, new_offset);
2323         } else {
2324                 old_offset += *y * pitch + *x * cpp;
2325
2326                 *y = (old_offset - new_offset) / pitch;
2327                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2328         }
2329
2330         return new_offset;
2331 }
2332
2333 /*
2334  * Computes the linear offset to the base tile and adjusts
2335  * x, y. bytes per pixel is assumed to be a power-of-two.
2336  *
2337  * In the 90/270 rotated case, x and y are assumed
2338  * to be already rotated to match the rotated GTT view, and
2339  * pitch is the tile_height aligned framebuffer height.
2340  *
2341  * This function is used when computing the derived information
2342  * under intel_framebuffer, so using any of that information
2343  * here is not allowed. Anything under drm_framebuffer can be
2344  * used. This is why the user has to pass in the pitch since it
2345  * is specified in the rotated orientation.
2346  */
2347 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2348                                       int *x, int *y,
2349                                       const struct drm_framebuffer *fb, int plane,
2350                                       unsigned int pitch,
2351                                       unsigned int rotation,
2352                                       u32 alignment)
2353 {
2354         uint64_t fb_modifier = fb->modifier;
2355         unsigned int cpp = fb->format->cpp[plane];
2356         u32 offset, offset_aligned;
2357
2358         if (alignment)
2359                 alignment--;
2360
2361         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2362                 unsigned int tile_size, tile_width, tile_height;
2363                 unsigned int tile_rows, tiles, pitch_tiles;
2364
2365                 tile_size = intel_tile_size(dev_priv);
2366                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2367
2368                 if (drm_rotation_90_or_270(rotation)) {
2369                         pitch_tiles = pitch / tile_height;
2370                         swap(tile_width, tile_height);
2371                 } else {
2372                         pitch_tiles = pitch / (tile_width * cpp);
2373                 }
2374
2375                 tile_rows = *y / tile_height;
2376                 *y %= tile_height;
2377
2378                 tiles = *x / tile_width;
2379                 *x %= tile_width;
2380
2381                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2382                 offset_aligned = offset & ~alignment;
2383
2384                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2385                                           tile_size, pitch_tiles,
2386                                           offset, offset_aligned);
2387         } else {
2388                 offset = *y * pitch + *x * cpp;
2389                 offset_aligned = offset & ~alignment;
2390
2391                 *y = (offset & alignment) / pitch;
2392                 *x = ((offset & alignment) - *y * pitch) / cpp;
2393         }
2394
2395         return offset_aligned;
2396 }
2397
2398 u32 intel_compute_tile_offset(int *x, int *y,
2399                               const struct intel_plane_state *state,
2400                               int plane)
2401 {
2402         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2403         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2404         const struct drm_framebuffer *fb = state->base.fb;
2405         unsigned int rotation = state->base.rotation;
2406         int pitch = intel_fb_pitch(fb, plane, rotation);
2407         u32 alignment;
2408
2409         if (intel_plane->id == PLANE_CURSOR)
2410                 alignment = intel_cursor_alignment(dev_priv);
2411         else
2412                 alignment = intel_surf_alignment(fb, plane);
2413
2414         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2415                                           rotation, alignment);
2416 }
2417
2418 /* Convert the fb->offset[] linear offset into x/y offsets */
2419 static void intel_fb_offset_to_xy(int *x, int *y,
2420                                   const struct drm_framebuffer *fb, int plane)
2421 {
2422         unsigned int cpp = fb->format->cpp[plane];
2423         unsigned int pitch = fb->pitches[plane];
2424         u32 linear_offset = fb->offsets[plane];
2425
2426         *y = linear_offset / pitch;
2427         *x = linear_offset % pitch / cpp;
2428 }
2429
2430 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2431 {
2432         switch (fb_modifier) {
2433         case I915_FORMAT_MOD_X_TILED:
2434                 return I915_TILING_X;
2435         case I915_FORMAT_MOD_Y_TILED:
2436                 return I915_TILING_Y;
2437         default:
2438                 return I915_TILING_NONE;
2439         }
2440 }
2441
2442 static int
2443 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2444                    struct drm_framebuffer *fb)
2445 {
2446         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2447         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2448         u32 gtt_offset_rotated = 0;
2449         unsigned int max_size = 0;
2450         int i, num_planes = fb->format->num_planes;
2451         unsigned int tile_size = intel_tile_size(dev_priv);
2452
2453         for (i = 0; i < num_planes; i++) {
2454                 unsigned int width, height;
2455                 unsigned int cpp, size;
2456                 u32 offset;
2457                 int x, y;
2458
2459                 cpp = fb->format->cpp[i];
2460                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2461                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2462
2463                 intel_fb_offset_to_xy(&x, &y, fb, i);
2464
2465                 /*
2466                  * The fence (if used) is aligned to the start of the object
2467                  * so having the framebuffer wrap around across the edge of the
2468                  * fenced region doesn't really work. We have no API to configure
2469                  * the fence start offset within the object (nor could we probably
2470                  * on gen2/3). So it's just easier if we just require that the
2471                  * fb layout agrees with the fence layout. We already check that the
2472                  * fb stride matches the fence stride elsewhere.
2473                  */
2474                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2475                     (x + width) * cpp > fb->pitches[i]) {
2476                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2477                                       i, fb->offsets[i]);
2478                         return -EINVAL;
2479                 }
2480
2481                 /*
2482                  * First pixel of the framebuffer from
2483                  * the start of the normal gtt mapping.
2484                  */
2485                 intel_fb->normal[i].x = x;
2486                 intel_fb->normal[i].y = y;
2487
2488                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2489                                                     fb, i, fb->pitches[i],
2490                                                     DRM_MODE_ROTATE_0, tile_size);
2491                 offset /= tile_size;
2492
2493                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2494                         unsigned int tile_width, tile_height;
2495                         unsigned int pitch_tiles;
2496                         struct drm_rect r;
2497
2498                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2499
2500                         rot_info->plane[i].offset = offset;
2501                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2502                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2503                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2504
2505                         intel_fb->rotated[i].pitch =
2506                                 rot_info->plane[i].height * tile_height;
2507
2508                         /* how many tiles does this plane need */
2509                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2510                         /*
2511                          * If the plane isn't horizontally tile aligned,
2512                          * we need one more tile.
2513                          */
2514                         if (x != 0)
2515                                 size++;
2516
2517                         /* rotate the x/y offsets to match the GTT view */
2518                         r.x1 = x;
2519                         r.y1 = y;
2520                         r.x2 = x + width;
2521                         r.y2 = y + height;
2522                         drm_rect_rotate(&r,
2523                                         rot_info->plane[i].width * tile_width,
2524                                         rot_info->plane[i].height * tile_height,
2525                                         DRM_MODE_ROTATE_270);
2526                         x = r.x1;
2527                         y = r.y1;
2528
2529                         /* rotate the tile dimensions to match the GTT view */
2530                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2531                         swap(tile_width, tile_height);
2532
2533                         /*
2534                          * We only keep the x/y offsets, so push all of the
2535                          * gtt offset into the x/y offsets.
2536                          */
2537                         _intel_adjust_tile_offset(&x, &y,
2538                                                   tile_width, tile_height,
2539                                                   tile_size, pitch_tiles,
2540                                                   gtt_offset_rotated * tile_size, 0);
2541
2542                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2543
2544                         /*
2545                          * First pixel of the framebuffer from
2546                          * the start of the rotated gtt mapping.
2547                          */
2548                         intel_fb->rotated[i].x = x;
2549                         intel_fb->rotated[i].y = y;
2550                 } else {
2551                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2552                                             x * cpp, tile_size);
2553                 }
2554
2555                 /* how many tiles in total needed in the bo */
2556                 max_size = max(max_size, offset + size);
2557         }
2558
2559         if (max_size * tile_size > intel_fb->obj->base.size) {
2560                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2561                               max_size * tile_size, intel_fb->obj->base.size);
2562                 return -EINVAL;
2563         }
2564
2565         return 0;
2566 }
2567
2568 static int i9xx_format_to_fourcc(int format)
2569 {
2570         switch (format) {
2571         case DISPPLANE_8BPP:
2572                 return DRM_FORMAT_C8;
2573         case DISPPLANE_BGRX555:
2574                 return DRM_FORMAT_XRGB1555;
2575         case DISPPLANE_BGRX565:
2576                 return DRM_FORMAT_RGB565;
2577         default:
2578         case DISPPLANE_BGRX888:
2579                 return DRM_FORMAT_XRGB8888;
2580         case DISPPLANE_RGBX888:
2581                 return DRM_FORMAT_XBGR8888;
2582         case DISPPLANE_BGRX101010:
2583                 return DRM_FORMAT_XRGB2101010;
2584         case DISPPLANE_RGBX101010:
2585                 return DRM_FORMAT_XBGR2101010;
2586         }
2587 }
2588
2589 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2590 {
2591         switch (format) {
2592         case PLANE_CTL_FORMAT_RGB_565:
2593                 return DRM_FORMAT_RGB565;
2594         default:
2595         case PLANE_CTL_FORMAT_XRGB_8888:
2596                 if (rgb_order) {
2597                         if (alpha)
2598                                 return DRM_FORMAT_ABGR8888;
2599                         else
2600                                 return DRM_FORMAT_XBGR8888;
2601                 } else {
2602                         if (alpha)
2603                                 return DRM_FORMAT_ARGB8888;
2604                         else
2605                                 return DRM_FORMAT_XRGB8888;
2606                 }
2607         case PLANE_CTL_FORMAT_XRGB_2101010:
2608                 if (rgb_order)
2609                         return DRM_FORMAT_XBGR2101010;
2610                 else
2611                         return DRM_FORMAT_XRGB2101010;
2612         }
2613 }
2614
2615 static bool
2616 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2617                               struct intel_initial_plane_config *plane_config)
2618 {
2619         struct drm_device *dev = crtc->base.dev;
2620         struct drm_i915_private *dev_priv = to_i915(dev);
2621         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2622         struct drm_i915_gem_object *obj = NULL;
2623         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2624         struct drm_framebuffer *fb = &plane_config->fb->base;
2625         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2626         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2627                                     PAGE_SIZE);
2628
2629         size_aligned -= base_aligned;
2630
2631         if (plane_config->size == 0)
2632                 return false;
2633
2634         /* If the FB is too big, just don't use it since fbdev is not very
2635          * important and we should probably use that space with FBC or other
2636          * features. */
2637         if (size_aligned * 2 > ggtt->stolen_usable_size)
2638                 return false;
2639
2640         mutex_lock(&dev->struct_mutex);
2641         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2642                                                              base_aligned,
2643                                                              base_aligned,
2644                                                              size_aligned);
2645         mutex_unlock(&dev->struct_mutex);
2646         if (!obj)
2647                 return false;
2648
2649         if (plane_config->tiling == I915_TILING_X)
2650                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2651
2652         mode_cmd.pixel_format = fb->format->format;
2653         mode_cmd.width = fb->width;
2654         mode_cmd.height = fb->height;
2655         mode_cmd.pitches[0] = fb->pitches[0];
2656         mode_cmd.modifier[0] = fb->modifier;
2657         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2658
2659         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2660                 DRM_DEBUG_KMS("intel fb init failed\n");
2661                 goto out_unref_obj;
2662         }
2663
2664
2665         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2666         return true;
2667
2668 out_unref_obj:
2669         i915_gem_object_put(obj);
2670         return false;
2671 }
2672
2673 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2674 static void
2675 update_state_fb(struct drm_plane *plane)
2676 {
2677         if (plane->fb == plane->state->fb)
2678                 return;
2679
2680         if (plane->state->fb)
2681                 drm_framebuffer_unreference(plane->state->fb);
2682         plane->state->fb = plane->fb;
2683         if (plane->state->fb)
2684                 drm_framebuffer_reference(plane->state->fb);
2685 }
2686
2687 static void
2688 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2689                         struct intel_plane_state *plane_state,
2690                         bool visible)
2691 {
2692         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2693
2694         plane_state->base.visible = visible;
2695
2696         /* FIXME pre-g4x don't work like this */
2697         if (visible) {
2698                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2699                 crtc_state->active_planes |= BIT(plane->id);
2700         } else {
2701                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2702                 crtc_state->active_planes &= ~BIT(plane->id);
2703         }
2704
2705         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2706                       crtc_state->base.crtc->name,
2707                       crtc_state->active_planes);
2708 }
2709
2710 static void
2711 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2712                              struct intel_initial_plane_config *plane_config)
2713 {
2714         struct drm_device *dev = intel_crtc->base.dev;
2715         struct drm_i915_private *dev_priv = to_i915(dev);
2716         struct drm_crtc *c;
2717         struct drm_i915_gem_object *obj;
2718         struct drm_plane *primary = intel_crtc->base.primary;
2719         struct drm_plane_state *plane_state = primary->state;
2720         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2721         struct intel_plane *intel_plane = to_intel_plane(primary);
2722         struct intel_plane_state *intel_state =
2723                 to_intel_plane_state(plane_state);
2724         struct drm_framebuffer *fb;
2725
2726         if (!plane_config->fb)
2727                 return;
2728
2729         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2730                 fb = &plane_config->fb->base;
2731                 goto valid_fb;
2732         }
2733
2734         kfree(plane_config->fb);
2735
2736         /*
2737          * Failed to alloc the obj, check to see if we should share
2738          * an fb with another CRTC instead
2739          */
2740         for_each_crtc(dev, c) {
2741                 struct intel_plane_state *state;
2742
2743                 if (c == &intel_crtc->base)
2744                         continue;
2745
2746                 if (!to_intel_crtc(c)->active)
2747                         continue;
2748
2749                 state = to_intel_plane_state(c->primary->state);
2750                 if (!state->vma)
2751                         continue;
2752
2753                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2754                         fb = c->primary->fb;
2755                         drm_framebuffer_reference(fb);
2756                         goto valid_fb;
2757                 }
2758         }
2759
2760         /*
2761          * We've failed to reconstruct the BIOS FB.  Current display state
2762          * indicates that the primary plane is visible, but has a NULL FB,
2763          * which will lead to problems later if we don't fix it up.  The
2764          * simplest solution is to just disable the primary plane now and
2765          * pretend the BIOS never had it enabled.
2766          */
2767         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2768                                 to_intel_plane_state(plane_state),
2769                                 false);
2770         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2771         trace_intel_disable_plane(primary, intel_crtc);
2772         intel_plane->disable_plane(intel_plane, intel_crtc);
2773
2774         return;
2775
2776 valid_fb:
2777         mutex_lock(&dev->struct_mutex);
2778         intel_state->vma =
2779                 intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
2780         mutex_unlock(&dev->struct_mutex);
2781         if (IS_ERR(intel_state->vma)) {
2782                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2783                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2784
2785                 intel_state->vma = NULL;
2786                 drm_framebuffer_unreference(fb);
2787                 return;
2788         }
2789
2790         plane_state->src_x = 0;
2791         plane_state->src_y = 0;
2792         plane_state->src_w = fb->width << 16;
2793         plane_state->src_h = fb->height << 16;
2794
2795         plane_state->crtc_x = 0;
2796         plane_state->crtc_y = 0;
2797         plane_state->crtc_w = fb->width;
2798         plane_state->crtc_h = fb->height;
2799
2800         intel_state->base.src = drm_plane_state_src(plane_state);
2801         intel_state->base.dst = drm_plane_state_dest(plane_state);
2802
2803         obj = intel_fb_obj(fb);
2804         if (i915_gem_object_is_tiled(obj))
2805                 dev_priv->preserve_bios_swizzle = true;
2806
2807         drm_framebuffer_reference(fb);
2808         primary->fb = primary->state->fb = fb;
2809         primary->crtc = primary->state->crtc = &intel_crtc->base;
2810
2811         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2812                                 to_intel_plane_state(plane_state),
2813                                 true);
2814
2815         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2816                   &obj->frontbuffer_bits);
2817 }
2818
2819 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2820                                unsigned int rotation)
2821 {
2822         int cpp = fb->format->cpp[plane];
2823
2824         switch (fb->modifier) {
2825         case DRM_FORMAT_MOD_LINEAR:
2826         case I915_FORMAT_MOD_X_TILED:
2827                 switch (cpp) {
2828                 case 8:
2829                         return 4096;
2830                 case 4:
2831                 case 2:
2832                 case 1:
2833                         return 8192;
2834                 default:
2835                         MISSING_CASE(cpp);
2836                         break;
2837                 }
2838                 break;
2839         case I915_FORMAT_MOD_Y_TILED:
2840         case I915_FORMAT_MOD_Yf_TILED:
2841                 switch (cpp) {
2842                 case 8:
2843                         return 2048;
2844                 case 4:
2845                         return 4096;
2846                 case 2:
2847                 case 1:
2848                         return 8192;
2849                 default:
2850                         MISSING_CASE(cpp);
2851                         break;
2852                 }
2853                 break;
2854         default:
2855                 MISSING_CASE(fb->modifier);
2856         }
2857
2858         return 2048;
2859 }
2860
2861 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2862 {
2863         const struct drm_framebuffer *fb = plane_state->base.fb;
2864         unsigned int rotation = plane_state->base.rotation;
2865         int x = plane_state->base.src.x1 >> 16;
2866         int y = plane_state->base.src.y1 >> 16;
2867         int w = drm_rect_width(&plane_state->base.src) >> 16;
2868         int h = drm_rect_height(&plane_state->base.src) >> 16;
2869         int max_width = skl_max_plane_width(fb, 0, rotation);
2870         int max_height = 4096;
2871         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2872
2873         if (w > max_width || h > max_height) {
2874                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2875                               w, h, max_width, max_height);
2876                 return -EINVAL;
2877         }
2878
2879         intel_add_fb_offsets(&x, &y, plane_state, 0);
2880         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2881         alignment = intel_surf_alignment(fb, 0);
2882
2883         /*
2884          * AUX surface offset is specified as the distance from the
2885          * main surface offset, and it must be non-negative. Make
2886          * sure that is what we will get.
2887          */
2888         if (offset > aux_offset)
2889                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2890                                                   offset, aux_offset & ~(alignment - 1));
2891
2892         /*
2893          * When using an X-tiled surface, the plane blows up
2894          * if the x offset + width exceed the stride.
2895          *
2896          * TODO: linear and Y-tiled seem fine, Yf untested,
2897          */
2898         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
2899                 int cpp = fb->format->cpp[0];
2900
2901                 while ((x + w) * cpp > fb->pitches[0]) {
2902                         if (offset == 0) {
2903                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2904                                 return -EINVAL;
2905                         }
2906
2907                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2908                                                           offset, offset - alignment);
2909                 }
2910         }
2911
2912         plane_state->main.offset = offset;
2913         plane_state->main.x = x;
2914         plane_state->main.y = y;
2915
2916         return 0;
2917 }
2918
2919 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2920 {
2921         const struct drm_framebuffer *fb = plane_state->base.fb;
2922         unsigned int rotation = plane_state->base.rotation;
2923         int max_width = skl_max_plane_width(fb, 1, rotation);
2924         int max_height = 4096;
2925         int x = plane_state->base.src.x1 >> 17;
2926         int y = plane_state->base.src.y1 >> 17;
2927         int w = drm_rect_width(&plane_state->base.src) >> 17;
2928         int h = drm_rect_height(&plane_state->base.src) >> 17;
2929         u32 offset;
2930
2931         intel_add_fb_offsets(&x, &y, plane_state, 1);
2932         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
2933
2934         /* FIXME not quite sure how/if these apply to the chroma plane */
2935         if (w > max_width || h > max_height) {
2936                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
2937                               w, h, max_width, max_height);
2938                 return -EINVAL;
2939         }
2940
2941         plane_state->aux.offset = offset;
2942         plane_state->aux.x = x;
2943         plane_state->aux.y = y;
2944
2945         return 0;
2946 }
2947
2948 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2949 {
2950         const struct drm_framebuffer *fb = plane_state->base.fb;
2951         unsigned int rotation = plane_state->base.rotation;
2952         int ret;
2953
2954         if (!plane_state->base.visible)
2955                 return 0;
2956
2957         /* Rotate src coordinates to match rotated GTT view */
2958         if (drm_rotation_90_or_270(rotation))
2959                 drm_rect_rotate(&plane_state->base.src,
2960                                 fb->width << 16, fb->height << 16,
2961                                 DRM_MODE_ROTATE_270);
2962
2963         /*
2964          * Handle the AUX surface first since
2965          * the main surface setup depends on it.
2966          */
2967         if (fb->format->format == DRM_FORMAT_NV12) {
2968                 ret = skl_check_nv12_aux_surface(plane_state);
2969                 if (ret)
2970                         return ret;
2971         } else {
2972                 plane_state->aux.offset = ~0xfff;
2973                 plane_state->aux.x = 0;
2974                 plane_state->aux.y = 0;
2975         }
2976
2977         ret = skl_check_main_surface(plane_state);
2978         if (ret)
2979                 return ret;
2980
2981         return 0;
2982 }
2983
2984 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
2985                           const struct intel_plane_state *plane_state)
2986 {
2987         struct drm_i915_private *dev_priv =
2988                 to_i915(plane_state->base.plane->dev);
2989         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
2990         const struct drm_framebuffer *fb = plane_state->base.fb;
2991         unsigned int rotation = plane_state->base.rotation;
2992         u32 dspcntr;
2993
2994         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
2995
2996         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
2997             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
2998                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2999
3000         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3001                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3002
3003         if (INTEL_GEN(dev_priv) < 4)
3004                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3005
3006         switch (fb->format->format) {
3007         case DRM_FORMAT_C8:
3008                 dspcntr |= DISPPLANE_8BPP;
3009                 break;
3010         case DRM_FORMAT_XRGB1555:
3011                 dspcntr |= DISPPLANE_BGRX555;
3012                 break;
3013         case DRM_FORMAT_RGB565:
3014                 dspcntr |= DISPPLANE_BGRX565;
3015                 break;
3016         case DRM_FORMAT_XRGB8888:
3017                 dspcntr |= DISPPLANE_BGRX888;
3018                 break;
3019         case DRM_FORMAT_XBGR8888:
3020                 dspcntr |= DISPPLANE_RGBX888;
3021                 break;
3022         case DRM_FORMAT_XRGB2101010:
3023                 dspcntr |= DISPPLANE_BGRX101010;
3024                 break;
3025         case DRM_FORMAT_XBGR2101010:
3026                 dspcntr |= DISPPLANE_RGBX101010;
3027                 break;
3028         default:
3029                 MISSING_CASE(fb->format->format);
3030                 return 0;
3031         }
3032
3033         if (INTEL_GEN(dev_priv) >= 4 &&
3034             fb->modifier == I915_FORMAT_MOD_X_TILED)
3035                 dspcntr |= DISPPLANE_TILED;
3036
3037         if (rotation & DRM_MODE_ROTATE_180)
3038                 dspcntr |= DISPPLANE_ROTATE_180;
3039
3040         if (rotation & DRM_MODE_REFLECT_X)
3041                 dspcntr |= DISPPLANE_MIRROR;
3042
3043         return dspcntr;
3044 }
3045
3046 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3047 {
3048         struct drm_i915_private *dev_priv =
3049                 to_i915(plane_state->base.plane->dev);
3050         int src_x = plane_state->base.src.x1 >> 16;
3051         int src_y = plane_state->base.src.y1 >> 16;
3052         u32 offset;
3053
3054         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3055
3056         if (INTEL_GEN(dev_priv) >= 4)
3057                 offset = intel_compute_tile_offset(&src_x, &src_y,
3058                                                    plane_state, 0);
3059         else
3060                 offset = 0;
3061
3062         /* HSW/BDW do this automagically in hardware */
3063         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3064                 unsigned int rotation = plane_state->base.rotation;
3065                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3066                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3067
3068                 if (rotation & DRM_MODE_ROTATE_180) {
3069                         src_x += src_w - 1;
3070                         src_y += src_h - 1;
3071                 } else if (rotation & DRM_MODE_REFLECT_X) {
3072                         src_x += src_w - 1;
3073                 }
3074         }
3075
3076         plane_state->main.offset = offset;
3077         plane_state->main.x = src_x;
3078         plane_state->main.y = src_y;
3079
3080         return 0;
3081 }
3082
3083 static void i9xx_update_primary_plane(struct intel_plane *primary,
3084                                       const struct intel_crtc_state *crtc_state,
3085                                       const struct intel_plane_state *plane_state)
3086 {
3087         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3088         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3089         const struct drm_framebuffer *fb = plane_state->base.fb;
3090         enum plane plane = primary->plane;
3091         u32 linear_offset;
3092         u32 dspcntr = plane_state->ctl;
3093         i915_reg_t reg = DSPCNTR(plane);
3094         int x = plane_state->main.x;
3095         int y = plane_state->main.y;
3096         unsigned long irqflags;
3097
3098         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3099
3100         if (INTEL_GEN(dev_priv) >= 4)
3101                 crtc->dspaddr_offset = plane_state->main.offset;
3102         else
3103                 crtc->dspaddr_offset = linear_offset;
3104
3105         crtc->adjusted_x = x;
3106         crtc->adjusted_y = y;
3107
3108         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3109
3110         if (INTEL_GEN(dev_priv) < 4) {
3111                 /* pipesrc and dspsize control the size that is scaled from,
3112                  * which should always be the user's requested size.
3113                  */
3114                 I915_WRITE_FW(DSPSIZE(plane),
3115                               ((crtc_state->pipe_src_h - 1) << 16) |
3116                               (crtc_state->pipe_src_w - 1));
3117                 I915_WRITE_FW(DSPPOS(plane), 0);
3118         } else if (IS_CHERRYVIEW(dev_priv) && plane == PLANE_B) {
3119                 I915_WRITE_FW(PRIMSIZE(plane),
3120                               ((crtc_state->pipe_src_h - 1) << 16) |
3121                               (crtc_state->pipe_src_w - 1));
3122                 I915_WRITE_FW(PRIMPOS(plane), 0);
3123                 I915_WRITE_FW(PRIMCNSTALPHA(plane), 0);
3124         }
3125
3126         I915_WRITE_FW(reg, dspcntr);
3127
3128         I915_WRITE_FW(DSPSTRIDE(plane), fb->pitches[0]);
3129         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3130                 I915_WRITE_FW(DSPSURF(plane),
3131                               intel_plane_ggtt_offset(plane_state) +
3132                               crtc->dspaddr_offset);
3133                 I915_WRITE_FW(DSPOFFSET(plane), (y << 16) | x);
3134         } else if (INTEL_GEN(dev_priv) >= 4) {
3135                 I915_WRITE_FW(DSPSURF(plane),
3136                               intel_plane_ggtt_offset(plane_state) +
3137                               crtc->dspaddr_offset);
3138                 I915_WRITE_FW(DSPTILEOFF(plane), (y << 16) | x);
3139                 I915_WRITE_FW(DSPLINOFF(plane), linear_offset);
3140         } else {
3141                 I915_WRITE_FW(DSPADDR(plane),
3142                               intel_plane_ggtt_offset(plane_state) +
3143                               crtc->dspaddr_offset);
3144         }
3145         POSTING_READ_FW(reg);
3146
3147         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3148 }
3149
3150 static void i9xx_disable_primary_plane(struct intel_plane *primary,
3151                                        struct intel_crtc *crtc)
3152 {
3153         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3154         enum plane plane = primary->plane;
3155         unsigned long irqflags;
3156
3157         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3158
3159         I915_WRITE_FW(DSPCNTR(plane), 0);
3160         if (INTEL_INFO(dev_priv)->gen >= 4)
3161                 I915_WRITE_FW(DSPSURF(plane), 0);
3162         else
3163                 I915_WRITE_FW(DSPADDR(plane), 0);
3164         POSTING_READ_FW(DSPCNTR(plane));
3165
3166         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3167 }
3168
3169 static u32
3170 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3171 {
3172         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3173                 return 64;
3174         else
3175                 return intel_tile_width_bytes(fb, plane);
3176 }
3177
3178 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3179 {
3180         struct drm_device *dev = intel_crtc->base.dev;
3181         struct drm_i915_private *dev_priv = to_i915(dev);
3182
3183         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3184         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3185         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3186 }
3187
3188 /*
3189  * This function detaches (aka. unbinds) unused scalers in hardware
3190  */
3191 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3192 {
3193         struct intel_crtc_scaler_state *scaler_state;
3194         int i;
3195
3196         scaler_state = &intel_crtc->config->scaler_state;
3197
3198         /* loop through and disable scalers that aren't in use */
3199         for (i = 0; i < intel_crtc->num_scalers; i++) {
3200                 if (!scaler_state->scalers[i].in_use)
3201                         skl_detach_scaler(intel_crtc, i);
3202         }
3203 }
3204
3205 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3206                      unsigned int rotation)
3207 {
3208         u32 stride;
3209
3210         if (plane >= fb->format->num_planes)
3211                 return 0;
3212
3213         stride = intel_fb_pitch(fb, plane, rotation);
3214
3215         /*
3216          * The stride is either expressed as a multiple of 64 bytes chunks for
3217          * linear buffers or in number of tiles for tiled buffers.
3218          */
3219         if (drm_rotation_90_or_270(rotation))
3220                 stride /= intel_tile_height(fb, plane);
3221         else
3222                 stride /= intel_fb_stride_alignment(fb, plane);
3223
3224         return stride;
3225 }
3226
3227 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3228 {
3229         switch (pixel_format) {
3230         case DRM_FORMAT_C8:
3231                 return PLANE_CTL_FORMAT_INDEXED;
3232         case DRM_FORMAT_RGB565:
3233                 return PLANE_CTL_FORMAT_RGB_565;
3234         case DRM_FORMAT_XBGR8888:
3235                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3236         case DRM_FORMAT_XRGB8888:
3237                 return PLANE_CTL_FORMAT_XRGB_8888;
3238         /*
3239          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3240          * to be already pre-multiplied. We need to add a knob (or a different
3241          * DRM_FORMAT) for user-space to configure that.
3242          */
3243         case DRM_FORMAT_ABGR8888:
3244                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3245                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3246         case DRM_FORMAT_ARGB8888:
3247                 return PLANE_CTL_FORMAT_XRGB_8888 |
3248                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3249         case DRM_FORMAT_XRGB2101010:
3250                 return PLANE_CTL_FORMAT_XRGB_2101010;
3251         case DRM_FORMAT_XBGR2101010:
3252                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3253         case DRM_FORMAT_YUYV:
3254                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3255         case DRM_FORMAT_YVYU:
3256                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3257         case DRM_FORMAT_UYVY:
3258                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3259         case DRM_FORMAT_VYUY:
3260                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3261         default:
3262                 MISSING_CASE(pixel_format);
3263         }
3264
3265         return 0;
3266 }
3267
3268 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3269 {
3270         switch (fb_modifier) {
3271         case DRM_FORMAT_MOD_LINEAR:
3272                 break;
3273         case I915_FORMAT_MOD_X_TILED:
3274                 return PLANE_CTL_TILED_X;
3275         case I915_FORMAT_MOD_Y_TILED:
3276                 return PLANE_CTL_TILED_Y;
3277         case I915_FORMAT_MOD_Yf_TILED:
3278                 return PLANE_CTL_TILED_YF;
3279         default:
3280                 MISSING_CASE(fb_modifier);
3281         }
3282
3283         return 0;
3284 }
3285
3286 static u32 skl_plane_ctl_rotation(unsigned int rotation)
3287 {
3288         switch (rotation) {
3289         case DRM_MODE_ROTATE_0:
3290                 break;
3291         /*
3292          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3293          * while i915 HW rotation is clockwise, thats why this swapping.
3294          */
3295         case DRM_MODE_ROTATE_90:
3296                 return PLANE_CTL_ROTATE_270;
3297         case DRM_MODE_ROTATE_180:
3298                 return PLANE_CTL_ROTATE_180;
3299         case DRM_MODE_ROTATE_270:
3300                 return PLANE_CTL_ROTATE_90;
3301         default:
3302                 MISSING_CASE(rotation);
3303         }
3304
3305         return 0;
3306 }
3307
3308 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3309                   const struct intel_plane_state *plane_state)
3310 {
3311         struct drm_i915_private *dev_priv =
3312                 to_i915(plane_state->base.plane->dev);
3313         const struct drm_framebuffer *fb = plane_state->base.fb;
3314         unsigned int rotation = plane_state->base.rotation;
3315         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3316         u32 plane_ctl;
3317
3318         plane_ctl = PLANE_CTL_ENABLE;
3319
3320         if (!IS_GEMINILAKE(dev_priv)) {
3321                 plane_ctl |=
3322                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3323                         PLANE_CTL_PIPE_CSC_ENABLE |
3324                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3325         }
3326
3327         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3328         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3329         plane_ctl |= skl_plane_ctl_rotation(rotation);
3330
3331         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3332                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3333         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3334                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3335
3336         return plane_ctl;
3337 }
3338
3339 static void skylake_update_primary_plane(struct intel_plane *plane,
3340                                          const struct intel_crtc_state *crtc_state,
3341                                          const struct intel_plane_state *plane_state)
3342 {
3343         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3344         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3345         const struct drm_framebuffer *fb = plane_state->base.fb;
3346         enum plane_id plane_id = plane->id;
3347         enum pipe pipe = plane->pipe;
3348         u32 plane_ctl = plane_state->ctl;
3349         unsigned int rotation = plane_state->base.rotation;
3350         u32 stride = skl_plane_stride(fb, 0, rotation);
3351         u32 surf_addr = plane_state->main.offset;
3352         int scaler_id = plane_state->scaler_id;
3353         int src_x = plane_state->main.x;
3354         int src_y = plane_state->main.y;
3355         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3356         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3357         int dst_x = plane_state->base.dst.x1;
3358         int dst_y = plane_state->base.dst.y1;
3359         int dst_w = drm_rect_width(&plane_state->base.dst);
3360         int dst_h = drm_rect_height(&plane_state->base.dst);
3361         unsigned long irqflags;
3362
3363         /* Sizes are 0 based */
3364         src_w--;
3365         src_h--;
3366         dst_w--;
3367         dst_h--;
3368
3369         crtc->dspaddr_offset = surf_addr;
3370
3371         crtc->adjusted_x = src_x;
3372         crtc->adjusted_y = src_y;
3373
3374         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3375
3376         if (IS_GEMINILAKE(dev_priv)) {
3377                 I915_WRITE_FW(PLANE_COLOR_CTL(pipe, plane_id),
3378                               PLANE_COLOR_PIPE_GAMMA_ENABLE |
3379                               PLANE_COLOR_PIPE_CSC_ENABLE |
3380                               PLANE_COLOR_PLANE_GAMMA_DISABLE);
3381         }
3382
3383         I915_WRITE_FW(PLANE_CTL(pipe, plane_id), plane_ctl);
3384         I915_WRITE_FW(PLANE_OFFSET(pipe, plane_id), (src_y << 16) | src_x);
3385         I915_WRITE_FW(PLANE_STRIDE(pipe, plane_id), stride);
3386         I915_WRITE_FW(PLANE_SIZE(pipe, plane_id), (src_h << 16) | src_w);
3387
3388         if (scaler_id >= 0) {
3389                 uint32_t ps_ctrl = 0;
3390
3391                 WARN_ON(!dst_w || !dst_h);
3392                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(plane_id) |
3393                         crtc_state->scaler_state.scalers[scaler_id].mode;
3394                 I915_WRITE_FW(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3395                 I915_WRITE_FW(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3396                 I915_WRITE_FW(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3397                 I915_WRITE_FW(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3398                 I915_WRITE_FW(PLANE_POS(pipe, plane_id), 0);
3399         } else {
3400                 I915_WRITE_FW(PLANE_POS(pipe, plane_id), (dst_y << 16) | dst_x);
3401         }
3402
3403         I915_WRITE_FW(PLANE_SURF(pipe, plane_id),
3404                       intel_plane_ggtt_offset(plane_state) + surf_addr);
3405
3406         POSTING_READ_FW(PLANE_SURF(pipe, plane_id));
3407
3408         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3409 }
3410
3411 static void skylake_disable_primary_plane(struct intel_plane *primary,
3412                                           struct intel_crtc *crtc)
3413 {
3414         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3415         enum plane_id plane_id = primary->id;
3416         enum pipe pipe = primary->pipe;
3417         unsigned long irqflags;
3418
3419         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3420
3421         I915_WRITE_FW(PLANE_CTL(pipe, plane_id), 0);
3422         I915_WRITE_FW(PLANE_SURF(pipe, plane_id), 0);
3423         POSTING_READ_FW(PLANE_SURF(pipe, plane_id));
3424
3425         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3426 }
3427
3428 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3429 {
3430         struct intel_crtc *crtc;
3431
3432         for_each_intel_crtc(&dev_priv->drm, crtc)
3433                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3434 }
3435
3436 static void intel_update_primary_planes(struct drm_device *dev)
3437 {
3438         struct drm_crtc *crtc;
3439
3440         for_each_crtc(dev, crtc) {
3441                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3442                 struct intel_plane_state *plane_state =
3443                         to_intel_plane_state(plane->base.state);
3444
3445                 if (plane_state->base.visible) {
3446                         trace_intel_update_plane(&plane->base,
3447                                                  to_intel_crtc(crtc));
3448
3449                         plane->update_plane(plane,
3450                                             to_intel_crtc_state(crtc->state),
3451                                             plane_state);
3452                 }
3453         }
3454 }
3455
3456 static int
3457 __intel_display_resume(struct drm_device *dev,
3458                        struct drm_atomic_state *state,
3459                        struct drm_modeset_acquire_ctx *ctx)
3460 {
3461         struct drm_crtc_state *crtc_state;
3462         struct drm_crtc *crtc;
3463         int i, ret;
3464
3465         intel_modeset_setup_hw_state(dev, ctx);
3466         i915_redisable_vga(to_i915(dev));
3467
3468         if (!state)
3469                 return 0;
3470
3471         /*
3472          * We've duplicated the state, pointers to the old state are invalid.
3473          *
3474          * Don't attempt to use the old state until we commit the duplicated state.
3475          */
3476         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3477                 /*
3478                  * Force recalculation even if we restore
3479                  * current state. With fast modeset this may not result
3480                  * in a modeset when the state is compatible.
3481                  */
3482                 crtc_state->mode_changed = true;
3483         }
3484
3485         /* ignore any reset values/BIOS leftovers in the WM registers */
3486         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3487                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3488
3489         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3490
3491         WARN_ON(ret == -EDEADLK);
3492         return ret;
3493 }
3494
3495 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3496 {
3497         return intel_has_gpu_reset(dev_priv) &&
3498                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3499 }
3500
3501 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3502 {
3503         struct drm_device *dev = &dev_priv->drm;
3504         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3505         struct drm_atomic_state *state;
3506         int ret;
3507
3508         /*
3509          * Need mode_config.mutex so that we don't
3510          * trample ongoing ->detect() and whatnot.
3511          */
3512         mutex_lock(&dev->mode_config.mutex);
3513         drm_modeset_acquire_init(ctx, 0);
3514         while (1) {
3515                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3516                 if (ret != -EDEADLK)
3517                         break;
3518
3519                 drm_modeset_backoff(ctx);
3520         }
3521
3522         /* reset doesn't touch the display, but flips might get nuked anyway, */
3523         if (!i915.force_reset_modeset_test &&
3524             !gpu_reset_clobbers_display(dev_priv))
3525                 return;
3526
3527         /*
3528          * Disabling the crtcs gracefully seems nicer. Also the
3529          * g33 docs say we should at least disable all the planes.
3530          */
3531         state = drm_atomic_helper_duplicate_state(dev, ctx);
3532         if (IS_ERR(state)) {
3533                 ret = PTR_ERR(state);
3534                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3535                 return;
3536         }
3537
3538         ret = drm_atomic_helper_disable_all(dev, ctx);
3539         if (ret) {
3540                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3541                 drm_atomic_state_put(state);
3542                 return;
3543         }
3544
3545         dev_priv->modeset_restore_state = state;
3546         state->acquire_ctx = ctx;
3547 }
3548
3549 void intel_finish_reset(struct drm_i915_private *dev_priv)
3550 {
3551         struct drm_device *dev = &dev_priv->drm;
3552         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3553         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3554         int ret;
3555
3556         /*
3557          * Flips in the rings will be nuked by the reset,
3558          * so complete all pending flips so that user space
3559          * will get its events and not get stuck.
3560          */
3561         intel_complete_page_flips(dev_priv);
3562
3563         dev_priv->modeset_restore_state = NULL;
3564
3565         /* reset doesn't touch the display */
3566         if (!gpu_reset_clobbers_display(dev_priv)) {
3567                 if (!state) {
3568                         /*
3569                          * Flips in the rings have been nuked by the reset,
3570                          * so update the base address of all primary
3571                          * planes to the the last fb to make sure we're
3572                          * showing the correct fb after a reset.
3573                          *
3574                          * FIXME: Atomic will make this obsolete since we won't schedule
3575                          * CS-based flips (which might get lost in gpu resets) any more.
3576                          */
3577                         intel_update_primary_planes(dev);
3578                 } else {
3579                         ret = __intel_display_resume(dev, state, ctx);
3580                         if (ret)
3581                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3582                 }
3583         } else {
3584                 /*
3585                  * The display has been reset as well,
3586                  * so need a full re-initialization.
3587                  */
3588                 intel_runtime_pm_disable_interrupts(dev_priv);
3589                 intel_runtime_pm_enable_interrupts(dev_priv);
3590
3591                 intel_pps_unlock_regs_wa(dev_priv);
3592                 intel_modeset_init_hw(dev);
3593
3594                 spin_lock_irq(&dev_priv->irq_lock);
3595                 if (dev_priv->display.hpd_irq_setup)
3596                         dev_priv->display.hpd_irq_setup(dev_priv);
3597                 spin_unlock_irq(&dev_priv->irq_lock);
3598
3599                 ret = __intel_display_resume(dev, state, ctx);
3600                 if (ret)
3601                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3602
3603                 intel_hpd_init(dev_priv);
3604         }
3605
3606         if (state)
3607                 drm_atomic_state_put(state);
3608         drm_modeset_drop_locks(ctx);
3609         drm_modeset_acquire_fini(ctx);
3610         mutex_unlock(&dev->mode_config.mutex);
3611 }
3612
3613 static bool abort_flip_on_reset(struct intel_crtc *crtc)
3614 {
3615         struct i915_gpu_error *error = &to_i915(crtc->base.dev)->gpu_error;
3616
3617         if (i915_reset_backoff(error))
3618                 return true;
3619
3620         if (crtc->reset_count != i915_reset_count(error))
3621                 return true;
3622
3623         return false;
3624 }
3625
3626 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3627 {
3628         struct drm_device *dev = crtc->dev;
3629         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3630         bool pending;
3631
3632         if (abort_flip_on_reset(intel_crtc))
3633                 return false;
3634
3635         spin_lock_irq(&dev->event_lock);
3636         pending = to_intel_crtc(crtc)->flip_work != NULL;
3637         spin_unlock_irq(&dev->event_lock);
3638
3639         return pending;
3640 }
3641
3642 static void intel_update_pipe_config(struct intel_crtc *crtc,
3643                                      struct intel_crtc_state *old_crtc_state)
3644 {
3645         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3646         struct intel_crtc_state *pipe_config =
3647                 to_intel_crtc_state(crtc->base.state);
3648
3649         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3650         crtc->base.mode = crtc->base.state->mode;
3651
3652         /*
3653          * Update pipe size and adjust fitter if needed: the reason for this is
3654          * that in compute_mode_changes we check the native mode (not the pfit
3655          * mode) to see if we can flip rather than do a full mode set. In the
3656          * fastboot case, we'll flip, but if we don't update the pipesrc and
3657          * pfit state, we'll end up with a big fb scanned out into the wrong
3658          * sized surface.
3659          */
3660
3661         I915_WRITE(PIPESRC(crtc->pipe),
3662                    ((pipe_config->pipe_src_w - 1) << 16) |
3663                    (pipe_config->pipe_src_h - 1));
3664
3665         /* on skylake this is done by detaching scalers */
3666         if (INTEL_GEN(dev_priv) >= 9) {
3667                 skl_detach_scalers(crtc);
3668
3669                 if (pipe_config->pch_pfit.enabled)
3670                         skylake_pfit_enable(crtc);
3671         } else if (HAS_PCH_SPLIT(dev_priv)) {
3672                 if (pipe_config->pch_pfit.enabled)
3673                         ironlake_pfit_enable(crtc);
3674                 else if (old_crtc_state->pch_pfit.enabled)
3675                         ironlake_pfit_disable(crtc, true);
3676         }
3677 }
3678
3679 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3680 {
3681         struct drm_device *dev = crtc->base.dev;
3682         struct drm_i915_private *dev_priv = to_i915(dev);
3683         int pipe = crtc->pipe;
3684         i915_reg_t reg;
3685         u32 temp;
3686
3687         /* enable normal train */
3688         reg = FDI_TX_CTL(pipe);
3689         temp = I915_READ(reg);
3690         if (IS_IVYBRIDGE(dev_priv)) {
3691                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3692                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3693         } else {
3694                 temp &= ~FDI_LINK_TRAIN_NONE;
3695                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3696         }
3697         I915_WRITE(reg, temp);
3698
3699         reg = FDI_RX_CTL(pipe);
3700         temp = I915_READ(reg);
3701         if (HAS_PCH_CPT(dev_priv)) {
3702                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3703                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3704         } else {
3705                 temp &= ~FDI_LINK_TRAIN_NONE;
3706                 temp |= FDI_LINK_TRAIN_NONE;
3707         }
3708         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3709
3710         /* wait one idle pattern time */
3711         POSTING_READ(reg);
3712         udelay(1000);
3713
3714         /* IVB wants error correction enabled */
3715         if (IS_IVYBRIDGE(dev_priv))
3716                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3717                            FDI_FE_ERRC_ENABLE);
3718 }
3719
3720 /* The FDI link training functions for ILK/Ibexpeak. */
3721 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3722                                     const struct intel_crtc_state *crtc_state)
3723 {
3724         struct drm_device *dev = crtc->base.dev;
3725         struct drm_i915_private *dev_priv = to_i915(dev);
3726         int pipe = crtc->pipe;
3727         i915_reg_t reg;
3728         u32 temp, tries;
3729
3730         /* FDI needs bits from pipe first */
3731         assert_pipe_enabled(dev_priv, pipe);
3732
3733         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3734            for train result */
3735         reg = FDI_RX_IMR(pipe);
3736         temp = I915_READ(reg);
3737         temp &= ~FDI_RX_SYMBOL_LOCK;
3738         temp &= ~FDI_RX_BIT_LOCK;
3739         I915_WRITE(reg, temp);
3740         I915_READ(reg);
3741         udelay(150);
3742
3743         /* enable CPU FDI TX and PCH FDI RX */
3744         reg = FDI_TX_CTL(pipe);
3745         temp = I915_READ(reg);
3746         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3747         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3748         temp &= ~FDI_LINK_TRAIN_NONE;
3749         temp |= FDI_LINK_TRAIN_PATTERN_1;
3750         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3751
3752         reg = FDI_RX_CTL(pipe);
3753         temp = I915_READ(reg);
3754         temp &= ~FDI_LINK_TRAIN_NONE;
3755         temp |= FDI_LINK_TRAIN_PATTERN_1;
3756         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3757
3758         POSTING_READ(reg);
3759         udelay(150);
3760
3761         /* Ironlake workaround, enable clock pointer after FDI enable*/
3762         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3763         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3764                    FDI_RX_PHASE_SYNC_POINTER_EN);
3765
3766         reg = FDI_RX_IIR(pipe);
3767         for (tries = 0; tries < 5; tries++) {
3768                 temp = I915_READ(reg);
3769                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3770
3771                 if ((temp & FDI_RX_BIT_LOCK)) {
3772                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3773                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3774                         break;
3775                 }
3776         }
3777         if (tries == 5)
3778                 DRM_ERROR("FDI train 1 fail!\n");
3779
3780         /* Train 2 */
3781         reg = FDI_TX_CTL(pipe);
3782         temp = I915_READ(reg);
3783         temp &= ~FDI_LINK_TRAIN_NONE;
3784         temp |= FDI_LINK_TRAIN_PATTERN_2;
3785         I915_WRITE(reg, temp);
3786
3787         reg = FDI_RX_CTL(pipe);
3788         temp = I915_READ(reg);
3789         temp &= ~FDI_LINK_TRAIN_NONE;
3790         temp |= FDI_LINK_TRAIN_PATTERN_2;
3791         I915_WRITE(reg, temp);
3792
3793         POSTING_READ(reg);
3794         udelay(150);
3795
3796         reg = FDI_RX_IIR(pipe);
3797         for (tries = 0; tries < 5; tries++) {
3798                 temp = I915_READ(reg);
3799                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3800
3801                 if (temp & FDI_RX_SYMBOL_LOCK) {
3802                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3803                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3804                         break;
3805                 }
3806         }
3807         if (tries == 5)
3808                 DRM_ERROR("FDI train 2 fail!\n");
3809
3810         DRM_DEBUG_KMS("FDI train done\n");
3811
3812 }
3813
3814 static const int snb_b_fdi_train_param[] = {
3815         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3816         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3817         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3818         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3819 };
3820
3821 /* The FDI link training functions for SNB/Cougarpoint. */
3822 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3823                                 const struct intel_crtc_state *crtc_state)
3824 {
3825         struct drm_device *dev = crtc->base.dev;
3826         struct drm_i915_private *dev_priv = to_i915(dev);
3827         int pipe = crtc->pipe;
3828         i915_reg_t reg;
3829         u32 temp, i, retry;
3830
3831         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3832            for train result */
3833         reg = FDI_RX_IMR(pipe);
3834         temp = I915_READ(reg);
3835         temp &= ~FDI_RX_SYMBOL_LOCK;
3836         temp &= ~FDI_RX_BIT_LOCK;
3837         I915_WRITE(reg, temp);
3838
3839         POSTING_READ(reg);
3840         udelay(150);
3841
3842         /* enable CPU FDI TX and PCH FDI RX */
3843         reg = FDI_TX_CTL(pipe);
3844         temp = I915_READ(reg);
3845         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3846         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3847         temp &= ~FDI_LINK_TRAIN_NONE;
3848         temp |= FDI_LINK_TRAIN_PATTERN_1;
3849         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3850         /* SNB-B */
3851         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3852         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3853
3854         I915_WRITE(FDI_RX_MISC(pipe),
3855                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3856
3857         reg = FDI_RX_CTL(pipe);
3858         temp = I915_READ(reg);
3859         if (HAS_PCH_CPT(dev_priv)) {
3860                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3861                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3862         } else {
3863                 temp &= ~FDI_LINK_TRAIN_NONE;
3864                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3865         }
3866         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3867
3868         POSTING_READ(reg);
3869         udelay(150);
3870
3871         for (i = 0; i < 4; i++) {
3872                 reg = FDI_TX_CTL(pipe);
3873                 temp = I915_READ(reg);
3874                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3875                 temp |= snb_b_fdi_train_param[i];
3876                 I915_WRITE(reg, temp);
3877
3878                 POSTING_READ(reg);
3879                 udelay(500);
3880
3881                 for (retry = 0; retry < 5; retry++) {
3882                         reg = FDI_RX_IIR(pipe);
3883                         temp = I915_READ(reg);
3884                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3885                         if (temp & FDI_RX_BIT_LOCK) {
3886                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3887                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3888                                 break;
3889                         }
3890                         udelay(50);
3891                 }
3892                 if (retry < 5)
3893                         break;
3894         }
3895         if (i == 4)
3896                 DRM_ERROR("FDI train 1 fail!\n");
3897
3898         /* Train 2 */
3899         reg = FDI_TX_CTL(pipe);
3900         temp = I915_READ(reg);
3901         temp &= ~FDI_LINK_TRAIN_NONE;
3902         temp |= FDI_LINK_TRAIN_PATTERN_2;
3903         if (IS_GEN6(dev_priv)) {
3904                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3905                 /* SNB-B */
3906                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3907         }
3908         I915_WRITE(reg, temp);
3909
3910         reg = FDI_RX_CTL(pipe);
3911         temp = I915_READ(reg);
3912         if (HAS_PCH_CPT(dev_priv)) {
3913                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3914                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3915         } else {
3916                 temp &= ~FDI_LINK_TRAIN_NONE;
3917                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3918         }
3919         I915_WRITE(reg, temp);
3920
3921         POSTING_READ(reg);
3922         udelay(150);
3923
3924         for (i = 0; i < 4; i++) {
3925                 reg = FDI_TX_CTL(pipe);
3926                 temp = I915_READ(reg);
3927                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3928                 temp |= snb_b_fdi_train_param[i];
3929                 I915_WRITE(reg, temp);
3930
3931                 POSTING_READ(reg);
3932                 udelay(500);
3933
3934                 for (retry = 0; retry < 5; retry++) {
3935                         reg = FDI_RX_IIR(pipe);
3936                         temp = I915_READ(reg);
3937                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3938                         if (temp & FDI_RX_SYMBOL_LOCK) {
3939                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3940                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3941                                 break;
3942                         }
3943                         udelay(50);
3944                 }
3945                 if (retry < 5)
3946                         break;
3947         }
3948         if (i == 4)
3949                 DRM_ERROR("FDI train 2 fail!\n");
3950
3951         DRM_DEBUG_KMS("FDI train done.\n");
3952 }
3953
3954 /* Manual link training for Ivy Bridge A0 parts */
3955 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
3956                                       const struct intel_crtc_state *crtc_state)
3957 {
3958         struct drm_device *dev = crtc->base.dev;
3959         struct drm_i915_private *dev_priv = to_i915(dev);
3960         int pipe = crtc->pipe;
3961         i915_reg_t reg;
3962         u32 temp, i, j;
3963
3964         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3965            for train result */
3966         reg = FDI_RX_IMR(pipe);
3967         temp = I915_READ(reg);
3968         temp &= ~FDI_RX_SYMBOL_LOCK;
3969         temp &= ~FDI_RX_BIT_LOCK;
3970         I915_WRITE(reg, temp);
3971
3972         POSTING_READ(reg);
3973         udelay(150);
3974
3975         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3976                       I915_READ(FDI_RX_IIR(pipe)));
3977
3978         /* Try each vswing and preemphasis setting twice before moving on */
3979         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3980                 /* disable first in case we need to retry */
3981                 reg = FDI_TX_CTL(pipe);
3982                 temp = I915_READ(reg);
3983                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3984                 temp &= ~FDI_TX_ENABLE;
3985                 I915_WRITE(reg, temp);
3986
3987                 reg = FDI_RX_CTL(pipe);
3988                 temp = I915_READ(reg);
3989                 temp &= ~FDI_LINK_TRAIN_AUTO;
3990                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3991                 temp &= ~FDI_RX_ENABLE;
3992                 I915_WRITE(reg, temp);
3993
3994                 /* enable CPU FDI TX and PCH FDI RX */
3995                 reg = FDI_TX_CTL(pipe);
3996                 temp = I915_READ(reg);
3997                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3998                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3999                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4000                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4001                 temp |= snb_b_fdi_train_param[j/2];
4002                 temp |= FDI_COMPOSITE_SYNC;
4003                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4004
4005                 I915_WRITE(FDI_RX_MISC(pipe),
4006                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4007
4008                 reg = FDI_RX_CTL(pipe);
4009                 temp = I915_READ(reg);
4010                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4011                 temp |= FDI_COMPOSITE_SYNC;
4012                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4013
4014                 POSTING_READ(reg);
4015                 udelay(1); /* should be 0.5us */
4016
4017                 for (i = 0; i < 4; i++) {
4018                         reg = FDI_RX_IIR(pipe);
4019                         temp = I915_READ(reg);
4020                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4021
4022                         if (temp & FDI_RX_BIT_LOCK ||
4023                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4024                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4025                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4026                                               i);
4027                                 break;
4028                         }
4029                         udelay(1); /* should be 0.5us */
4030                 }
4031                 if (i == 4) {
4032                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4033                         continue;
4034                 }
4035
4036                 /* Train 2 */
4037                 reg = FDI_TX_CTL(pipe);
4038                 temp = I915_READ(reg);
4039                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4040                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4041                 I915_WRITE(reg, temp);
4042
4043                 reg = FDI_RX_CTL(pipe);
4044                 temp = I915_READ(reg);
4045                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4046                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4047                 I915_WRITE(reg, temp);
4048
4049                 POSTING_READ(reg);
4050                 udelay(2); /* should be 1.5us */
4051
4052                 for (i = 0; i < 4; i++) {
4053                         reg = FDI_RX_IIR(pipe);
4054                         temp = I915_READ(reg);
4055                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4056
4057                         if (temp & FDI_RX_SYMBOL_LOCK ||
4058                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4059                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4060                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4061                                               i);
4062                                 goto train_done;
4063                         }
4064                         udelay(2); /* should be 1.5us */
4065                 }
4066                 if (i == 4)
4067                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4068         }
4069
4070 train_done:
4071         DRM_DEBUG_KMS("FDI train done.\n");
4072 }
4073
4074 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4075 {
4076         struct drm_device *dev = intel_crtc->base.dev;
4077         struct drm_i915_private *dev_priv = to_i915(dev);
4078         int pipe = intel_crtc->pipe;
4079         i915_reg_t reg;
4080         u32 temp;
4081
4082         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4083         reg = FDI_RX_CTL(pipe);
4084         temp = I915_READ(reg);
4085         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4086         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4087         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4088         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4089
4090         POSTING_READ(reg);
4091         udelay(200);
4092
4093         /* Switch from Rawclk to PCDclk */
4094         temp = I915_READ(reg);
4095         I915_WRITE(reg, temp | FDI_PCDCLK);
4096
4097         POSTING_READ(reg);
4098         udelay(200);
4099
4100         /* Enable CPU FDI TX PLL, always on for Ironlake */
4101         reg = FDI_TX_CTL(pipe);
4102         temp = I915_READ(reg);
4103         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4104                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4105
4106                 POSTING_READ(reg);
4107                 udelay(100);
4108         }
4109 }
4110
4111 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4112 {
4113         struct drm_device *dev = intel_crtc->base.dev;
4114         struct drm_i915_private *dev_priv = to_i915(dev);
4115         int pipe = intel_crtc->pipe;
4116         i915_reg_t reg;
4117         u32 temp;
4118
4119         /* Switch from PCDclk to Rawclk */
4120         reg = FDI_RX_CTL(pipe);
4121         temp = I915_READ(reg);
4122         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4123
4124         /* Disable CPU FDI TX PLL */
4125         reg = FDI_TX_CTL(pipe);
4126         temp = I915_READ(reg);
4127         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4128
4129         POSTING_READ(reg);
4130         udelay(100);
4131
4132         reg = FDI_RX_CTL(pipe);
4133         temp = I915_READ(reg);
4134         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4135
4136         /* Wait for the clocks to turn off. */
4137         POSTING_READ(reg);
4138         udelay(100);
4139 }
4140
4141 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4142 {
4143         struct drm_device *dev = crtc->dev;
4144         struct drm_i915_private *dev_priv = to_i915(dev);
4145         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4146         int pipe = intel_crtc->pipe;
4147         i915_reg_t reg;
4148         u32 temp;
4149
4150         /* disable CPU FDI tx and PCH FDI rx */
4151         reg = FDI_TX_CTL(pipe);
4152         temp = I915_READ(reg);
4153         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4154         POSTING_READ(reg);
4155
4156         reg = FDI_RX_CTL(pipe);
4157         temp = I915_READ(reg);
4158         temp &= ~(0x7 << 16);
4159         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4160         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4161
4162         POSTING_READ(reg);
4163         udelay(100);
4164
4165         /* Ironlake workaround, disable clock pointer after downing FDI */
4166         if (HAS_PCH_IBX(dev_priv))
4167                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4168
4169         /* still set train pattern 1 */
4170         reg = FDI_TX_CTL(pipe);
4171         temp = I915_READ(reg);
4172         temp &= ~FDI_LINK_TRAIN_NONE;
4173         temp |= FDI_LINK_TRAIN_PATTERN_1;
4174         I915_WRITE(reg, temp);
4175
4176         reg = FDI_RX_CTL(pipe);
4177         temp = I915_READ(reg);
4178         if (HAS_PCH_CPT(dev_priv)) {
4179                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4180                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4181         } else {
4182                 temp &= ~FDI_LINK_TRAIN_NONE;
4183                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4184         }
4185         /* BPC in FDI rx is consistent with that in PIPECONF */
4186         temp &= ~(0x07 << 16);
4187         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4188         I915_WRITE(reg, temp);
4189
4190         POSTING_READ(reg);
4191         udelay(100);
4192 }
4193
4194 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4195 {
4196         struct intel_crtc *crtc;
4197
4198         /* Note that we don't need to be called with mode_config.lock here
4199          * as our list of CRTC objects is static for the lifetime of the
4200          * device and so cannot disappear as we iterate. Similarly, we can
4201          * happily treat the predicates as racy, atomic checks as userspace
4202          * cannot claim and pin a new fb without at least acquring the
4203          * struct_mutex and so serialising with us.
4204          */
4205         for_each_intel_crtc(&dev_priv->drm, crtc) {
4206                 if (atomic_read(&crtc->unpin_work_count) == 0)
4207                         continue;
4208
4209                 if (crtc->flip_work)
4210                         intel_wait_for_vblank(dev_priv, crtc->pipe);
4211
4212                 return true;
4213         }
4214
4215         return false;
4216 }
4217
4218 static void page_flip_completed(struct intel_crtc *intel_crtc)
4219 {
4220         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4221         struct intel_flip_work *work = intel_crtc->flip_work;
4222
4223         intel_crtc->flip_work = NULL;
4224
4225         if (work->event)
4226                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4227
4228         drm_crtc_vblank_put(&intel_crtc->base);
4229
4230         wake_up_all(&dev_priv->pending_flip_queue);
4231         trace_i915_flip_complete(intel_crtc->plane,
4232                                  work->pending_flip_obj);
4233
4234         queue_work(dev_priv->wq, &work->unpin_work);
4235 }
4236
4237 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4238 {
4239         struct drm_device *dev = crtc->dev;
4240         struct drm_i915_private *dev_priv = to_i915(dev);
4241         long ret;
4242
4243         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4244
4245         ret = wait_event_interruptible_timeout(
4246                                         dev_priv->pending_flip_queue,
4247                                         !intel_crtc_has_pending_flip(crtc),
4248                                         60*HZ);
4249
4250         if (ret < 0)
4251                 return ret;
4252
4253         if (ret == 0) {
4254                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4255                 struct intel_flip_work *work;
4256
4257                 spin_lock_irq(&dev->event_lock);
4258                 work = intel_crtc->flip_work;
4259                 if (work && !is_mmio_work(work)) {
4260                         WARN_ONCE(1, "Removing stuck page flip\n");
4261                         page_flip_completed(intel_crtc);
4262                 }
4263                 spin_unlock_irq(&dev->event_lock);
4264         }
4265
4266         return 0;
4267 }
4268
4269 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4270 {
4271         u32 temp;
4272
4273         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4274
4275         mutex_lock(&dev_priv->sb_lock);
4276
4277         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4278         temp |= SBI_SSCCTL_DISABLE;
4279         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4280
4281         mutex_unlock(&dev_priv->sb_lock);
4282 }
4283
4284 /* Program iCLKIP clock to the desired frequency */
4285 static void lpt_program_iclkip(struct intel_crtc *crtc)
4286 {
4287         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4288         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4289         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4290         u32 temp;
4291
4292         lpt_disable_iclkip(dev_priv);
4293
4294         /* The iCLK virtual clock root frequency is in MHz,
4295          * but the adjusted_mode->crtc_clock in in KHz. To get the
4296          * divisors, it is necessary to divide one by another, so we
4297          * convert the virtual clock precision to KHz here for higher
4298          * precision.
4299          */
4300         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4301                 u32 iclk_virtual_root_freq = 172800 * 1000;
4302                 u32 iclk_pi_range = 64;
4303                 u32 desired_divisor;
4304
4305                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4306                                                     clock << auxdiv);
4307                 divsel = (desired_divisor / iclk_pi_range) - 2;
4308                 phaseinc = desired_divisor % iclk_pi_range;
4309
4310                 /*
4311                  * Near 20MHz is a corner case which is
4312                  * out of range for the 7-bit divisor
4313                  */
4314                 if (divsel <= 0x7f)
4315                         break;
4316         }
4317
4318         /* This should not happen with any sane values */
4319         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4320                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4321         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4322                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4323
4324         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4325                         clock,
4326                         auxdiv,
4327                         divsel,
4328                         phasedir,
4329                         phaseinc);
4330
4331         mutex_lock(&dev_priv->sb_lock);
4332
4333         /* Program SSCDIVINTPHASE6 */
4334         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4335         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4336         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4337         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4338         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4339         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4340         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4341         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4342
4343         /* Program SSCAUXDIV */
4344         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4345         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4346         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4347         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4348
4349         /* Enable modulator and associated divider */
4350         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4351         temp &= ~SBI_SSCCTL_DISABLE;
4352         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4353
4354         mutex_unlock(&dev_priv->sb_lock);
4355
4356         /* Wait for initialization time */
4357         udelay(24);
4358
4359         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4360 }
4361
4362 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4363 {
4364         u32 divsel, phaseinc, auxdiv;
4365         u32 iclk_virtual_root_freq = 172800 * 1000;
4366         u32 iclk_pi_range = 64;
4367         u32 desired_divisor;
4368         u32 temp;
4369
4370         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4371                 return 0;
4372
4373         mutex_lock(&dev_priv->sb_lock);
4374
4375         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4376         if (temp & SBI_SSCCTL_DISABLE) {
4377                 mutex_unlock(&dev_priv->sb_lock);
4378                 return 0;
4379         }
4380
4381         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4382         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4383                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4384         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4385                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4386
4387         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4388         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4389                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4390
4391         mutex_unlock(&dev_priv->sb_lock);
4392
4393         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4394
4395         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4396                                  desired_divisor << auxdiv);
4397 }
4398
4399 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4400                                                 enum pipe pch_transcoder)
4401 {
4402         struct drm_device *dev = crtc->base.dev;
4403         struct drm_i915_private *dev_priv = to_i915(dev);
4404         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4405
4406         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4407                    I915_READ(HTOTAL(cpu_transcoder)));
4408         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4409                    I915_READ(HBLANK(cpu_transcoder)));
4410         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4411                    I915_READ(HSYNC(cpu_transcoder)));
4412
4413         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4414                    I915_READ(VTOTAL(cpu_transcoder)));
4415         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4416                    I915_READ(VBLANK(cpu_transcoder)));
4417         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4418                    I915_READ(VSYNC(cpu_transcoder)));
4419         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4420                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4421 }
4422
4423 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4424 {
4425         struct drm_i915_private *dev_priv = to_i915(dev);
4426         uint32_t temp;
4427
4428         temp = I915_READ(SOUTH_CHICKEN1);
4429         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4430                 return;
4431
4432         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4433         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4434
4435         temp &= ~FDI_BC_BIFURCATION_SELECT;
4436         if (enable)
4437                 temp |= FDI_BC_BIFURCATION_SELECT;
4438
4439         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4440         I915_WRITE(SOUTH_CHICKEN1, temp);
4441         POSTING_READ(SOUTH_CHICKEN1);
4442 }
4443
4444 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4445 {
4446         struct drm_device *dev = intel_crtc->base.dev;
4447
4448         switch (intel_crtc->pipe) {
4449         case PIPE_A:
4450                 break;
4451         case PIPE_B:
4452                 if (intel_crtc->config->fdi_lanes > 2)
4453                         cpt_set_fdi_bc_bifurcation(dev, false);
4454                 else
4455                         cpt_set_fdi_bc_bifurcation(dev, true);
4456
4457                 break;
4458         case PIPE_C:
4459                 cpt_set_fdi_bc_bifurcation(dev, true);
4460
4461                 break;
4462         default:
4463                 BUG();
4464         }
4465 }
4466
4467 /* Return which DP Port should be selected for Transcoder DP control */
4468 static enum port
4469 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4470 {
4471         struct drm_device *dev = crtc->base.dev;
4472         struct intel_encoder *encoder;
4473
4474         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4475                 if (encoder->type == INTEL_OUTPUT_DP ||
4476                     encoder->type == INTEL_OUTPUT_EDP)
4477                         return enc_to_dig_port(&encoder->base)->port;
4478         }
4479
4480         return -1;
4481 }
4482
4483 /*
4484  * Enable PCH resources required for PCH ports:
4485  *   - PCH PLLs
4486  *   - FDI training & RX/TX
4487  *   - update transcoder timings
4488  *   - DP transcoding bits
4489  *   - transcoder
4490  */
4491 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4492 {
4493         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4494         struct drm_device *dev = crtc->base.dev;
4495         struct drm_i915_private *dev_priv = to_i915(dev);
4496         int pipe = crtc->pipe;
4497         u32 temp;
4498
4499         assert_pch_transcoder_disabled(dev_priv, pipe);
4500
4501         if (IS_IVYBRIDGE(dev_priv))
4502                 ivybridge_update_fdi_bc_bifurcation(crtc);
4503
4504         /* Write the TU size bits before fdi link training, so that error
4505          * detection works. */
4506         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4507                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4508
4509         /* For PCH output, training FDI link */
4510         dev_priv->display.fdi_link_train(crtc, crtc_state);
4511
4512         /* We need to program the right clock selection before writing the pixel
4513          * mutliplier into the DPLL. */
4514         if (HAS_PCH_CPT(dev_priv)) {
4515                 u32 sel;
4516
4517                 temp = I915_READ(PCH_DPLL_SEL);
4518                 temp |= TRANS_DPLL_ENABLE(pipe);
4519                 sel = TRANS_DPLLB_SEL(pipe);
4520                 if (crtc_state->shared_dpll ==
4521                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4522                         temp |= sel;
4523                 else
4524                         temp &= ~sel;
4525                 I915_WRITE(PCH_DPLL_SEL, temp);
4526         }
4527
4528         /* XXX: pch pll's can be enabled any time before we enable the PCH
4529          * transcoder, and we actually should do this to not upset any PCH
4530          * transcoder that already use the clock when we share it.
4531          *
4532          * Note that enable_shared_dpll tries to do the right thing, but
4533          * get_shared_dpll unconditionally resets the pll - we need that to have
4534          * the right LVDS enable sequence. */
4535         intel_enable_shared_dpll(crtc);
4536
4537         /* set transcoder timing, panel must allow it */
4538         assert_panel_unlocked(dev_priv, pipe);
4539         ironlake_pch_transcoder_set_timings(crtc, pipe);
4540
4541         intel_fdi_normal_train(crtc);
4542
4543         /* For PCH DP, enable TRANS_DP_CTL */
4544         if (HAS_PCH_CPT(dev_priv) &&
4545             intel_crtc_has_dp_encoder(crtc_state)) {
4546                 const struct drm_display_mode *adjusted_mode =
4547                         &crtc_state->base.adjusted_mode;
4548                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4549                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4550                 temp = I915_READ(reg);
4551                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4552                           TRANS_DP_SYNC_MASK |
4553                           TRANS_DP_BPC_MASK);
4554                 temp |= TRANS_DP_OUTPUT_ENABLE;
4555                 temp |= bpc << 9; /* same format but at 11:9 */
4556
4557                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4558                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4559                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4560                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4561
4562                 switch (intel_trans_dp_port_sel(crtc)) {
4563                 case PORT_B:
4564                         temp |= TRANS_DP_PORT_SEL_B;
4565                         break;
4566                 case PORT_C:
4567                         temp |= TRANS_DP_PORT_SEL_C;
4568                         break;
4569                 case PORT_D:
4570                         temp |= TRANS_DP_PORT_SEL_D;
4571                         break;
4572                 default:
4573                         BUG();
4574                 }
4575
4576                 I915_WRITE(reg, temp);
4577         }
4578
4579         ironlake_enable_pch_transcoder(dev_priv, pipe);
4580 }
4581
4582 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4583 {
4584         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4585         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4586         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4587
4588         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4589
4590         lpt_program_iclkip(crtc);
4591
4592         /* Set transcoder timing. */
4593         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4594
4595         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4596 }
4597
4598 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4599 {
4600         struct drm_i915_private *dev_priv = to_i915(dev);
4601         i915_reg_t dslreg = PIPEDSL(pipe);
4602         u32 temp;
4603
4604         temp = I915_READ(dslreg);
4605         udelay(500);
4606         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4607                 if (wait_for(I915_READ(dslreg) != temp, 5))
4608                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4609         }
4610 }
4611
4612 static int
4613 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4614                   unsigned int scaler_user, int *scaler_id,
4615                   int src_w, int src_h, int dst_w, int dst_h)
4616 {
4617         struct intel_crtc_scaler_state *scaler_state =
4618                 &crtc_state->scaler_state;
4619         struct intel_crtc *intel_crtc =
4620                 to_intel_crtc(crtc_state->base.crtc);
4621         int need_scaling;
4622
4623         /*
4624          * Src coordinates are already rotated by 270 degrees for
4625          * the 90/270 degree plane rotation cases (to match the
4626          * GTT mapping), hence no need to account for rotation here.
4627          */
4628         need_scaling = src_w != dst_w || src_h != dst_h;
4629
4630         /*
4631          * if plane is being disabled or scaler is no more required or force detach
4632          *  - free scaler binded to this plane/crtc
4633          *  - in order to do this, update crtc->scaler_usage
4634          *
4635          * Here scaler state in crtc_state is set free so that
4636          * scaler can be assigned to other user. Actual register
4637          * update to free the scaler is done in plane/panel-fit programming.
4638          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4639          */
4640         if (force_detach || !need_scaling) {
4641                 if (*scaler_id >= 0) {
4642                         scaler_state->scaler_users &= ~(1 << scaler_user);
4643                         scaler_state->scalers[*scaler_id].in_use = 0;
4644
4645                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4646                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4647                                 intel_crtc->pipe, scaler_user, *scaler_id,
4648                                 scaler_state->scaler_users);
4649                         *scaler_id = -1;
4650                 }
4651                 return 0;
4652         }
4653
4654         /* range checks */
4655         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4656                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4657
4658                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4659                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4660                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4661                         "size is out of scaler range\n",
4662                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4663                 return -EINVAL;
4664         }
4665
4666         /* mark this plane as a scaler user in crtc_state */
4667         scaler_state->scaler_users |= (1 << scaler_user);
4668         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4669                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4670                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4671                 scaler_state->scaler_users);
4672
4673         return 0;
4674 }
4675
4676 /**
4677  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4678  *
4679  * @state: crtc's scaler state
4680  *
4681  * Return
4682  *     0 - scaler_usage updated successfully
4683  *    error - requested scaling cannot be supported or other error condition
4684  */
4685 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4686 {
4687         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4688
4689         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4690                 &state->scaler_state.scaler_id,
4691                 state->pipe_src_w, state->pipe_src_h,
4692                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4693 }
4694
4695 /**
4696  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4697  *
4698  * @state: crtc's scaler state
4699  * @plane_state: atomic plane state to update
4700  *
4701  * Return
4702  *     0 - scaler_usage updated successfully
4703  *    error - requested scaling cannot be supported or other error condition
4704  */
4705 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4706                                    struct intel_plane_state *plane_state)
4707 {
4708
4709         struct intel_plane *intel_plane =
4710                 to_intel_plane(plane_state->base.plane);
4711         struct drm_framebuffer *fb = plane_state->base.fb;
4712         int ret;
4713
4714         bool force_detach = !fb || !plane_state->base.visible;
4715
4716         ret = skl_update_scaler(crtc_state, force_detach,
4717                                 drm_plane_index(&intel_plane->base),
4718                                 &plane_state->scaler_id,
4719                                 drm_rect_width(&plane_state->base.src) >> 16,
4720                                 drm_rect_height(&plane_state->base.src) >> 16,
4721                                 drm_rect_width(&plane_state->base.dst),
4722                                 drm_rect_height(&plane_state->base.dst));
4723
4724         if (ret || plane_state->scaler_id < 0)
4725                 return ret;
4726
4727         /* check colorkey */
4728         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4729                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4730                               intel_plane->base.base.id,
4731                               intel_plane->base.name);
4732                 return -EINVAL;
4733         }
4734
4735         /* Check src format */
4736         switch (fb->format->format) {
4737         case DRM_FORMAT_RGB565:
4738         case DRM_FORMAT_XBGR8888:
4739         case DRM_FORMAT_XRGB8888:
4740         case DRM_FORMAT_ABGR8888:
4741         case DRM_FORMAT_ARGB8888:
4742         case DRM_FORMAT_XRGB2101010:
4743         case DRM_FORMAT_XBGR2101010:
4744         case DRM_FORMAT_YUYV:
4745         case DRM_FORMAT_YVYU:
4746         case DRM_FORMAT_UYVY:
4747         case DRM_FORMAT_VYUY:
4748                 break;
4749         default:
4750                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4751                               intel_plane->base.base.id, intel_plane->base.name,
4752                               fb->base.id, fb->format->format);
4753                 return -EINVAL;
4754         }
4755
4756         return 0;
4757 }
4758
4759 static void skylake_scaler_disable(struct intel_crtc *crtc)
4760 {
4761         int i;
4762
4763         for (i = 0; i < crtc->num_scalers; i++)
4764                 skl_detach_scaler(crtc, i);
4765 }
4766
4767 static void skylake_pfit_enable(struct intel_crtc *crtc)
4768 {
4769         struct drm_device *dev = crtc->base.dev;
4770         struct drm_i915_private *dev_priv = to_i915(dev);
4771         int pipe = crtc->pipe;
4772         struct intel_crtc_scaler_state *scaler_state =
4773                 &crtc->config->scaler_state;
4774
4775         if (crtc->config->pch_pfit.enabled) {
4776                 int id;
4777
4778                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4779                         return;
4780
4781                 id = scaler_state->scaler_id;
4782                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4783                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4784                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4785                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4786         }
4787 }
4788
4789 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4790 {
4791         struct drm_device *dev = crtc->base.dev;
4792         struct drm_i915_private *dev_priv = to_i915(dev);
4793         int pipe = crtc->pipe;
4794
4795         if (crtc->config->pch_pfit.enabled) {
4796                 /* Force use of hard-coded filter coefficients
4797                  * as some pre-programmed values are broken,
4798                  * e.g. x201.
4799                  */
4800                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4801                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4802                                                  PF_PIPE_SEL_IVB(pipe));
4803                 else
4804                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4805                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4806                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4807         }
4808 }
4809
4810 void hsw_enable_ips(struct intel_crtc *crtc)
4811 {
4812         struct drm_device *dev = crtc->base.dev;
4813         struct drm_i915_private *dev_priv = to_i915(dev);
4814
4815         if (!crtc->config->ips_enabled)
4816                 return;
4817
4818         /*
4819          * We can only enable IPS after we enable a plane and wait for a vblank
4820          * This function is called from post_plane_update, which is run after
4821          * a vblank wait.
4822          */
4823
4824         assert_plane_enabled(dev_priv, crtc->plane);
4825         if (IS_BROADWELL(dev_priv)) {
4826                 mutex_lock(&dev_priv->rps.hw_lock);
4827                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4828                 mutex_unlock(&dev_priv->rps.hw_lock);
4829                 /* Quoting Art Runyan: "its not safe to expect any particular
4830                  * value in IPS_CTL bit 31 after enabling IPS through the
4831                  * mailbox." Moreover, the mailbox may return a bogus state,
4832                  * so we need to just enable it and continue on.
4833                  */
4834         } else {
4835                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4836                 /* The bit only becomes 1 in the next vblank, so this wait here
4837                  * is essentially intel_wait_for_vblank. If we don't have this
4838                  * and don't wait for vblanks until the end of crtc_enable, then
4839                  * the HW state readout code will complain that the expected
4840                  * IPS_CTL value is not the one we read. */
4841                 if (intel_wait_for_register(dev_priv,
4842                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4843                                             50))
4844                         DRM_ERROR("Timed out waiting for IPS enable\n");
4845         }
4846 }
4847
4848 void hsw_disable_ips(struct intel_crtc *crtc)
4849 {
4850         struct drm_device *dev = crtc->base.dev;
4851         struct drm_i915_private *dev_priv = to_i915(dev);
4852
4853         if (!crtc->config->ips_enabled)
4854                 return;
4855
4856         assert_plane_enabled(dev_priv, crtc->plane);
4857         if (IS_BROADWELL(dev_priv)) {
4858                 mutex_lock(&dev_priv->rps.hw_lock);
4859                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4860                 mutex_unlock(&dev_priv->rps.hw_lock);
4861                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4862                 if (intel_wait_for_register(dev_priv,
4863                                             IPS_CTL, IPS_ENABLE, 0,
4864                                             42))
4865                         DRM_ERROR("Timed out waiting for IPS disable\n");
4866         } else {
4867                 I915_WRITE(IPS_CTL, 0);
4868                 POSTING_READ(IPS_CTL);
4869         }
4870
4871         /* We need to wait for a vblank before we can disable the plane. */
4872         intel_wait_for_vblank(dev_priv, crtc->pipe);
4873 }
4874
4875 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4876 {
4877         if (intel_crtc->overlay) {
4878                 struct drm_device *dev = intel_crtc->base.dev;
4879
4880                 mutex_lock(&dev->struct_mutex);
4881                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4882                 mutex_unlock(&dev->struct_mutex);
4883         }
4884
4885         /* Let userspace switch the overlay on again. In most cases userspace
4886          * has to recompute where to put it anyway.
4887          */
4888 }
4889
4890 /**
4891  * intel_post_enable_primary - Perform operations after enabling primary plane
4892  * @crtc: the CRTC whose primary plane was just enabled
4893  *
4894  * Performs potentially sleeping operations that must be done after the primary
4895  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4896  * called due to an explicit primary plane update, or due to an implicit
4897  * re-enable that is caused when a sprite plane is updated to no longer
4898  * completely hide the primary plane.
4899  */
4900 static void
4901 intel_post_enable_primary(struct drm_crtc *crtc)
4902 {
4903         struct drm_device *dev = crtc->dev;
4904         struct drm_i915_private *dev_priv = to_i915(dev);
4905         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4906         int pipe = intel_crtc->pipe;
4907
4908         /*
4909          * FIXME IPS should be fine as long as one plane is
4910          * enabled, but in practice it seems to have problems
4911          * when going from primary only to sprite only and vice
4912          * versa.
4913          */
4914         hsw_enable_ips(intel_crtc);
4915
4916         /*
4917          * Gen2 reports pipe underruns whenever all planes are disabled.
4918          * So don't enable underrun reporting before at least some planes
4919          * are enabled.
4920          * FIXME: Need to fix the logic to work when we turn off all planes
4921          * but leave the pipe running.
4922          */
4923         if (IS_GEN2(dev_priv))
4924                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4925
4926         /* Underruns don't always raise interrupts, so check manually. */
4927         intel_check_cpu_fifo_underruns(dev_priv);
4928         intel_check_pch_fifo_underruns(dev_priv);
4929 }
4930
4931 /* FIXME move all this to pre_plane_update() with proper state tracking */
4932 static void
4933 intel_pre_disable_primary(struct drm_crtc *crtc)
4934 {
4935         struct drm_device *dev = crtc->dev;
4936         struct drm_i915_private *dev_priv = to_i915(dev);
4937         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4938         int pipe = intel_crtc->pipe;
4939
4940         /*
4941          * Gen2 reports pipe underruns whenever all planes are disabled.
4942          * So diasble underrun reporting before all the planes get disabled.
4943          * FIXME: Need to fix the logic to work when we turn off all planes
4944          * but leave the pipe running.
4945          */
4946         if (IS_GEN2(dev_priv))
4947                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4948
4949         /*
4950          * FIXME IPS should be fine as long as one plane is
4951          * enabled, but in practice it seems to have problems
4952          * when going from primary only to sprite only and vice
4953          * versa.
4954          */
4955         hsw_disable_ips(intel_crtc);
4956 }
4957
4958 /* FIXME get rid of this and use pre_plane_update */
4959 static void
4960 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4961 {
4962         struct drm_device *dev = crtc->dev;
4963         struct drm_i915_private *dev_priv = to_i915(dev);
4964         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4965         int pipe = intel_crtc->pipe;
4966
4967         intel_pre_disable_primary(crtc);
4968
4969         /*
4970          * Vblank time updates from the shadow to live plane control register
4971          * are blocked if the memory self-refresh mode is active at that
4972          * moment. So to make sure the plane gets truly disabled, disable
4973          * first the self-refresh mode. The self-refresh enable bit in turn
4974          * will be checked/applied by the HW only at the next frame start
4975          * event which is after the vblank start event, so we need to have a
4976          * wait-for-vblank between disabling the plane and the pipe.
4977          */
4978         if (HAS_GMCH_DISPLAY(dev_priv) &&
4979             intel_set_memory_cxsr(dev_priv, false))
4980                 intel_wait_for_vblank(dev_priv, pipe);
4981 }
4982
4983 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4984 {
4985         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4986         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4987         struct intel_crtc_state *pipe_config =
4988                 to_intel_crtc_state(crtc->base.state);
4989         struct drm_plane *primary = crtc->base.primary;
4990         struct drm_plane_state *old_pri_state =
4991                 drm_atomic_get_existing_plane_state(old_state, primary);
4992
4993         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
4994
4995         if (pipe_config->update_wm_post && pipe_config->base.active)
4996                 intel_update_watermarks(crtc);
4997
4998         if (old_pri_state) {
4999                 struct intel_plane_state *primary_state =
5000                         to_intel_plane_state(primary->state);
5001                 struct intel_plane_state *old_primary_state =
5002                         to_intel_plane_state(old_pri_state);
5003
5004                 intel_fbc_post_update(crtc);
5005
5006                 if (primary_state->base.visible &&
5007                     (needs_modeset(&pipe_config->base) ||
5008                      !old_primary_state->base.visible))
5009                         intel_post_enable_primary(&crtc->base);
5010         }
5011 }
5012
5013 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5014                                    struct intel_crtc_state *pipe_config)
5015 {
5016         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5017         struct drm_device *dev = crtc->base.dev;
5018         struct drm_i915_private *dev_priv = to_i915(dev);
5019         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5020         struct drm_plane *primary = crtc->base.primary;
5021         struct drm_plane_state *old_pri_state =
5022                 drm_atomic_get_existing_plane_state(old_state, primary);
5023         bool modeset = needs_modeset(&pipe_config->base);
5024         struct intel_atomic_state *old_intel_state =
5025                 to_intel_atomic_state(old_state);
5026
5027         if (old_pri_state) {
5028                 struct intel_plane_state *primary_state =
5029                         to_intel_plane_state(primary->state);
5030                 struct intel_plane_state *old_primary_state =
5031                         to_intel_plane_state(old_pri_state);
5032
5033                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5034
5035                 if (old_primary_state->base.visible &&
5036                     (modeset || !primary_state->base.visible))
5037                         intel_pre_disable_primary(&crtc->base);
5038         }
5039
5040         /*
5041          * Vblank time updates from the shadow to live plane control register
5042          * are blocked if the memory self-refresh mode is active at that
5043          * moment. So to make sure the plane gets truly disabled, disable
5044          * first the self-refresh mode. The self-refresh enable bit in turn
5045          * will be checked/applied by the HW only at the next frame start
5046          * event which is after the vblank start event, so we need to have a
5047          * wait-for-vblank between disabling the plane and the pipe.
5048          */
5049         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5050             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5051                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5052
5053         /*
5054          * IVB workaround: must disable low power watermarks for at least
5055          * one frame before enabling scaling.  LP watermarks can be re-enabled
5056          * when scaling is disabled.
5057          *
5058          * WaCxSRDisabledForSpriteScaling:ivb
5059          */
5060         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5061                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5062
5063         /*
5064          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5065          * watermark programming here.
5066          */
5067         if (needs_modeset(&pipe_config->base))
5068                 return;
5069
5070         /*
5071          * For platforms that support atomic watermarks, program the
5072          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5073          * will be the intermediate values that are safe for both pre- and
5074          * post- vblank; when vblank happens, the 'active' values will be set
5075          * to the final 'target' values and we'll do this again to get the
5076          * optimal watermarks.  For gen9+ platforms, the values we program here
5077          * will be the final target values which will get automatically latched
5078          * at vblank time; no further programming will be necessary.
5079          *
5080          * If a platform hasn't been transitioned to atomic watermarks yet,
5081          * we'll continue to update watermarks the old way, if flags tell
5082          * us to.
5083          */
5084         if (dev_priv->display.initial_watermarks != NULL)
5085                 dev_priv->display.initial_watermarks(old_intel_state,
5086                                                      pipe_config);
5087         else if (pipe_config->update_wm_pre)
5088                 intel_update_watermarks(crtc);
5089 }
5090
5091 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5092 {
5093         struct drm_device *dev = crtc->dev;
5094         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5095         struct drm_plane *p;
5096         int pipe = intel_crtc->pipe;
5097
5098         intel_crtc_dpms_overlay_disable(intel_crtc);
5099
5100         drm_for_each_plane_mask(p, dev, plane_mask)
5101                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5102
5103         /*
5104          * FIXME: Once we grow proper nuclear flip support out of this we need
5105          * to compute the mask of flip planes precisely. For the time being
5106          * consider this a flip to a NULL plane.
5107          */
5108         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5109 }
5110
5111 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5112                                           struct intel_crtc_state *crtc_state,
5113                                           struct drm_atomic_state *old_state)
5114 {
5115         struct drm_connector_state *conn_state;
5116         struct drm_connector *conn;
5117         int i;
5118
5119         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5120                 struct intel_encoder *encoder =
5121                         to_intel_encoder(conn_state->best_encoder);
5122
5123                 if (conn_state->crtc != crtc)
5124                         continue;
5125
5126                 if (encoder->pre_pll_enable)
5127                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5128         }
5129 }
5130
5131 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5132                                       struct intel_crtc_state *crtc_state,
5133                                       struct drm_atomic_state *old_state)
5134 {
5135         struct drm_connector_state *conn_state;
5136         struct drm_connector *conn;
5137         int i;
5138
5139         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5140                 struct intel_encoder *encoder =
5141                         to_intel_encoder(conn_state->best_encoder);
5142
5143                 if (conn_state->crtc != crtc)
5144                         continue;
5145
5146                 if (encoder->pre_enable)
5147                         encoder->pre_enable(encoder, crtc_state, conn_state);
5148         }
5149 }
5150
5151 static void intel_encoders_enable(struct drm_crtc *crtc,
5152                                   struct intel_crtc_state *crtc_state,
5153                                   struct drm_atomic_state *old_state)
5154 {
5155         struct drm_connector_state *conn_state;
5156         struct drm_connector *conn;
5157         int i;
5158
5159         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5160                 struct intel_encoder *encoder =
5161                         to_intel_encoder(conn_state->best_encoder);
5162
5163                 if (conn_state->crtc != crtc)
5164                         continue;
5165
5166                 encoder->enable(encoder, crtc_state, conn_state);
5167                 intel_opregion_notify_encoder(encoder, true);
5168         }
5169 }
5170
5171 static void intel_encoders_disable(struct drm_crtc *crtc,
5172                                    struct intel_crtc_state *old_crtc_state,
5173                                    struct drm_atomic_state *old_state)
5174 {
5175         struct drm_connector_state *old_conn_state;
5176         struct drm_connector *conn;
5177         int i;
5178
5179         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5180                 struct intel_encoder *encoder =
5181                         to_intel_encoder(old_conn_state->best_encoder);
5182
5183                 if (old_conn_state->crtc != crtc)
5184                         continue;
5185
5186                 intel_opregion_notify_encoder(encoder, false);
5187                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5188         }
5189 }
5190
5191 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5192                                         struct intel_crtc_state *old_crtc_state,
5193                                         struct drm_atomic_state *old_state)
5194 {
5195         struct drm_connector_state *old_conn_state;
5196         struct drm_connector *conn;
5197         int i;
5198
5199         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5200                 struct intel_encoder *encoder =
5201                         to_intel_encoder(old_conn_state->best_encoder);
5202
5203                 if (old_conn_state->crtc != crtc)
5204                         continue;
5205
5206                 if (encoder->post_disable)
5207                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5208         }
5209 }
5210
5211 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5212                                             struct intel_crtc_state *old_crtc_state,
5213                                             struct drm_atomic_state *old_state)
5214 {
5215         struct drm_connector_state *old_conn_state;
5216         struct drm_connector *conn;
5217         int i;
5218
5219         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5220                 struct intel_encoder *encoder =
5221                         to_intel_encoder(old_conn_state->best_encoder);
5222
5223                 if (old_conn_state->crtc != crtc)
5224                         continue;
5225
5226                 if (encoder->post_pll_disable)
5227                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5228         }
5229 }
5230
5231 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5232                                  struct drm_atomic_state *old_state)
5233 {
5234         struct drm_crtc *crtc = pipe_config->base.crtc;
5235         struct drm_device *dev = crtc->dev;
5236         struct drm_i915_private *dev_priv = to_i915(dev);
5237         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5238         int pipe = intel_crtc->pipe;
5239         struct intel_atomic_state *old_intel_state =
5240                 to_intel_atomic_state(old_state);
5241
5242         if (WARN_ON(intel_crtc->active))
5243                 return;
5244
5245         /*
5246          * Sometimes spurious CPU pipe underruns happen during FDI
5247          * training, at least with VGA+HDMI cloning. Suppress them.
5248          *
5249          * On ILK we get an occasional spurious CPU pipe underruns
5250          * between eDP port A enable and vdd enable. Also PCH port
5251          * enable seems to result in the occasional CPU pipe underrun.
5252          *
5253          * Spurious PCH underruns also occur during PCH enabling.
5254          */
5255         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5256                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5257         if (intel_crtc->config->has_pch_encoder)
5258                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5259
5260         if (intel_crtc->config->has_pch_encoder)
5261                 intel_prepare_shared_dpll(intel_crtc);
5262
5263         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5264                 intel_dp_set_m_n(intel_crtc, M1_N1);
5265
5266         intel_set_pipe_timings(intel_crtc);
5267         intel_set_pipe_src_size(intel_crtc);
5268
5269         if (intel_crtc->config->has_pch_encoder) {
5270                 intel_cpu_transcoder_set_m_n(intel_crtc,
5271                                      &intel_crtc->config->fdi_m_n, NULL);
5272         }
5273
5274         ironlake_set_pipeconf(crtc);
5275
5276         intel_crtc->active = true;
5277
5278         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5279
5280         if (intel_crtc->config->has_pch_encoder) {
5281                 /* Note: FDI PLL enabling _must_ be done before we enable the
5282                  * cpu pipes, hence this is separate from all the other fdi/pch
5283                  * enabling. */
5284                 ironlake_fdi_pll_enable(intel_crtc);
5285         } else {
5286                 assert_fdi_tx_disabled(dev_priv, pipe);
5287                 assert_fdi_rx_disabled(dev_priv, pipe);
5288         }
5289
5290         ironlake_pfit_enable(intel_crtc);
5291
5292         /*
5293          * On ILK+ LUT must be loaded before the pipe is running but with
5294          * clocks enabled
5295          */
5296         intel_color_load_luts(&pipe_config->base);
5297
5298         if (dev_priv->display.initial_watermarks != NULL)
5299                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5300         intel_enable_pipe(intel_crtc);
5301
5302         if (intel_crtc->config->has_pch_encoder)
5303                 ironlake_pch_enable(pipe_config);
5304
5305         assert_vblank_disabled(crtc);
5306         drm_crtc_vblank_on(crtc);
5307
5308         intel_encoders_enable(crtc, pipe_config, old_state);
5309
5310         if (HAS_PCH_CPT(dev_priv))
5311                 cpt_verify_modeset(dev, intel_crtc->pipe);
5312
5313         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5314         if (intel_crtc->config->has_pch_encoder)
5315                 intel_wait_for_vblank(dev_priv, pipe);
5316         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5317         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5318 }
5319
5320 /* IPS only exists on ULT machines and is tied to pipe A. */
5321 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5322 {
5323         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5324 }
5325
5326 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5327                                 struct drm_atomic_state *old_state)
5328 {
5329         struct drm_crtc *crtc = pipe_config->base.crtc;
5330         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5331         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5332         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5333         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5334         struct intel_atomic_state *old_intel_state =
5335                 to_intel_atomic_state(old_state);
5336
5337         if (WARN_ON(intel_crtc->active))
5338                 return;
5339
5340         if (intel_crtc->config->has_pch_encoder)
5341                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5342                                                       false);
5343
5344         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5345
5346         if (intel_crtc->config->shared_dpll)
5347                 intel_enable_shared_dpll(intel_crtc);
5348
5349         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5350                 intel_dp_set_m_n(intel_crtc, M1_N1);
5351
5352         if (!transcoder_is_dsi(cpu_transcoder))
5353                 intel_set_pipe_timings(intel_crtc);
5354
5355         intel_set_pipe_src_size(intel_crtc);
5356
5357         if (cpu_transcoder != TRANSCODER_EDP &&
5358             !transcoder_is_dsi(cpu_transcoder)) {
5359                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5360                            intel_crtc->config->pixel_multiplier - 1);
5361         }
5362
5363         if (intel_crtc->config->has_pch_encoder) {
5364                 intel_cpu_transcoder_set_m_n(intel_crtc,
5365                                      &intel_crtc->config->fdi_m_n, NULL);
5366         }
5367
5368         if (!transcoder_is_dsi(cpu_transcoder))
5369                 haswell_set_pipeconf(crtc);
5370
5371         haswell_set_pipemisc(crtc);
5372
5373         intel_color_set_csc(&pipe_config->base);
5374
5375         intel_crtc->active = true;
5376
5377         if (intel_crtc->config->has_pch_encoder)
5378                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5379         else
5380                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5381
5382         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5383
5384         if (intel_crtc->config->has_pch_encoder)
5385                 dev_priv->display.fdi_link_train(intel_crtc, pipe_config);
5386
5387         if (!transcoder_is_dsi(cpu_transcoder))
5388                 intel_ddi_enable_pipe_clock(pipe_config);
5389
5390         if (INTEL_GEN(dev_priv) >= 9)
5391                 skylake_pfit_enable(intel_crtc);
5392         else
5393                 ironlake_pfit_enable(intel_crtc);
5394
5395         /*
5396          * On ILK+ LUT must be loaded before the pipe is running but with
5397          * clocks enabled
5398          */
5399         intel_color_load_luts(&pipe_config->base);
5400
5401         intel_ddi_set_pipe_settings(pipe_config);
5402         if (!transcoder_is_dsi(cpu_transcoder))
5403                 intel_ddi_enable_transcoder_func(pipe_config);
5404
5405         if (dev_priv->display.initial_watermarks != NULL)
5406                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5407
5408         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5409         if (!transcoder_is_dsi(cpu_transcoder))
5410                 intel_enable_pipe(intel_crtc);
5411
5412         if (intel_crtc->config->has_pch_encoder)
5413                 lpt_pch_enable(pipe_config);
5414
5415         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5416                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5417
5418         assert_vblank_disabled(crtc);
5419         drm_crtc_vblank_on(crtc);
5420
5421         intel_encoders_enable(crtc, pipe_config, old_state);
5422
5423         if (intel_crtc->config->has_pch_encoder) {
5424                 intel_wait_for_vblank(dev_priv, pipe);
5425                 intel_wait_for_vblank(dev_priv, pipe);
5426                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5427                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5428                                                       true);
5429         }
5430
5431         /* If we change the relative order between pipe/planes enabling, we need
5432          * to change the workaround. */
5433         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5434         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5435                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5436                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5437         }
5438 }
5439
5440 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5441 {
5442         struct drm_device *dev = crtc->base.dev;
5443         struct drm_i915_private *dev_priv = to_i915(dev);
5444         int pipe = crtc->pipe;
5445
5446         /* To avoid upsetting the power well on haswell only disable the pfit if
5447          * it's in use. The hw state code will make sure we get this right. */
5448         if (force || crtc->config->pch_pfit.enabled) {
5449                 I915_WRITE(PF_CTL(pipe), 0);
5450                 I915_WRITE(PF_WIN_POS(pipe), 0);
5451                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5452         }
5453 }
5454
5455 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5456                                   struct drm_atomic_state *old_state)
5457 {
5458         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5459         struct drm_device *dev = crtc->dev;
5460         struct drm_i915_private *dev_priv = to_i915(dev);
5461         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5462         int pipe = intel_crtc->pipe;
5463
5464         /*
5465          * Sometimes spurious CPU pipe underruns happen when the
5466          * pipe is already disabled, but FDI RX/TX is still enabled.
5467          * Happens at least with VGA+HDMI cloning. Suppress them.
5468          */
5469         if (intel_crtc->config->has_pch_encoder) {
5470                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5471                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5472         }
5473
5474         intel_encoders_disable(crtc, old_crtc_state, old_state);
5475
5476         drm_crtc_vblank_off(crtc);
5477         assert_vblank_disabled(crtc);
5478
5479         intel_disable_pipe(intel_crtc);
5480
5481         ironlake_pfit_disable(intel_crtc, false);
5482
5483         if (intel_crtc->config->has_pch_encoder)
5484                 ironlake_fdi_disable(crtc);
5485
5486         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5487
5488         if (intel_crtc->config->has_pch_encoder) {
5489                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5490
5491                 if (HAS_PCH_CPT(dev_priv)) {
5492                         i915_reg_t reg;
5493                         u32 temp;
5494
5495                         /* disable TRANS_DP_CTL */
5496                         reg = TRANS_DP_CTL(pipe);
5497                         temp = I915_READ(reg);
5498                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5499                                   TRANS_DP_PORT_SEL_MASK);
5500                         temp |= TRANS_DP_PORT_SEL_NONE;
5501                         I915_WRITE(reg, temp);
5502
5503                         /* disable DPLL_SEL */
5504                         temp = I915_READ(PCH_DPLL_SEL);
5505                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5506                         I915_WRITE(PCH_DPLL_SEL, temp);
5507                 }
5508
5509                 ironlake_fdi_pll_disable(intel_crtc);
5510         }
5511
5512         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5513         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5514 }
5515
5516 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5517                                  struct drm_atomic_state *old_state)
5518 {
5519         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5520         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5521         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5522         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5523
5524         if (intel_crtc->config->has_pch_encoder)
5525                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5526                                                       false);
5527
5528         intel_encoders_disable(crtc, old_crtc_state, old_state);
5529
5530         drm_crtc_vblank_off(crtc);
5531         assert_vblank_disabled(crtc);
5532
5533         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5534         if (!transcoder_is_dsi(cpu_transcoder))
5535                 intel_disable_pipe(intel_crtc);
5536
5537         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5538                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5539
5540         if (!transcoder_is_dsi(cpu_transcoder))
5541                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5542
5543         if (INTEL_GEN(dev_priv) >= 9)
5544                 skylake_scaler_disable(intel_crtc);
5545         else
5546                 ironlake_pfit_disable(intel_crtc, false);
5547
5548         if (!transcoder_is_dsi(cpu_transcoder))
5549                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5550
5551         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5552
5553         if (old_crtc_state->has_pch_encoder)
5554                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5555                                                       true);
5556 }
5557
5558 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5559 {
5560         struct drm_device *dev = crtc->base.dev;
5561         struct drm_i915_private *dev_priv = to_i915(dev);
5562         struct intel_crtc_state *pipe_config = crtc->config;
5563
5564         if (!pipe_config->gmch_pfit.control)
5565                 return;
5566
5567         /*
5568          * The panel fitter should only be adjusted whilst the pipe is disabled,
5569          * according to register description and PRM.
5570          */
5571         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5572         assert_pipe_disabled(dev_priv, crtc->pipe);
5573
5574         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5575         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5576
5577         /* Border color in case we don't scale up to the full screen. Black by
5578          * default, change to something else for debugging. */
5579         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5580 }
5581
5582 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5583 {
5584         switch (port) {
5585         case PORT_A:
5586                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5587         case PORT_B:
5588                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5589         case PORT_C:
5590                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5591         case PORT_D:
5592                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5593         case PORT_E:
5594                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5595         default:
5596                 MISSING_CASE(port);
5597                 return POWER_DOMAIN_PORT_OTHER;
5598         }
5599 }
5600
5601 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5602                                   struct intel_crtc_state *crtc_state)
5603 {
5604         struct drm_device *dev = crtc->dev;
5605         struct drm_i915_private *dev_priv = to_i915(dev);
5606         struct drm_encoder *encoder;
5607         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5608         enum pipe pipe = intel_crtc->pipe;
5609         u64 mask;
5610         enum transcoder transcoder = crtc_state->cpu_transcoder;
5611
5612         if (!crtc_state->base.active)
5613                 return 0;
5614
5615         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5616         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5617         if (crtc_state->pch_pfit.enabled ||
5618             crtc_state->pch_pfit.force_thru)
5619                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5620
5621         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5622                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5623
5624                 mask |= BIT_ULL(intel_encoder->power_domain);
5625         }
5626
5627         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5628                 mask |= BIT(POWER_DOMAIN_AUDIO);
5629
5630         if (crtc_state->shared_dpll)
5631                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5632
5633         return mask;
5634 }
5635
5636 static u64
5637 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5638                                struct intel_crtc_state *crtc_state)
5639 {
5640         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5641         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5642         enum intel_display_power_domain domain;
5643         u64 domains, new_domains, old_domains;
5644
5645         old_domains = intel_crtc->enabled_power_domains;
5646         intel_crtc->enabled_power_domains = new_domains =
5647                 get_crtc_power_domains(crtc, crtc_state);
5648
5649         domains = new_domains & ~old_domains;
5650
5651         for_each_power_domain(domain, domains)
5652                 intel_display_power_get(dev_priv, domain);
5653
5654         return old_domains & ~new_domains;
5655 }
5656
5657 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5658                                       u64 domains)
5659 {
5660         enum intel_display_power_domain domain;
5661
5662         for_each_power_domain(domain, domains)
5663                 intel_display_power_put(dev_priv, domain);
5664 }
5665
5666 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5667                                    struct drm_atomic_state *old_state)
5668 {
5669         struct intel_atomic_state *old_intel_state =
5670                 to_intel_atomic_state(old_state);
5671         struct drm_crtc *crtc = pipe_config->base.crtc;
5672         struct drm_device *dev = crtc->dev;
5673         struct drm_i915_private *dev_priv = to_i915(dev);
5674         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5675         int pipe = intel_crtc->pipe;
5676
5677         if (WARN_ON(intel_crtc->active))
5678                 return;
5679
5680         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5681                 intel_dp_set_m_n(intel_crtc, M1_N1);
5682
5683         intel_set_pipe_timings(intel_crtc);
5684         intel_set_pipe_src_size(intel_crtc);
5685
5686         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5687                 struct drm_i915_private *dev_priv = to_i915(dev);
5688
5689                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5690                 I915_WRITE(CHV_CANVAS(pipe), 0);
5691         }
5692
5693         i9xx_set_pipeconf(intel_crtc);
5694
5695         intel_crtc->active = true;
5696
5697         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5698
5699         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5700
5701         if (IS_CHERRYVIEW(dev_priv)) {
5702                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5703                 chv_enable_pll(intel_crtc, intel_crtc->config);
5704         } else {
5705                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5706                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5707         }
5708
5709         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5710
5711         i9xx_pfit_enable(intel_crtc);
5712
5713         intel_color_load_luts(&pipe_config->base);
5714
5715         dev_priv->display.initial_watermarks(old_intel_state,
5716                                              pipe_config);
5717         intel_enable_pipe(intel_crtc);
5718
5719         assert_vblank_disabled(crtc);
5720         drm_crtc_vblank_on(crtc);
5721
5722         intel_encoders_enable(crtc, pipe_config, old_state);
5723 }
5724
5725 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5726 {
5727         struct drm_device *dev = crtc->base.dev;
5728         struct drm_i915_private *dev_priv = to_i915(dev);
5729
5730         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5731         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5732 }
5733
5734 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5735                              struct drm_atomic_state *old_state)
5736 {
5737         struct intel_atomic_state *old_intel_state =
5738                 to_intel_atomic_state(old_state);
5739         struct drm_crtc *crtc = pipe_config->base.crtc;
5740         struct drm_device *dev = crtc->dev;
5741         struct drm_i915_private *dev_priv = to_i915(dev);
5742         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5743         enum pipe pipe = intel_crtc->pipe;
5744
5745         if (WARN_ON(intel_crtc->active))
5746                 return;
5747
5748         i9xx_set_pll_dividers(intel_crtc);
5749
5750         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5751                 intel_dp_set_m_n(intel_crtc, M1_N1);
5752
5753         intel_set_pipe_timings(intel_crtc);
5754         intel_set_pipe_src_size(intel_crtc);
5755
5756         i9xx_set_pipeconf(intel_crtc);
5757
5758         intel_crtc->active = true;
5759
5760         if (!IS_GEN2(dev_priv))
5761                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5762
5763         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5764
5765         i9xx_enable_pll(intel_crtc);
5766
5767         i9xx_pfit_enable(intel_crtc);
5768
5769         intel_color_load_luts(&pipe_config->base);
5770
5771         if (dev_priv->display.initial_watermarks != NULL)
5772                 dev_priv->display.initial_watermarks(old_intel_state,
5773                                                      intel_crtc->config);
5774         else
5775                 intel_update_watermarks(intel_crtc);
5776         intel_enable_pipe(intel_crtc);
5777
5778         assert_vblank_disabled(crtc);
5779         drm_crtc_vblank_on(crtc);
5780
5781         intel_encoders_enable(crtc, pipe_config, old_state);
5782 }
5783
5784 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5785 {
5786         struct drm_device *dev = crtc->base.dev;
5787         struct drm_i915_private *dev_priv = to_i915(dev);
5788
5789         if (!crtc->config->gmch_pfit.control)
5790                 return;
5791
5792         assert_pipe_disabled(dev_priv, crtc->pipe);
5793
5794         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5795                          I915_READ(PFIT_CONTROL));
5796         I915_WRITE(PFIT_CONTROL, 0);
5797 }
5798
5799 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5800                               struct drm_atomic_state *old_state)
5801 {
5802         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5803         struct drm_device *dev = crtc->dev;
5804         struct drm_i915_private *dev_priv = to_i915(dev);
5805         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5806         int pipe = intel_crtc->pipe;
5807
5808         /*
5809          * On gen2 planes are double buffered but the pipe isn't, so we must
5810          * wait for planes to fully turn off before disabling the pipe.
5811          */
5812         if (IS_GEN2(dev_priv))
5813                 intel_wait_for_vblank(dev_priv, pipe);
5814
5815         intel_encoders_disable(crtc, old_crtc_state, old_state);
5816
5817         drm_crtc_vblank_off(crtc);
5818         assert_vblank_disabled(crtc);
5819
5820         intel_disable_pipe(intel_crtc);
5821
5822         i9xx_pfit_disable(intel_crtc);
5823
5824         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5825
5826         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
5827                 if (IS_CHERRYVIEW(dev_priv))
5828                         chv_disable_pll(dev_priv, pipe);
5829                 else if (IS_VALLEYVIEW(dev_priv))
5830                         vlv_disable_pll(dev_priv, pipe);
5831                 else
5832                         i9xx_disable_pll(intel_crtc);
5833         }
5834
5835         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5836
5837         if (!IS_GEN2(dev_priv))
5838                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5839
5840         if (!dev_priv->display.initial_watermarks)
5841                 intel_update_watermarks(intel_crtc);
5842 }
5843
5844 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
5845 {
5846         struct intel_encoder *encoder;
5847         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5848         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5849         enum intel_display_power_domain domain;
5850         u64 domains;
5851         struct drm_atomic_state *state;
5852         struct intel_crtc_state *crtc_state;
5853         int ret;
5854
5855         if (!intel_crtc->active)
5856                 return;
5857
5858         if (crtc->primary->state->visible) {
5859                 WARN_ON(intel_crtc->flip_work);
5860
5861                 intel_pre_disable_primary_noatomic(crtc);
5862
5863                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
5864                 crtc->primary->state->visible = false;
5865         }
5866
5867         state = drm_atomic_state_alloc(crtc->dev);
5868         if (!state) {
5869                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
5870                               crtc->base.id, crtc->name);
5871                 return;
5872         }
5873
5874         state->acquire_ctx = crtc->dev->mode_config.acquire_ctx;
5875
5876         /* Everything's already locked, -EDEADLK can't happen. */
5877         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5878         ret = drm_atomic_add_affected_connectors(state, crtc);
5879
5880         WARN_ON(IS_ERR(crtc_state) || ret);
5881
5882         dev_priv->display.crtc_disable(crtc_state, state);
5883
5884         drm_atomic_state_put(state);
5885
5886         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
5887                       crtc->base.id, crtc->name);
5888
5889         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
5890         crtc->state->active = false;
5891         intel_crtc->active = false;
5892         crtc->enabled = false;
5893         crtc->state->connector_mask = 0;
5894         crtc->state->encoder_mask = 0;
5895
5896         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
5897                 encoder->base.crtc = NULL;
5898
5899         intel_fbc_disable(intel_crtc);
5900         intel_update_watermarks(intel_crtc);
5901         intel_disable_shared_dpll(intel_crtc);
5902
5903         domains = intel_crtc->enabled_power_domains;
5904         for_each_power_domain(domain, domains)
5905                 intel_display_power_put(dev_priv, domain);
5906         intel_crtc->enabled_power_domains = 0;
5907
5908         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
5909         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
5910 }
5911
5912 /*
5913  * turn all crtc's off, but do not adjust state
5914  * This has to be paired with a call to intel_modeset_setup_hw_state.
5915  */
5916 int intel_display_suspend(struct drm_device *dev)
5917 {
5918         struct drm_i915_private *dev_priv = to_i915(dev);
5919         struct drm_atomic_state *state;
5920         int ret;
5921
5922         state = drm_atomic_helper_suspend(dev);
5923         ret = PTR_ERR_OR_ZERO(state);
5924         if (ret)
5925                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
5926         else
5927                 dev_priv->modeset_restore_state = state;
5928         return ret;
5929 }
5930
5931 void intel_encoder_destroy(struct drm_encoder *encoder)
5932 {
5933         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5934
5935         drm_encoder_cleanup(encoder);
5936         kfree(intel_encoder);
5937 }
5938
5939 /* Cross check the actual hw state with our own modeset state tracking (and it's
5940  * internal consistency). */
5941 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
5942                                          struct drm_connector_state *conn_state)
5943 {
5944         struct intel_connector *connector = to_intel_connector(conn_state->connector);
5945
5946         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
5947                       connector->base.base.id,
5948                       connector->base.name);
5949
5950         if (connector->get_hw_state(connector)) {
5951                 struct intel_encoder *encoder = connector->encoder;
5952
5953                 I915_STATE_WARN(!crtc_state,
5954                          "connector enabled without attached crtc\n");
5955
5956                 if (!crtc_state)
5957                         return;
5958
5959                 I915_STATE_WARN(!crtc_state->active,
5960                       "connector is active, but attached crtc isn't\n");
5961
5962                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
5963                         return;
5964
5965                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
5966                         "atomic encoder doesn't match attached encoder\n");
5967
5968                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
5969                         "attached encoder crtc differs from connector crtc\n");
5970         } else {
5971                 I915_STATE_WARN(crtc_state && crtc_state->active,
5972                         "attached crtc is active, but connector isn't\n");
5973                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
5974                         "best encoder set without crtc!\n");
5975         }
5976 }
5977
5978 int intel_connector_init(struct intel_connector *connector)
5979 {
5980         struct intel_digital_connector_state *conn_state;
5981
5982         /*
5983          * Allocate enough memory to hold intel_digital_connector_state,
5984          * This might be a few bytes too many, but for connectors that don't
5985          * need it we'll free the state and allocate a smaller one on the first
5986          * succesful commit anyway.
5987          */
5988         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
5989         if (!conn_state)
5990                 return -ENOMEM;
5991
5992         __drm_atomic_helper_connector_reset(&connector->base,
5993                                             &conn_state->base);
5994
5995         return 0;
5996 }
5997
5998 struct intel_connector *intel_connector_alloc(void)
5999 {
6000         struct intel_connector *connector;
6001
6002         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6003         if (!connector)
6004                 return NULL;
6005
6006         if (intel_connector_init(connector) < 0) {
6007                 kfree(connector);
6008                 return NULL;
6009         }
6010
6011         return connector;
6012 }
6013
6014 /* Simple connector->get_hw_state implementation for encoders that support only
6015  * one connector and no cloning and hence the encoder state determines the state
6016  * of the connector. */
6017 bool intel_connector_get_hw_state(struct intel_connector *connector)
6018 {
6019         enum pipe pipe = 0;
6020         struct intel_encoder *encoder = connector->encoder;
6021
6022         return encoder->get_hw_state(encoder, &pipe);
6023 }
6024
6025 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6026 {
6027         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6028                 return crtc_state->fdi_lanes;
6029
6030         return 0;
6031 }
6032
6033 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6034                                      struct intel_crtc_state *pipe_config)
6035 {
6036         struct drm_i915_private *dev_priv = to_i915(dev);
6037         struct drm_atomic_state *state = pipe_config->base.state;
6038         struct intel_crtc *other_crtc;
6039         struct intel_crtc_state *other_crtc_state;
6040
6041         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6042                       pipe_name(pipe), pipe_config->fdi_lanes);
6043         if (pipe_config->fdi_lanes > 4) {
6044                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6045                               pipe_name(pipe), pipe_config->fdi_lanes);
6046                 return -EINVAL;
6047         }
6048
6049         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6050                 if (pipe_config->fdi_lanes > 2) {
6051                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6052                                       pipe_config->fdi_lanes);
6053                         return -EINVAL;
6054                 } else {
6055                         return 0;
6056                 }
6057         }
6058
6059         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6060                 return 0;
6061
6062         /* Ivybridge 3 pipe is really complicated */
6063         switch (pipe) {
6064         case PIPE_A:
6065                 return 0;
6066         case PIPE_B:
6067                 if (pipe_config->fdi_lanes <= 2)
6068                         return 0;
6069
6070                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6071                 other_crtc_state =
6072                         intel_atomic_get_crtc_state(state, other_crtc);
6073                 if (IS_ERR(other_crtc_state))
6074                         return PTR_ERR(other_crtc_state);
6075
6076                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6077                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6078                                       pipe_name(pipe), pipe_config->fdi_lanes);
6079                         return -EINVAL;
6080                 }
6081                 return 0;
6082         case PIPE_C:
6083                 if (pipe_config->fdi_lanes > 2) {
6084                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6085                                       pipe_name(pipe), pipe_config->fdi_lanes);
6086                         return -EINVAL;
6087                 }
6088
6089                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6090                 other_crtc_state =
6091                         intel_atomic_get_crtc_state(state, other_crtc);
6092                 if (IS_ERR(other_crtc_state))
6093                         return PTR_ERR(other_crtc_state);
6094
6095                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6096                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6097                         return -EINVAL;
6098                 }
6099                 return 0;
6100         default:
6101                 BUG();
6102         }
6103 }
6104
6105 #define RETRY 1
6106 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6107                                        struct intel_crtc_state *pipe_config)
6108 {
6109         struct drm_device *dev = intel_crtc->base.dev;
6110         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6111         int lane, link_bw, fdi_dotclock, ret;
6112         bool needs_recompute = false;
6113
6114 retry:
6115         /* FDI is a binary signal running at ~2.7GHz, encoding
6116          * each output octet as 10 bits. The actual frequency
6117          * is stored as a divider into a 100MHz clock, and the
6118          * mode pixel clock is stored in units of 1KHz.
6119          * Hence the bw of each lane in terms of the mode signal
6120          * is:
6121          */
6122         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6123
6124         fdi_dotclock = adjusted_mode->crtc_clock;
6125
6126         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6127                                            pipe_config->pipe_bpp);
6128
6129         pipe_config->fdi_lanes = lane;
6130
6131         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6132                                link_bw, &pipe_config->fdi_m_n);
6133
6134         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6135         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6136                 pipe_config->pipe_bpp -= 2*3;
6137                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6138                               pipe_config->pipe_bpp);
6139                 needs_recompute = true;
6140                 pipe_config->bw_constrained = true;
6141
6142                 goto retry;
6143         }
6144
6145         if (needs_recompute)
6146                 return RETRY;
6147
6148         return ret;
6149 }
6150
6151 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6152                                      struct intel_crtc_state *pipe_config)
6153 {
6154         if (pipe_config->pipe_bpp > 24)
6155                 return false;
6156
6157         /* HSW can handle pixel rate up to cdclk? */
6158         if (IS_HASWELL(dev_priv))
6159                 return true;
6160
6161         /*
6162          * We compare against max which means we must take
6163          * the increased cdclk requirement into account when
6164          * calculating the new cdclk.
6165          *
6166          * Should measure whether using a lower cdclk w/o IPS
6167          */
6168         return pipe_config->pixel_rate <=
6169                 dev_priv->max_cdclk_freq * 95 / 100;
6170 }
6171
6172 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6173                                    struct intel_crtc_state *pipe_config)
6174 {
6175         struct drm_device *dev = crtc->base.dev;
6176         struct drm_i915_private *dev_priv = to_i915(dev);
6177
6178         pipe_config->ips_enabled = i915.enable_ips &&
6179                 hsw_crtc_supports_ips(crtc) &&
6180                 pipe_config_supports_ips(dev_priv, pipe_config);
6181 }
6182
6183 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6184 {
6185         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6186
6187         /* GDG double wide on either pipe, otherwise pipe A only */
6188         return INTEL_INFO(dev_priv)->gen < 4 &&
6189                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6190 }
6191
6192 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6193 {
6194         uint32_t pixel_rate;
6195
6196         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6197
6198         /*
6199          * We only use IF-ID interlacing. If we ever use
6200          * PF-ID we'll need to adjust the pixel_rate here.
6201          */
6202
6203         if (pipe_config->pch_pfit.enabled) {
6204                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6205                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6206
6207                 pipe_w = pipe_config->pipe_src_w;
6208                 pipe_h = pipe_config->pipe_src_h;
6209
6210                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6211                 pfit_h = pfit_size & 0xFFFF;
6212                 if (pipe_w < pfit_w)
6213                         pipe_w = pfit_w;
6214                 if (pipe_h < pfit_h)
6215                         pipe_h = pfit_h;
6216
6217                 if (WARN_ON(!pfit_w || !pfit_h))
6218                         return pixel_rate;
6219
6220                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6221                                      pfit_w * pfit_h);
6222         }
6223
6224         return pixel_rate;
6225 }
6226
6227 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6228 {
6229         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6230
6231         if (HAS_GMCH_DISPLAY(dev_priv))
6232                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6233                 crtc_state->pixel_rate =
6234                         crtc_state->base.adjusted_mode.crtc_clock;
6235         else
6236                 crtc_state->pixel_rate =
6237                         ilk_pipe_pixel_rate(crtc_state);
6238 }
6239
6240 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6241                                      struct intel_crtc_state *pipe_config)
6242 {
6243         struct drm_device *dev = crtc->base.dev;
6244         struct drm_i915_private *dev_priv = to_i915(dev);
6245         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6246         int clock_limit = dev_priv->max_dotclk_freq;
6247
6248         if (INTEL_GEN(dev_priv) < 4) {
6249                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6250
6251                 /*
6252                  * Enable double wide mode when the dot clock
6253                  * is > 90% of the (display) core speed.
6254                  */
6255                 if (intel_crtc_supports_double_wide(crtc) &&
6256                     adjusted_mode->crtc_clock > clock_limit) {
6257                         clock_limit = dev_priv->max_dotclk_freq;
6258                         pipe_config->double_wide = true;
6259                 }
6260         }
6261
6262         if (adjusted_mode->crtc_clock > clock_limit) {
6263                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6264                               adjusted_mode->crtc_clock, clock_limit,
6265                               yesno(pipe_config->double_wide));
6266                 return -EINVAL;
6267         }
6268
6269         /*
6270          * Pipe horizontal size must be even in:
6271          * - DVO ganged mode
6272          * - LVDS dual channel mode
6273          * - Double wide pipe
6274          */
6275         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6276              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6277                 pipe_config->pipe_src_w &= ~1;
6278
6279         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6280          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6281          */
6282         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6283                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6284                 return -EINVAL;
6285
6286         intel_crtc_compute_pixel_rate(pipe_config);
6287
6288         if (HAS_IPS(dev_priv))
6289                 hsw_compute_ips_config(crtc, pipe_config);
6290
6291         if (pipe_config->has_pch_encoder)
6292                 return ironlake_fdi_compute_config(crtc, pipe_config);
6293
6294         return 0;
6295 }
6296
6297 static void
6298 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6299 {
6300         while (*num > DATA_LINK_M_N_MASK ||
6301                *den > DATA_LINK_M_N_MASK) {
6302                 *num >>= 1;
6303                 *den >>= 1;
6304         }
6305 }
6306
6307 static void compute_m_n(unsigned int m, unsigned int n,
6308                         uint32_t *ret_m, uint32_t *ret_n)
6309 {
6310         /*
6311          * Reduce M/N as much as possible without loss in precision. Several DP
6312          * dongles in particular seem to be fussy about too large *link* M/N
6313          * values. The passed in values are more likely to have the least
6314          * significant bits zero than M after rounding below, so do this first.
6315          */
6316         while ((m & 1) == 0 && (n & 1) == 0) {
6317                 m >>= 1;
6318                 n >>= 1;
6319         }
6320
6321         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6322         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6323         intel_reduce_m_n_ratio(ret_m, ret_n);
6324 }
6325
6326 void
6327 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6328                        int pixel_clock, int link_clock,
6329                        struct intel_link_m_n *m_n)
6330 {
6331         m_n->tu = 64;
6332
6333         compute_m_n(bits_per_pixel * pixel_clock,
6334                     link_clock * nlanes * 8,
6335                     &m_n->gmch_m, &m_n->gmch_n);
6336
6337         compute_m_n(pixel_clock, link_clock,
6338                     &m_n->link_m, &m_n->link_n);
6339 }
6340
6341 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6342 {
6343         if (i915.panel_use_ssc >= 0)
6344                 return i915.panel_use_ssc != 0;
6345         return dev_priv->vbt.lvds_use_ssc
6346                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6347 }
6348
6349 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6350 {
6351         return (1 << dpll->n) << 16 | dpll->m2;
6352 }
6353
6354 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6355 {
6356         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6357 }
6358
6359 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6360                                      struct intel_crtc_state *crtc_state,
6361                                      struct dpll *reduced_clock)
6362 {
6363         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6364         u32 fp, fp2 = 0;
6365
6366         if (IS_PINEVIEW(dev_priv)) {
6367                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6368                 if (reduced_clock)
6369                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6370         } else {
6371                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6372                 if (reduced_clock)
6373                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6374         }
6375
6376         crtc_state->dpll_hw_state.fp0 = fp;
6377
6378         crtc->lowfreq_avail = false;
6379         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6380             reduced_clock) {
6381                 crtc_state->dpll_hw_state.fp1 = fp2;
6382                 crtc->lowfreq_avail = true;
6383         } else {
6384                 crtc_state->dpll_hw_state.fp1 = fp;
6385         }
6386 }
6387
6388 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6389                 pipe)
6390 {
6391         u32 reg_val;
6392
6393         /*
6394          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6395          * and set it to a reasonable value instead.
6396          */
6397         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6398         reg_val &= 0xffffff00;
6399         reg_val |= 0x00000030;
6400         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6401
6402         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6403         reg_val &= 0x00ffffff;
6404         reg_val |= 0x8c000000;
6405         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6406
6407         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6408         reg_val &= 0xffffff00;
6409         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6410
6411         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6412         reg_val &= 0x00ffffff;
6413         reg_val |= 0xb0000000;
6414         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6415 }
6416
6417 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6418                                          struct intel_link_m_n *m_n)
6419 {
6420         struct drm_device *dev = crtc->base.dev;
6421         struct drm_i915_private *dev_priv = to_i915(dev);
6422         int pipe = crtc->pipe;
6423
6424         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6425         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6426         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6427         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6428 }
6429
6430 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6431                                          struct intel_link_m_n *m_n,
6432                                          struct intel_link_m_n *m2_n2)
6433 {
6434         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6435         int pipe = crtc->pipe;
6436         enum transcoder transcoder = crtc->config->cpu_transcoder;
6437
6438         if (INTEL_GEN(dev_priv) >= 5) {
6439                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6440                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6441                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6442                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6443                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6444                  * for gen < 8) and if DRRS is supported (to make sure the
6445                  * registers are not unnecessarily accessed).
6446                  */
6447                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6448                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6449                         I915_WRITE(PIPE_DATA_M2(transcoder),
6450                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6451                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6452                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6453                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6454                 }
6455         } else {
6456                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6457                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6458                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6459                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6460         }
6461 }
6462
6463 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6464 {
6465         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6466
6467         if (m_n == M1_N1) {
6468                 dp_m_n = &crtc->config->dp_m_n;
6469                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6470         } else if (m_n == M2_N2) {
6471
6472                 /*
6473                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6474                  * needs to be programmed into M1_N1.
6475                  */
6476                 dp_m_n = &crtc->config->dp_m2_n2;
6477         } else {
6478                 DRM_ERROR("Unsupported divider value\n");
6479                 return;
6480         }
6481
6482         if (crtc->config->has_pch_encoder)
6483                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6484         else
6485                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6486 }
6487
6488 static void vlv_compute_dpll(struct intel_crtc *crtc,
6489                              struct intel_crtc_state *pipe_config)
6490 {
6491         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6492                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6493         if (crtc->pipe != PIPE_A)
6494                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6495
6496         /* DPLL not used with DSI, but still need the rest set up */
6497         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6498                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6499                         DPLL_EXT_BUFFER_ENABLE_VLV;
6500
6501         pipe_config->dpll_hw_state.dpll_md =
6502                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6503 }
6504
6505 static void chv_compute_dpll(struct intel_crtc *crtc,
6506                              struct intel_crtc_state *pipe_config)
6507 {
6508         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6509                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6510         if (crtc->pipe != PIPE_A)
6511                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6512
6513         /* DPLL not used with DSI, but still need the rest set up */
6514         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6515                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6516
6517         pipe_config->dpll_hw_state.dpll_md =
6518                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6519 }
6520
6521 static void vlv_prepare_pll(struct intel_crtc *crtc,
6522                             const struct intel_crtc_state *pipe_config)
6523 {
6524         struct drm_device *dev = crtc->base.dev;
6525         struct drm_i915_private *dev_priv = to_i915(dev);
6526         enum pipe pipe = crtc->pipe;
6527         u32 mdiv;
6528         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6529         u32 coreclk, reg_val;
6530
6531         /* Enable Refclk */
6532         I915_WRITE(DPLL(pipe),
6533                    pipe_config->dpll_hw_state.dpll &
6534                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6535
6536         /* No need to actually set up the DPLL with DSI */
6537         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6538                 return;
6539
6540         mutex_lock(&dev_priv->sb_lock);
6541
6542         bestn = pipe_config->dpll.n;
6543         bestm1 = pipe_config->dpll.m1;
6544         bestm2 = pipe_config->dpll.m2;
6545         bestp1 = pipe_config->dpll.p1;
6546         bestp2 = pipe_config->dpll.p2;
6547
6548         /* See eDP HDMI DPIO driver vbios notes doc */
6549
6550         /* PLL B needs special handling */
6551         if (pipe == PIPE_B)
6552                 vlv_pllb_recal_opamp(dev_priv, pipe);
6553
6554         /* Set up Tx target for periodic Rcomp update */
6555         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6556
6557         /* Disable target IRef on PLL */
6558         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6559         reg_val &= 0x00ffffff;
6560         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6561
6562         /* Disable fast lock */
6563         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6564
6565         /* Set idtafcrecal before PLL is enabled */
6566         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6567         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6568         mdiv |= ((bestn << DPIO_N_SHIFT));
6569         mdiv |= (1 << DPIO_K_SHIFT);
6570
6571         /*
6572          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6573          * but we don't support that).
6574          * Note: don't use the DAC post divider as it seems unstable.
6575          */
6576         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6577         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6578
6579         mdiv |= DPIO_ENABLE_CALIBRATION;
6580         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6581
6582         /* Set HBR and RBR LPF coefficients */
6583         if (pipe_config->port_clock == 162000 ||
6584             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6585             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6586                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6587                                  0x009f0003);
6588         else
6589                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6590                                  0x00d0000f);
6591
6592         if (intel_crtc_has_dp_encoder(pipe_config)) {
6593                 /* Use SSC source */
6594                 if (pipe == PIPE_A)
6595                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6596                                          0x0df40000);
6597                 else
6598                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6599                                          0x0df70000);
6600         } else { /* HDMI or VGA */
6601                 /* Use bend source */
6602                 if (pipe == PIPE_A)
6603                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6604                                          0x0df70000);
6605                 else
6606                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6607                                          0x0df40000);
6608         }
6609
6610         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6611         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6612         if (intel_crtc_has_dp_encoder(crtc->config))
6613                 coreclk |= 0x01000000;
6614         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6615
6616         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6617         mutex_unlock(&dev_priv->sb_lock);
6618 }
6619
6620 static void chv_prepare_pll(struct intel_crtc *crtc,
6621                             const struct intel_crtc_state *pipe_config)
6622 {
6623         struct drm_device *dev = crtc->base.dev;
6624         struct drm_i915_private *dev_priv = to_i915(dev);
6625         enum pipe pipe = crtc->pipe;
6626         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6627         u32 loopfilter, tribuf_calcntr;
6628         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6629         u32 dpio_val;
6630         int vco;
6631
6632         /* Enable Refclk and SSC */
6633         I915_WRITE(DPLL(pipe),
6634                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6635
6636         /* No need to actually set up the DPLL with DSI */
6637         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6638                 return;
6639
6640         bestn = pipe_config->dpll.n;
6641         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6642         bestm1 = pipe_config->dpll.m1;
6643         bestm2 = pipe_config->dpll.m2 >> 22;
6644         bestp1 = pipe_config->dpll.p1;
6645         bestp2 = pipe_config->dpll.p2;
6646         vco = pipe_config->dpll.vco;
6647         dpio_val = 0;
6648         loopfilter = 0;
6649
6650         mutex_lock(&dev_priv->sb_lock);
6651
6652         /* p1 and p2 divider */
6653         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6654                         5 << DPIO_CHV_S1_DIV_SHIFT |
6655                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6656                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6657                         1 << DPIO_CHV_K_DIV_SHIFT);
6658
6659         /* Feedback post-divider - m2 */
6660         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6661
6662         /* Feedback refclk divider - n and m1 */
6663         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6664                         DPIO_CHV_M1_DIV_BY_2 |
6665                         1 << DPIO_CHV_N_DIV_SHIFT);
6666
6667         /* M2 fraction division */
6668         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6669
6670         /* M2 fraction division enable */
6671         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6672         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6673         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6674         if (bestm2_frac)
6675                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6676         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6677
6678         /* Program digital lock detect threshold */
6679         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6680         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6681                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6682         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6683         if (!bestm2_frac)
6684                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6685         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6686
6687         /* Loop filter */
6688         if (vco == 5400000) {
6689                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6690                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6691                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6692                 tribuf_calcntr = 0x9;
6693         } else if (vco <= 6200000) {
6694                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6695                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6696                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6697                 tribuf_calcntr = 0x9;
6698         } else if (vco <= 6480000) {
6699                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6700                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6701                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6702                 tribuf_calcntr = 0x8;
6703         } else {
6704                 /* Not supported. Apply the same limits as in the max case */
6705                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6706                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6707                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6708                 tribuf_calcntr = 0;
6709         }
6710         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6711
6712         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6713         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6714         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6715         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6716
6717         /* AFC Recal */
6718         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6719                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6720                         DPIO_AFC_RECAL);
6721
6722         mutex_unlock(&dev_priv->sb_lock);
6723 }
6724
6725 /**
6726  * vlv_force_pll_on - forcibly enable just the PLL
6727  * @dev_priv: i915 private structure
6728  * @pipe: pipe PLL to enable
6729  * @dpll: PLL configuration
6730  *
6731  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6732  * in cases where we need the PLL enabled even when @pipe is not going to
6733  * be enabled.
6734  */
6735 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6736                      const struct dpll *dpll)
6737 {
6738         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6739         struct intel_crtc_state *pipe_config;
6740
6741         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6742         if (!pipe_config)
6743                 return -ENOMEM;
6744
6745         pipe_config->base.crtc = &crtc->base;
6746         pipe_config->pixel_multiplier = 1;
6747         pipe_config->dpll = *dpll;
6748
6749         if (IS_CHERRYVIEW(dev_priv)) {
6750                 chv_compute_dpll(crtc, pipe_config);
6751                 chv_prepare_pll(crtc, pipe_config);
6752                 chv_enable_pll(crtc, pipe_config);
6753         } else {
6754                 vlv_compute_dpll(crtc, pipe_config);
6755                 vlv_prepare_pll(crtc, pipe_config);
6756                 vlv_enable_pll(crtc, pipe_config);
6757         }
6758
6759         kfree(pipe_config);
6760
6761         return 0;
6762 }
6763
6764 /**
6765  * vlv_force_pll_off - forcibly disable just the PLL
6766  * @dev_priv: i915 private structure
6767  * @pipe: pipe PLL to disable
6768  *
6769  * Disable the PLL for @pipe. To be used in cases where we need
6770  * the PLL enabled even when @pipe is not going to be enabled.
6771  */
6772 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
6773 {
6774         if (IS_CHERRYVIEW(dev_priv))
6775                 chv_disable_pll(dev_priv, pipe);
6776         else
6777                 vlv_disable_pll(dev_priv, pipe);
6778 }
6779
6780 static void i9xx_compute_dpll(struct intel_crtc *crtc,
6781                               struct intel_crtc_state *crtc_state,
6782                               struct dpll *reduced_clock)
6783 {
6784         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6785         u32 dpll;
6786         struct dpll *clock = &crtc_state->dpll;
6787
6788         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6789
6790         dpll = DPLL_VGA_MODE_DIS;
6791
6792         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
6793                 dpll |= DPLLB_MODE_LVDS;
6794         else
6795                 dpll |= DPLLB_MODE_DAC_SERIAL;
6796
6797         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
6798             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
6799                 dpll |= (crtc_state->pixel_multiplier - 1)
6800                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6801         }
6802
6803         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
6804             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
6805                 dpll |= DPLL_SDVO_HIGH_SPEED;
6806
6807         if (intel_crtc_has_dp_encoder(crtc_state))
6808                 dpll |= DPLL_SDVO_HIGH_SPEED;
6809
6810         /* compute bitmask from p1 value */
6811         if (IS_PINEVIEW(dev_priv))
6812                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6813         else {
6814                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6815                 if (IS_G4X(dev_priv) && reduced_clock)
6816                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6817         }
6818         switch (clock->p2) {
6819         case 5:
6820                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6821                 break;
6822         case 7:
6823                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6824                 break;
6825         case 10:
6826                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6827                 break;
6828         case 14:
6829                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6830                 break;
6831         }
6832         if (INTEL_GEN(dev_priv) >= 4)
6833                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6834
6835         if (crtc_state->sdvo_tv_clock)
6836                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6837         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6838                  intel_panel_use_ssc(dev_priv))
6839                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6840         else
6841                 dpll |= PLL_REF_INPUT_DREFCLK;
6842
6843         dpll |= DPLL_VCO_ENABLE;
6844         crtc_state->dpll_hw_state.dpll = dpll;
6845
6846         if (INTEL_GEN(dev_priv) >= 4) {
6847                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6848                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6849                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
6850         }
6851 }
6852
6853 static void i8xx_compute_dpll(struct intel_crtc *crtc,
6854                               struct intel_crtc_state *crtc_state,
6855                               struct dpll *reduced_clock)
6856 {
6857         struct drm_device *dev = crtc->base.dev;
6858         struct drm_i915_private *dev_priv = to_i915(dev);
6859         u32 dpll;
6860         struct dpll *clock = &crtc_state->dpll;
6861
6862         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6863
6864         dpll = DPLL_VGA_MODE_DIS;
6865
6866         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
6867                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6868         } else {
6869                 if (clock->p1 == 2)
6870                         dpll |= PLL_P1_DIVIDE_BY_TWO;
6871                 else
6872                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6873                 if (clock->p2 == 4)
6874                         dpll |= PLL_P2_DIVIDE_BY_4;
6875         }
6876
6877         if (!IS_I830(dev_priv) &&
6878             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
6879                 dpll |= DPLL_DVO_2X_MODE;
6880
6881         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6882             intel_panel_use_ssc(dev_priv))
6883                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6884         else
6885                 dpll |= PLL_REF_INPUT_DREFCLK;
6886
6887         dpll |= DPLL_VCO_ENABLE;
6888         crtc_state->dpll_hw_state.dpll = dpll;
6889 }
6890
6891 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
6892 {
6893         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
6894         enum pipe pipe = intel_crtc->pipe;
6895         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
6896         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
6897         uint32_t crtc_vtotal, crtc_vblank_end;
6898         int vsyncshift = 0;
6899
6900         /* We need to be careful not to changed the adjusted mode, for otherwise
6901          * the hw state checker will get angry at the mismatch. */
6902         crtc_vtotal = adjusted_mode->crtc_vtotal;
6903         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
6904
6905         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
6906                 /* the chip adds 2 halflines automatically */
6907                 crtc_vtotal -= 1;
6908                 crtc_vblank_end -= 1;
6909
6910                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
6911                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
6912                 else
6913                         vsyncshift = adjusted_mode->crtc_hsync_start -
6914                                 adjusted_mode->crtc_htotal / 2;
6915                 if (vsyncshift < 0)
6916                         vsyncshift += adjusted_mode->crtc_htotal;
6917         }
6918
6919         if (INTEL_GEN(dev_priv) > 3)
6920                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
6921
6922         I915_WRITE(HTOTAL(cpu_transcoder),
6923                    (adjusted_mode->crtc_hdisplay - 1) |
6924                    ((adjusted_mode->crtc_htotal - 1) << 16));
6925         I915_WRITE(HBLANK(cpu_transcoder),
6926                    (adjusted_mode->crtc_hblank_start - 1) |
6927                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
6928         I915_WRITE(HSYNC(cpu_transcoder),
6929                    (adjusted_mode->crtc_hsync_start - 1) |
6930                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
6931
6932         I915_WRITE(VTOTAL(cpu_transcoder),
6933                    (adjusted_mode->crtc_vdisplay - 1) |
6934                    ((crtc_vtotal - 1) << 16));
6935         I915_WRITE(VBLANK(cpu_transcoder),
6936                    (adjusted_mode->crtc_vblank_start - 1) |
6937                    ((crtc_vblank_end - 1) << 16));
6938         I915_WRITE(VSYNC(cpu_transcoder),
6939                    (adjusted_mode->crtc_vsync_start - 1) |
6940                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
6941
6942         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
6943          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
6944          * documented on the DDI_FUNC_CTL register description, EDP Input Select
6945          * bits. */
6946         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
6947             (pipe == PIPE_B || pipe == PIPE_C))
6948                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
6949
6950 }
6951
6952 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
6953 {
6954         struct drm_device *dev = intel_crtc->base.dev;
6955         struct drm_i915_private *dev_priv = to_i915(dev);
6956         enum pipe pipe = intel_crtc->pipe;
6957
6958         /* pipesrc controls the size that is scaled from, which should
6959          * always be the user's requested size.
6960          */
6961         I915_WRITE(PIPESRC(pipe),
6962                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
6963                    (intel_crtc->config->pipe_src_h - 1));
6964 }
6965
6966 static void intel_get_pipe_timings(struct intel_crtc *crtc,
6967                                    struct intel_crtc_state *pipe_config)
6968 {
6969         struct drm_device *dev = crtc->base.dev;
6970         struct drm_i915_private *dev_priv = to_i915(dev);
6971         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6972         uint32_t tmp;
6973
6974         tmp = I915_READ(HTOTAL(cpu_transcoder));
6975         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
6976         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
6977         tmp = I915_READ(HBLANK(cpu_transcoder));
6978         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
6979         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
6980         tmp = I915_READ(HSYNC(cpu_transcoder));
6981         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
6982         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
6983
6984         tmp = I915_READ(VTOTAL(cpu_transcoder));
6985         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
6986         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
6987         tmp = I915_READ(VBLANK(cpu_transcoder));
6988         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
6989         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
6990         tmp = I915_READ(VSYNC(cpu_transcoder));
6991         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
6992         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
6993
6994         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
6995                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
6996                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
6997                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
6998         }
6999 }
7000
7001 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7002                                     struct intel_crtc_state *pipe_config)
7003 {
7004         struct drm_device *dev = crtc->base.dev;
7005         struct drm_i915_private *dev_priv = to_i915(dev);
7006         u32 tmp;
7007
7008         tmp = I915_READ(PIPESRC(crtc->pipe));
7009         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7010         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7011
7012         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7013         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7014 }
7015
7016 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7017                                  struct intel_crtc_state *pipe_config)
7018 {
7019         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7020         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7021         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7022         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7023
7024         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7025         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7026         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7027         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7028
7029         mode->flags = pipe_config->base.adjusted_mode.flags;
7030         mode->type = DRM_MODE_TYPE_DRIVER;
7031
7032         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7033
7034         mode->hsync = drm_mode_hsync(mode);
7035         mode->vrefresh = drm_mode_vrefresh(mode);
7036         drm_mode_set_name(mode);
7037 }
7038
7039 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7040 {
7041         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7042         uint32_t pipeconf;
7043
7044         pipeconf = 0;
7045
7046         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7047             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7048                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7049
7050         if (intel_crtc->config->double_wide)
7051                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7052
7053         /* only g4x and later have fancy bpc/dither controls */
7054         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7055             IS_CHERRYVIEW(dev_priv)) {
7056                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7057                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7058                         pipeconf |= PIPECONF_DITHER_EN |
7059                                     PIPECONF_DITHER_TYPE_SP;
7060
7061                 switch (intel_crtc->config->pipe_bpp) {
7062                 case 18:
7063                         pipeconf |= PIPECONF_6BPC;
7064                         break;
7065                 case 24:
7066                         pipeconf |= PIPECONF_8BPC;
7067                         break;
7068                 case 30:
7069                         pipeconf |= PIPECONF_10BPC;
7070                         break;
7071                 default:
7072                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7073                         BUG();
7074                 }
7075         }
7076
7077         if (HAS_PIPE_CXSR(dev_priv)) {
7078                 if (intel_crtc->lowfreq_avail) {
7079                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7080                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7081                 } else {
7082                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7083                 }
7084         }
7085
7086         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7087                 if (INTEL_GEN(dev_priv) < 4 ||
7088                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7089                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7090                 else
7091                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7092         } else
7093                 pipeconf |= PIPECONF_PROGRESSIVE;
7094
7095         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7096              intel_crtc->config->limited_color_range)
7097                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7098
7099         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7100         POSTING_READ(PIPECONF(intel_crtc->pipe));
7101 }
7102
7103 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7104                                    struct intel_crtc_state *crtc_state)
7105 {
7106         struct drm_device *dev = crtc->base.dev;
7107         struct drm_i915_private *dev_priv = to_i915(dev);
7108         const struct intel_limit *limit;
7109         int refclk = 48000;
7110
7111         memset(&crtc_state->dpll_hw_state, 0,
7112                sizeof(crtc_state->dpll_hw_state));
7113
7114         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7115                 if (intel_panel_use_ssc(dev_priv)) {
7116                         refclk = dev_priv->vbt.lvds_ssc_freq;
7117                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7118                 }
7119
7120                 limit = &intel_limits_i8xx_lvds;
7121         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7122                 limit = &intel_limits_i8xx_dvo;
7123         } else {
7124                 limit = &intel_limits_i8xx_dac;
7125         }
7126
7127         if (!crtc_state->clock_set &&
7128             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7129                                  refclk, NULL, &crtc_state->dpll)) {
7130                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7131                 return -EINVAL;
7132         }
7133
7134         i8xx_compute_dpll(crtc, crtc_state, NULL);
7135
7136         return 0;
7137 }
7138
7139 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7140                                   struct intel_crtc_state *crtc_state)
7141 {
7142         struct drm_device *dev = crtc->base.dev;
7143         struct drm_i915_private *dev_priv = to_i915(dev);
7144         const struct intel_limit *limit;
7145         int refclk = 96000;
7146
7147         memset(&crtc_state->dpll_hw_state, 0,
7148                sizeof(crtc_state->dpll_hw_state));
7149
7150         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7151                 if (intel_panel_use_ssc(dev_priv)) {
7152                         refclk = dev_priv->vbt.lvds_ssc_freq;
7153                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7154                 }
7155
7156                 if (intel_is_dual_link_lvds(dev))
7157                         limit = &intel_limits_g4x_dual_channel_lvds;
7158                 else
7159                         limit = &intel_limits_g4x_single_channel_lvds;
7160         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7161                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7162                 limit = &intel_limits_g4x_hdmi;
7163         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7164                 limit = &intel_limits_g4x_sdvo;
7165         } else {
7166                 /* The option is for other outputs */
7167                 limit = &intel_limits_i9xx_sdvo;
7168         }
7169
7170         if (!crtc_state->clock_set &&
7171             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7172                                 refclk, NULL, &crtc_state->dpll)) {
7173                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7174                 return -EINVAL;
7175         }
7176
7177         i9xx_compute_dpll(crtc, crtc_state, NULL);
7178
7179         return 0;
7180 }
7181
7182 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7183                                   struct intel_crtc_state *crtc_state)
7184 {
7185         struct drm_device *dev = crtc->base.dev;
7186         struct drm_i915_private *dev_priv = to_i915(dev);
7187         const struct intel_limit *limit;
7188         int refclk = 96000;
7189
7190         memset(&crtc_state->dpll_hw_state, 0,
7191                sizeof(crtc_state->dpll_hw_state));
7192
7193         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7194                 if (intel_panel_use_ssc(dev_priv)) {
7195                         refclk = dev_priv->vbt.lvds_ssc_freq;
7196                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7197                 }
7198
7199                 limit = &intel_limits_pineview_lvds;
7200         } else {
7201                 limit = &intel_limits_pineview_sdvo;
7202         }
7203
7204         if (!crtc_state->clock_set &&
7205             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7206                                 refclk, NULL, &crtc_state->dpll)) {
7207                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7208                 return -EINVAL;
7209         }
7210
7211         i9xx_compute_dpll(crtc, crtc_state, NULL);
7212
7213         return 0;
7214 }
7215
7216 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7217                                    struct intel_crtc_state *crtc_state)
7218 {
7219         struct drm_device *dev = crtc->base.dev;
7220         struct drm_i915_private *dev_priv = to_i915(dev);
7221         const struct intel_limit *limit;
7222         int refclk = 96000;
7223
7224         memset(&crtc_state->dpll_hw_state, 0,
7225                sizeof(crtc_state->dpll_hw_state));
7226
7227         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7228                 if (intel_panel_use_ssc(dev_priv)) {
7229                         refclk = dev_priv->vbt.lvds_ssc_freq;
7230                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7231                 }
7232
7233                 limit = &intel_limits_i9xx_lvds;
7234         } else {
7235                 limit = &intel_limits_i9xx_sdvo;
7236         }
7237
7238         if (!crtc_state->clock_set &&
7239             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7240                                  refclk, NULL, &crtc_state->dpll)) {
7241                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7242                 return -EINVAL;
7243         }
7244
7245         i9xx_compute_dpll(crtc, crtc_state, NULL);
7246
7247         return 0;
7248 }
7249
7250 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7251                                   struct intel_crtc_state *crtc_state)
7252 {
7253         int refclk = 100000;
7254         const struct intel_limit *limit = &intel_limits_chv;
7255
7256         memset(&crtc_state->dpll_hw_state, 0,
7257                sizeof(crtc_state->dpll_hw_state));
7258
7259         if (!crtc_state->clock_set &&
7260             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7261                                 refclk, NULL, &crtc_state->dpll)) {
7262                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7263                 return -EINVAL;
7264         }
7265
7266         chv_compute_dpll(crtc, crtc_state);
7267
7268         return 0;
7269 }
7270
7271 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7272                                   struct intel_crtc_state *crtc_state)
7273 {
7274         int refclk = 100000;
7275         const struct intel_limit *limit = &intel_limits_vlv;
7276
7277         memset(&crtc_state->dpll_hw_state, 0,
7278                sizeof(crtc_state->dpll_hw_state));
7279
7280         if (!crtc_state->clock_set &&
7281             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7282                                 refclk, NULL, &crtc_state->dpll)) {
7283                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7284                 return -EINVAL;
7285         }
7286
7287         vlv_compute_dpll(crtc, crtc_state);
7288
7289         return 0;
7290 }
7291
7292 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7293                                  struct intel_crtc_state *pipe_config)
7294 {
7295         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7296         uint32_t tmp;
7297
7298         if (INTEL_GEN(dev_priv) <= 3 &&
7299             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7300                 return;
7301
7302         tmp = I915_READ(PFIT_CONTROL);
7303         if (!(tmp & PFIT_ENABLE))
7304                 return;
7305
7306         /* Check whether the pfit is attached to our pipe. */
7307         if (INTEL_GEN(dev_priv) < 4) {
7308                 if (crtc->pipe != PIPE_B)
7309                         return;
7310         } else {
7311                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7312                         return;
7313         }
7314
7315         pipe_config->gmch_pfit.control = tmp;
7316         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7317 }
7318
7319 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7320                                struct intel_crtc_state *pipe_config)
7321 {
7322         struct drm_device *dev = crtc->base.dev;
7323         struct drm_i915_private *dev_priv = to_i915(dev);
7324         int pipe = pipe_config->cpu_transcoder;
7325         struct dpll clock;
7326         u32 mdiv;
7327         int refclk = 100000;
7328
7329         /* In case of DSI, DPLL will not be used */
7330         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7331                 return;
7332
7333         mutex_lock(&dev_priv->sb_lock);
7334         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7335         mutex_unlock(&dev_priv->sb_lock);
7336
7337         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7338         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7339         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7340         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7341         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7342
7343         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7344 }
7345
7346 static void
7347 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7348                               struct intel_initial_plane_config *plane_config)
7349 {
7350         struct drm_device *dev = crtc->base.dev;
7351         struct drm_i915_private *dev_priv = to_i915(dev);
7352         u32 val, base, offset;
7353         int pipe = crtc->pipe, plane = crtc->plane;
7354         int fourcc, pixel_format;
7355         unsigned int aligned_height;
7356         struct drm_framebuffer *fb;
7357         struct intel_framebuffer *intel_fb;
7358
7359         val = I915_READ(DSPCNTR(plane));
7360         if (!(val & DISPLAY_PLANE_ENABLE))
7361                 return;
7362
7363         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7364         if (!intel_fb) {
7365                 DRM_DEBUG_KMS("failed to alloc fb\n");
7366                 return;
7367         }
7368
7369         fb = &intel_fb->base;
7370
7371         fb->dev = dev;
7372
7373         if (INTEL_GEN(dev_priv) >= 4) {
7374                 if (val & DISPPLANE_TILED) {
7375                         plane_config->tiling = I915_TILING_X;
7376                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7377                 }
7378         }
7379
7380         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7381         fourcc = i9xx_format_to_fourcc(pixel_format);
7382         fb->format = drm_format_info(fourcc);
7383
7384         if (INTEL_GEN(dev_priv) >= 4) {
7385                 if (plane_config->tiling)
7386                         offset = I915_READ(DSPTILEOFF(plane));
7387                 else
7388                         offset = I915_READ(DSPLINOFF(plane));
7389                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7390         } else {
7391                 base = I915_READ(DSPADDR(plane));
7392         }
7393         plane_config->base = base;
7394
7395         val = I915_READ(PIPESRC(pipe));
7396         fb->width = ((val >> 16) & 0xfff) + 1;
7397         fb->height = ((val >> 0) & 0xfff) + 1;
7398
7399         val = I915_READ(DSPSTRIDE(pipe));
7400         fb->pitches[0] = val & 0xffffffc0;
7401
7402         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7403
7404         plane_config->size = fb->pitches[0] * aligned_height;
7405
7406         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7407                       pipe_name(pipe), plane, fb->width, fb->height,
7408                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7409                       plane_config->size);
7410
7411         plane_config->fb = intel_fb;
7412 }
7413
7414 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7415                                struct intel_crtc_state *pipe_config)
7416 {
7417         struct drm_device *dev = crtc->base.dev;
7418         struct drm_i915_private *dev_priv = to_i915(dev);
7419         int pipe = pipe_config->cpu_transcoder;
7420         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7421         struct dpll clock;
7422         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7423         int refclk = 100000;
7424
7425         /* In case of DSI, DPLL will not be used */
7426         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7427                 return;
7428
7429         mutex_lock(&dev_priv->sb_lock);
7430         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7431         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7432         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7433         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7434         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7435         mutex_unlock(&dev_priv->sb_lock);
7436
7437         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7438         clock.m2 = (pll_dw0 & 0xff) << 22;
7439         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7440                 clock.m2 |= pll_dw2 & 0x3fffff;
7441         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7442         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7443         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7444
7445         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7446 }
7447
7448 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7449                                  struct intel_crtc_state *pipe_config)
7450 {
7451         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7452         enum intel_display_power_domain power_domain;
7453         uint32_t tmp;
7454         bool ret;
7455
7456         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7457         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7458                 return false;
7459
7460         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7461         pipe_config->shared_dpll = NULL;
7462
7463         ret = false;
7464
7465         tmp = I915_READ(PIPECONF(crtc->pipe));
7466         if (!(tmp & PIPECONF_ENABLE))
7467                 goto out;
7468
7469         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7470             IS_CHERRYVIEW(dev_priv)) {
7471                 switch (tmp & PIPECONF_BPC_MASK) {
7472                 case PIPECONF_6BPC:
7473                         pipe_config->pipe_bpp = 18;
7474                         break;
7475                 case PIPECONF_8BPC:
7476                         pipe_config->pipe_bpp = 24;
7477                         break;
7478                 case PIPECONF_10BPC:
7479                         pipe_config->pipe_bpp = 30;
7480                         break;
7481                 default:
7482                         break;
7483                 }
7484         }
7485
7486         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7487             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7488                 pipe_config->limited_color_range = true;
7489
7490         if (INTEL_GEN(dev_priv) < 4)
7491                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7492
7493         intel_get_pipe_timings(crtc, pipe_config);
7494         intel_get_pipe_src_size(crtc, pipe_config);
7495
7496         i9xx_get_pfit_config(crtc, pipe_config);
7497
7498         if (INTEL_GEN(dev_priv) >= 4) {
7499                 /* No way to read it out on pipes B and C */
7500                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7501                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7502                 else
7503                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7504                 pipe_config->pixel_multiplier =
7505                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7506                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7507                 pipe_config->dpll_hw_state.dpll_md = tmp;
7508         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7509                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7510                 tmp = I915_READ(DPLL(crtc->pipe));
7511                 pipe_config->pixel_multiplier =
7512                         ((tmp & SDVO_MULTIPLIER_MASK)
7513                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7514         } else {
7515                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7516                  * port and will be fixed up in the encoder->get_config
7517                  * function. */
7518                 pipe_config->pixel_multiplier = 1;
7519         }
7520         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7521         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7522                 /*
7523                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7524                  * on 830. Filter it out here so that we don't
7525                  * report errors due to that.
7526                  */
7527                 if (IS_I830(dev_priv))
7528                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7529
7530                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7531                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7532         } else {
7533                 /* Mask out read-only status bits. */
7534                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7535                                                      DPLL_PORTC_READY_MASK |
7536                                                      DPLL_PORTB_READY_MASK);
7537         }
7538
7539         if (IS_CHERRYVIEW(dev_priv))
7540                 chv_crtc_clock_get(crtc, pipe_config);
7541         else if (IS_VALLEYVIEW(dev_priv))
7542                 vlv_crtc_clock_get(crtc, pipe_config);
7543         else
7544                 i9xx_crtc_clock_get(crtc, pipe_config);
7545
7546         /*
7547          * Normally the dotclock is filled in by the encoder .get_config()
7548          * but in case the pipe is enabled w/o any ports we need a sane
7549          * default.
7550          */
7551         pipe_config->base.adjusted_mode.crtc_clock =
7552                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7553
7554         ret = true;
7555
7556 out:
7557         intel_display_power_put(dev_priv, power_domain);
7558
7559         return ret;
7560 }
7561
7562 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7563 {
7564         struct intel_encoder *encoder;
7565         int i;
7566         u32 val, final;
7567         bool has_lvds = false;
7568         bool has_cpu_edp = false;
7569         bool has_panel = false;
7570         bool has_ck505 = false;
7571         bool can_ssc = false;
7572         bool using_ssc_source = false;
7573
7574         /* We need to take the global config into account */
7575         for_each_intel_encoder(&dev_priv->drm, encoder) {
7576                 switch (encoder->type) {
7577                 case INTEL_OUTPUT_LVDS:
7578                         has_panel = true;
7579                         has_lvds = true;
7580                         break;
7581                 case INTEL_OUTPUT_EDP:
7582                         has_panel = true;
7583                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
7584                                 has_cpu_edp = true;
7585                         break;
7586                 default:
7587                         break;
7588                 }
7589         }
7590
7591         if (HAS_PCH_IBX(dev_priv)) {
7592                 has_ck505 = dev_priv->vbt.display_clock_mode;
7593                 can_ssc = has_ck505;
7594         } else {
7595                 has_ck505 = false;
7596                 can_ssc = true;
7597         }
7598
7599         /* Check if any DPLLs are using the SSC source */
7600         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7601                 u32 temp = I915_READ(PCH_DPLL(i));
7602
7603                 if (!(temp & DPLL_VCO_ENABLE))
7604                         continue;
7605
7606                 if ((temp & PLL_REF_INPUT_MASK) ==
7607                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7608                         using_ssc_source = true;
7609                         break;
7610                 }
7611         }
7612
7613         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7614                       has_panel, has_lvds, has_ck505, using_ssc_source);
7615
7616         /* Ironlake: try to setup display ref clock before DPLL
7617          * enabling. This is only under driver's control after
7618          * PCH B stepping, previous chipset stepping should be
7619          * ignoring this setting.
7620          */
7621         val = I915_READ(PCH_DREF_CONTROL);
7622
7623         /* As we must carefully and slowly disable/enable each source in turn,
7624          * compute the final state we want first and check if we need to
7625          * make any changes at all.
7626          */
7627         final = val;
7628         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7629         if (has_ck505)
7630                 final |= DREF_NONSPREAD_CK505_ENABLE;
7631         else
7632                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7633
7634         final &= ~DREF_SSC_SOURCE_MASK;
7635         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7636         final &= ~DREF_SSC1_ENABLE;
7637
7638         if (has_panel) {
7639                 final |= DREF_SSC_SOURCE_ENABLE;
7640
7641                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7642                         final |= DREF_SSC1_ENABLE;
7643
7644                 if (has_cpu_edp) {
7645                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7646                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7647                         else
7648                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7649                 } else
7650                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7651         } else if (using_ssc_source) {
7652                 final |= DREF_SSC_SOURCE_ENABLE;
7653                 final |= DREF_SSC1_ENABLE;
7654         }
7655
7656         if (final == val)
7657                 return;
7658
7659         /* Always enable nonspread source */
7660         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7661
7662         if (has_ck505)
7663                 val |= DREF_NONSPREAD_CK505_ENABLE;
7664         else
7665                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7666
7667         if (has_panel) {
7668                 val &= ~DREF_SSC_SOURCE_MASK;
7669                 val |= DREF_SSC_SOURCE_ENABLE;
7670
7671                 /* SSC must be turned on before enabling the CPU output  */
7672                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7673                         DRM_DEBUG_KMS("Using SSC on panel\n");
7674                         val |= DREF_SSC1_ENABLE;
7675                 } else
7676                         val &= ~DREF_SSC1_ENABLE;
7677
7678                 /* Get SSC going before enabling the outputs */
7679                 I915_WRITE(PCH_DREF_CONTROL, val);
7680                 POSTING_READ(PCH_DREF_CONTROL);
7681                 udelay(200);
7682
7683                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7684
7685                 /* Enable CPU source on CPU attached eDP */
7686                 if (has_cpu_edp) {
7687                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7688                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7689                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7690                         } else
7691                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7692                 } else
7693                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7694
7695                 I915_WRITE(PCH_DREF_CONTROL, val);
7696                 POSTING_READ(PCH_DREF_CONTROL);
7697                 udelay(200);
7698         } else {
7699                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7700
7701                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7702
7703                 /* Turn off CPU output */
7704                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7705
7706                 I915_WRITE(PCH_DREF_CONTROL, val);
7707                 POSTING_READ(PCH_DREF_CONTROL);
7708                 udelay(200);
7709
7710                 if (!using_ssc_source) {
7711                         DRM_DEBUG_KMS("Disabling SSC source\n");
7712
7713                         /* Turn off the SSC source */
7714                         val &= ~DREF_SSC_SOURCE_MASK;
7715                         val |= DREF_SSC_SOURCE_DISABLE;
7716
7717                         /* Turn off SSC1 */
7718                         val &= ~DREF_SSC1_ENABLE;
7719
7720                         I915_WRITE(PCH_DREF_CONTROL, val);
7721                         POSTING_READ(PCH_DREF_CONTROL);
7722                         udelay(200);
7723                 }
7724         }
7725
7726         BUG_ON(val != final);
7727 }
7728
7729 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7730 {
7731         uint32_t tmp;
7732
7733         tmp = I915_READ(SOUTH_CHICKEN2);
7734         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7735         I915_WRITE(SOUTH_CHICKEN2, tmp);
7736
7737         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7738                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7739                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7740
7741         tmp = I915_READ(SOUTH_CHICKEN2);
7742         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7743         I915_WRITE(SOUTH_CHICKEN2, tmp);
7744
7745         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7746                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7747                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7748 }
7749
7750 /* WaMPhyProgramming:hsw */
7751 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7752 {
7753         uint32_t tmp;
7754
7755         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7756         tmp &= ~(0xFF << 24);
7757         tmp |= (0x12 << 24);
7758         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7759
7760         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7761         tmp |= (1 << 11);
7762         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7763
7764         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7765         tmp |= (1 << 11);
7766         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7767
7768         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7769         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7770         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7771
7772         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7773         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7774         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7775
7776         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7777         tmp &= ~(7 << 13);
7778         tmp |= (5 << 13);
7779         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7780
7781         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7782         tmp &= ~(7 << 13);
7783         tmp |= (5 << 13);
7784         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7785
7786         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7787         tmp &= ~0xFF;
7788         tmp |= 0x1C;
7789         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7790
7791         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7792         tmp &= ~0xFF;
7793         tmp |= 0x1C;
7794         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7795
7796         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7797         tmp &= ~(0xFF << 16);
7798         tmp |= (0x1C << 16);
7799         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7800
7801         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7802         tmp &= ~(0xFF << 16);
7803         tmp |= (0x1C << 16);
7804         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7805
7806         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7807         tmp |= (1 << 27);
7808         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7809
7810         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7811         tmp |= (1 << 27);
7812         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7813
7814         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7815         tmp &= ~(0xF << 28);
7816         tmp |= (4 << 28);
7817         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7818
7819         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7820         tmp &= ~(0xF << 28);
7821         tmp |= (4 << 28);
7822         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7823 }
7824
7825 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7826  * Programming" based on the parameters passed:
7827  * - Sequence to enable CLKOUT_DP
7828  * - Sequence to enable CLKOUT_DP without spread
7829  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7830  */
7831 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
7832                                  bool with_spread, bool with_fdi)
7833 {
7834         uint32_t reg, tmp;
7835
7836         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7837                 with_spread = true;
7838         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
7839             with_fdi, "LP PCH doesn't have FDI\n"))
7840                 with_fdi = false;
7841
7842         mutex_lock(&dev_priv->sb_lock);
7843
7844         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7845         tmp &= ~SBI_SSCCTL_DISABLE;
7846         tmp |= SBI_SSCCTL_PATHALT;
7847         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7848
7849         udelay(24);
7850
7851         if (with_spread) {
7852                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7853                 tmp &= ~SBI_SSCCTL_PATHALT;
7854                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7855
7856                 if (with_fdi) {
7857                         lpt_reset_fdi_mphy(dev_priv);
7858                         lpt_program_fdi_mphy(dev_priv);
7859                 }
7860         }
7861
7862         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7863         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7864         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7865         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7866
7867         mutex_unlock(&dev_priv->sb_lock);
7868 }
7869
7870 /* Sequence to disable CLKOUT_DP */
7871 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
7872 {
7873         uint32_t reg, tmp;
7874
7875         mutex_lock(&dev_priv->sb_lock);
7876
7877         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7878         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7879         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7880         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7881
7882         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7883         if (!(tmp & SBI_SSCCTL_DISABLE)) {
7884                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
7885                         tmp |= SBI_SSCCTL_PATHALT;
7886                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7887                         udelay(32);
7888                 }
7889                 tmp |= SBI_SSCCTL_DISABLE;
7890                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7891         }
7892
7893         mutex_unlock(&dev_priv->sb_lock);
7894 }
7895
7896 #define BEND_IDX(steps) ((50 + (steps)) / 5)
7897
7898 static const uint16_t sscdivintphase[] = {
7899         [BEND_IDX( 50)] = 0x3B23,
7900         [BEND_IDX( 45)] = 0x3B23,
7901         [BEND_IDX( 40)] = 0x3C23,
7902         [BEND_IDX( 35)] = 0x3C23,
7903         [BEND_IDX( 30)] = 0x3D23,
7904         [BEND_IDX( 25)] = 0x3D23,
7905         [BEND_IDX( 20)] = 0x3E23,
7906         [BEND_IDX( 15)] = 0x3E23,
7907         [BEND_IDX( 10)] = 0x3F23,
7908         [BEND_IDX(  5)] = 0x3F23,
7909         [BEND_IDX(  0)] = 0x0025,
7910         [BEND_IDX( -5)] = 0x0025,
7911         [BEND_IDX(-10)] = 0x0125,
7912         [BEND_IDX(-15)] = 0x0125,
7913         [BEND_IDX(-20)] = 0x0225,
7914         [BEND_IDX(-25)] = 0x0225,
7915         [BEND_IDX(-30)] = 0x0325,
7916         [BEND_IDX(-35)] = 0x0325,
7917         [BEND_IDX(-40)] = 0x0425,
7918         [BEND_IDX(-45)] = 0x0425,
7919         [BEND_IDX(-50)] = 0x0525,
7920 };
7921
7922 /*
7923  * Bend CLKOUT_DP
7924  * steps -50 to 50 inclusive, in steps of 5
7925  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
7926  * change in clock period = -(steps / 10) * 5.787 ps
7927  */
7928 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
7929 {
7930         uint32_t tmp;
7931         int idx = BEND_IDX(steps);
7932
7933         if (WARN_ON(steps % 5 != 0))
7934                 return;
7935
7936         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
7937                 return;
7938
7939         mutex_lock(&dev_priv->sb_lock);
7940
7941         if (steps % 10 != 0)
7942                 tmp = 0xAAAAAAAB;
7943         else
7944                 tmp = 0x00000000;
7945         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
7946
7947         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
7948         tmp &= 0xffff0000;
7949         tmp |= sscdivintphase[idx];
7950         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
7951
7952         mutex_unlock(&dev_priv->sb_lock);
7953 }
7954
7955 #undef BEND_IDX
7956
7957 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
7958 {
7959         struct intel_encoder *encoder;
7960         bool has_vga = false;
7961
7962         for_each_intel_encoder(&dev_priv->drm, encoder) {
7963                 switch (encoder->type) {
7964                 case INTEL_OUTPUT_ANALOG:
7965                         has_vga = true;
7966                         break;
7967                 default:
7968                         break;
7969                 }
7970         }
7971
7972         if (has_vga) {
7973                 lpt_bend_clkout_dp(dev_priv, 0);
7974                 lpt_enable_clkout_dp(dev_priv, true, true);
7975         } else {
7976                 lpt_disable_clkout_dp(dev_priv);
7977         }
7978 }
7979
7980 /*
7981  * Initialize reference clocks when the driver loads
7982  */
7983 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
7984 {
7985         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
7986                 ironlake_init_pch_refclk(dev_priv);
7987         else if (HAS_PCH_LPT(dev_priv))
7988                 lpt_init_pch_refclk(dev_priv);
7989 }
7990
7991 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
7992 {
7993         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
7994         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7995         int pipe = intel_crtc->pipe;
7996         uint32_t val;
7997
7998         val = 0;
7999
8000         switch (intel_crtc->config->pipe_bpp) {
8001         case 18:
8002                 val |= PIPECONF_6BPC;
8003                 break;
8004         case 24:
8005                 val |= PIPECONF_8BPC;
8006                 break;
8007         case 30:
8008                 val |= PIPECONF_10BPC;
8009                 break;
8010         case 36:
8011                 val |= PIPECONF_12BPC;
8012                 break;
8013         default:
8014                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8015                 BUG();
8016         }
8017
8018         if (intel_crtc->config->dither)
8019                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8020
8021         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8022                 val |= PIPECONF_INTERLACED_ILK;
8023         else
8024                 val |= PIPECONF_PROGRESSIVE;
8025
8026         if (intel_crtc->config->limited_color_range)
8027                 val |= PIPECONF_COLOR_RANGE_SELECT;
8028
8029         I915_WRITE(PIPECONF(pipe), val);
8030         POSTING_READ(PIPECONF(pipe));
8031 }
8032
8033 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8034 {
8035         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8036         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8037         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8038         u32 val = 0;
8039
8040         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8041                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8042
8043         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8044                 val |= PIPECONF_INTERLACED_ILK;
8045         else
8046                 val |= PIPECONF_PROGRESSIVE;
8047
8048         I915_WRITE(PIPECONF(cpu_transcoder), val);
8049         POSTING_READ(PIPECONF(cpu_transcoder));
8050 }
8051
8052 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8053 {
8054         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8055         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8056
8057         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8058                 u32 val = 0;
8059
8060                 switch (intel_crtc->config->pipe_bpp) {
8061                 case 18:
8062                         val |= PIPEMISC_DITHER_6_BPC;
8063                         break;
8064                 case 24:
8065                         val |= PIPEMISC_DITHER_8_BPC;
8066                         break;
8067                 case 30:
8068                         val |= PIPEMISC_DITHER_10_BPC;
8069                         break;
8070                 case 36:
8071                         val |= PIPEMISC_DITHER_12_BPC;
8072                         break;
8073                 default:
8074                         /* Case prevented by pipe_config_set_bpp. */
8075                         BUG();
8076                 }
8077
8078                 if (intel_crtc->config->dither)
8079                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8080
8081                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8082         }
8083 }
8084
8085 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8086 {
8087         /*
8088          * Account for spread spectrum to avoid
8089          * oversubscribing the link. Max center spread
8090          * is 2.5%; use 5% for safety's sake.
8091          */
8092         u32 bps = target_clock * bpp * 21 / 20;
8093         return DIV_ROUND_UP(bps, link_bw * 8);
8094 }
8095
8096 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8097 {
8098         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8099 }
8100
8101 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8102                                   struct intel_crtc_state *crtc_state,
8103                                   struct dpll *reduced_clock)
8104 {
8105         struct drm_crtc *crtc = &intel_crtc->base;
8106         struct drm_device *dev = crtc->dev;
8107         struct drm_i915_private *dev_priv = to_i915(dev);
8108         u32 dpll, fp, fp2;
8109         int factor;
8110
8111         /* Enable autotuning of the PLL clock (if permissible) */
8112         factor = 21;
8113         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8114                 if ((intel_panel_use_ssc(dev_priv) &&
8115                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8116                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8117                         factor = 25;
8118         } else if (crtc_state->sdvo_tv_clock)
8119                 factor = 20;
8120
8121         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8122
8123         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8124                 fp |= FP_CB_TUNE;
8125
8126         if (reduced_clock) {
8127                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8128
8129                 if (reduced_clock->m < factor * reduced_clock->n)
8130                         fp2 |= FP_CB_TUNE;
8131         } else {
8132                 fp2 = fp;
8133         }
8134
8135         dpll = 0;
8136
8137         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8138                 dpll |= DPLLB_MODE_LVDS;
8139         else
8140                 dpll |= DPLLB_MODE_DAC_SERIAL;
8141
8142         dpll |= (crtc_state->pixel_multiplier - 1)
8143                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8144
8145         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8146             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8147                 dpll |= DPLL_SDVO_HIGH_SPEED;
8148
8149         if (intel_crtc_has_dp_encoder(crtc_state))
8150                 dpll |= DPLL_SDVO_HIGH_SPEED;
8151
8152         /*
8153          * The high speed IO clock is only really required for
8154          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8155          * possible to share the DPLL between CRT and HDMI. Enabling
8156          * the clock needlessly does no real harm, except use up a
8157          * bit of power potentially.
8158          *
8159          * We'll limit this to IVB with 3 pipes, since it has only two
8160          * DPLLs and so DPLL sharing is the only way to get three pipes
8161          * driving PCH ports at the same time. On SNB we could do this,
8162          * and potentially avoid enabling the second DPLL, but it's not
8163          * clear if it''s a win or loss power wise. No point in doing
8164          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8165          */
8166         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8167             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8168                 dpll |= DPLL_SDVO_HIGH_SPEED;
8169
8170         /* compute bitmask from p1 value */
8171         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8172         /* also FPA1 */
8173         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8174
8175         switch (crtc_state->dpll.p2) {
8176         case 5:
8177                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8178                 break;
8179         case 7:
8180                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8181                 break;
8182         case 10:
8183                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8184                 break;
8185         case 14:
8186                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8187                 break;
8188         }
8189
8190         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8191             intel_panel_use_ssc(dev_priv))
8192                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8193         else
8194                 dpll |= PLL_REF_INPUT_DREFCLK;
8195
8196         dpll |= DPLL_VCO_ENABLE;
8197
8198         crtc_state->dpll_hw_state.dpll = dpll;
8199         crtc_state->dpll_hw_state.fp0 = fp;
8200         crtc_state->dpll_hw_state.fp1 = fp2;
8201 }
8202
8203 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8204                                        struct intel_crtc_state *crtc_state)
8205 {
8206         struct drm_device *dev = crtc->base.dev;
8207         struct drm_i915_private *dev_priv = to_i915(dev);
8208         const struct intel_limit *limit;
8209         int refclk = 120000;
8210
8211         memset(&crtc_state->dpll_hw_state, 0,
8212                sizeof(crtc_state->dpll_hw_state));
8213
8214         crtc->lowfreq_avail = false;
8215
8216         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8217         if (!crtc_state->has_pch_encoder)
8218                 return 0;
8219
8220         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8221                 if (intel_panel_use_ssc(dev_priv)) {
8222                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8223                                       dev_priv->vbt.lvds_ssc_freq);
8224                         refclk = dev_priv->vbt.lvds_ssc_freq;
8225                 }
8226
8227                 if (intel_is_dual_link_lvds(dev)) {
8228                         if (refclk == 100000)
8229                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8230                         else
8231                                 limit = &intel_limits_ironlake_dual_lvds;
8232                 } else {
8233                         if (refclk == 100000)
8234                                 limit = &intel_limits_ironlake_single_lvds_100m;
8235                         else
8236                                 limit = &intel_limits_ironlake_single_lvds;
8237                 }
8238         } else {
8239                 limit = &intel_limits_ironlake_dac;
8240         }
8241
8242         if (!crtc_state->clock_set &&
8243             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8244                                 refclk, NULL, &crtc_state->dpll)) {
8245                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8246                 return -EINVAL;
8247         }
8248
8249         ironlake_compute_dpll(crtc, crtc_state, NULL);
8250
8251         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8252                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8253                                  pipe_name(crtc->pipe));
8254                 return -EINVAL;
8255         }
8256
8257         return 0;
8258 }
8259
8260 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8261                                          struct intel_link_m_n *m_n)
8262 {
8263         struct drm_device *dev = crtc->base.dev;
8264         struct drm_i915_private *dev_priv = to_i915(dev);
8265         enum pipe pipe = crtc->pipe;
8266
8267         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8268         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8269         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8270                 & ~TU_SIZE_MASK;
8271         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8272         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8273                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8274 }
8275
8276 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8277                                          enum transcoder transcoder,
8278                                          struct intel_link_m_n *m_n,
8279                                          struct intel_link_m_n *m2_n2)
8280 {
8281         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8282         enum pipe pipe = crtc->pipe;
8283
8284         if (INTEL_GEN(dev_priv) >= 5) {
8285                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8286                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8287                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8288                         & ~TU_SIZE_MASK;
8289                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8290                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8291                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8292                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8293                  * gen < 8) and if DRRS is supported (to make sure the
8294                  * registers are not unnecessarily read).
8295                  */
8296                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8297                         crtc->config->has_drrs) {
8298                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8299                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8300                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8301                                         & ~TU_SIZE_MASK;
8302                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8303                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8304                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8305                 }
8306         } else {
8307                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8308                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8309                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8310                         & ~TU_SIZE_MASK;
8311                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8312                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8313                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8314         }
8315 }
8316
8317 void intel_dp_get_m_n(struct intel_crtc *crtc,
8318                       struct intel_crtc_state *pipe_config)
8319 {
8320         if (pipe_config->has_pch_encoder)
8321                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8322         else
8323                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8324                                              &pipe_config->dp_m_n,
8325                                              &pipe_config->dp_m2_n2);
8326 }
8327
8328 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8329                                         struct intel_crtc_state *pipe_config)
8330 {
8331         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8332                                      &pipe_config->fdi_m_n, NULL);
8333 }
8334
8335 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8336                                     struct intel_crtc_state *pipe_config)
8337 {
8338         struct drm_device *dev = crtc->base.dev;
8339         struct drm_i915_private *dev_priv = to_i915(dev);
8340         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8341         uint32_t ps_ctrl = 0;
8342         int id = -1;
8343         int i;
8344
8345         /* find scaler attached to this pipe */
8346         for (i = 0; i < crtc->num_scalers; i++) {
8347                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8348                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8349                         id = i;
8350                         pipe_config->pch_pfit.enabled = true;
8351                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8352                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8353                         break;
8354                 }
8355         }
8356
8357         scaler_state->scaler_id = id;
8358         if (id >= 0) {
8359                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8360         } else {
8361                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8362         }
8363 }
8364
8365 static void
8366 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8367                                  struct intel_initial_plane_config *plane_config)
8368 {
8369         struct drm_device *dev = crtc->base.dev;
8370         struct drm_i915_private *dev_priv = to_i915(dev);
8371         u32 val, base, offset, stride_mult, tiling;
8372         int pipe = crtc->pipe;
8373         int fourcc, pixel_format;
8374         unsigned int aligned_height;
8375         struct drm_framebuffer *fb;
8376         struct intel_framebuffer *intel_fb;
8377
8378         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8379         if (!intel_fb) {
8380                 DRM_DEBUG_KMS("failed to alloc fb\n");
8381                 return;
8382         }
8383
8384         fb = &intel_fb->base;
8385
8386         fb->dev = dev;
8387
8388         val = I915_READ(PLANE_CTL(pipe, 0));
8389         if (!(val & PLANE_CTL_ENABLE))
8390                 goto error;
8391
8392         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8393         fourcc = skl_format_to_fourcc(pixel_format,
8394                                       val & PLANE_CTL_ORDER_RGBX,
8395                                       val & PLANE_CTL_ALPHA_MASK);
8396         fb->format = drm_format_info(fourcc);
8397
8398         tiling = val & PLANE_CTL_TILED_MASK;
8399         switch (tiling) {
8400         case PLANE_CTL_TILED_LINEAR:
8401                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8402                 break;
8403         case PLANE_CTL_TILED_X:
8404                 plane_config->tiling = I915_TILING_X;
8405                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8406                 break;
8407         case PLANE_CTL_TILED_Y:
8408                 fb->modifier = I915_FORMAT_MOD_Y_TILED;
8409                 break;
8410         case PLANE_CTL_TILED_YF:
8411                 fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8412                 break;
8413         default:
8414                 MISSING_CASE(tiling);
8415                 goto error;
8416         }
8417
8418         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
8419         plane_config->base = base;
8420
8421         offset = I915_READ(PLANE_OFFSET(pipe, 0));
8422
8423         val = I915_READ(PLANE_SIZE(pipe, 0));
8424         fb->height = ((val >> 16) & 0xfff) + 1;
8425         fb->width = ((val >> 0) & 0x1fff) + 1;
8426
8427         val = I915_READ(PLANE_STRIDE(pipe, 0));
8428         stride_mult = intel_fb_stride_alignment(fb, 0);
8429         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8430
8431         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8432
8433         plane_config->size = fb->pitches[0] * aligned_height;
8434
8435         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8436                       pipe_name(pipe), fb->width, fb->height,
8437                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8438                       plane_config->size);
8439
8440         plane_config->fb = intel_fb;
8441         return;
8442
8443 error:
8444         kfree(intel_fb);
8445 }
8446
8447 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8448                                      struct intel_crtc_state *pipe_config)
8449 {
8450         struct drm_device *dev = crtc->base.dev;
8451         struct drm_i915_private *dev_priv = to_i915(dev);
8452         uint32_t tmp;
8453
8454         tmp = I915_READ(PF_CTL(crtc->pipe));
8455
8456         if (tmp & PF_ENABLE) {
8457                 pipe_config->pch_pfit.enabled = true;
8458                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8459                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8460
8461                 /* We currently do not free assignements of panel fitters on
8462                  * ivb/hsw (since we don't use the higher upscaling modes which
8463                  * differentiates them) so just WARN about this case for now. */
8464                 if (IS_GEN7(dev_priv)) {
8465                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8466                                 PF_PIPE_SEL_IVB(crtc->pipe));
8467                 }
8468         }
8469 }
8470
8471 static void
8472 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
8473                                   struct intel_initial_plane_config *plane_config)
8474 {
8475         struct drm_device *dev = crtc->base.dev;
8476         struct drm_i915_private *dev_priv = to_i915(dev);
8477         u32 val, base, offset;
8478         int pipe = crtc->pipe;
8479         int fourcc, pixel_format;
8480         unsigned int aligned_height;
8481         struct drm_framebuffer *fb;
8482         struct intel_framebuffer *intel_fb;
8483
8484         val = I915_READ(DSPCNTR(pipe));
8485         if (!(val & DISPLAY_PLANE_ENABLE))
8486                 return;
8487
8488         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8489         if (!intel_fb) {
8490                 DRM_DEBUG_KMS("failed to alloc fb\n");
8491                 return;
8492         }
8493
8494         fb = &intel_fb->base;
8495
8496         fb->dev = dev;
8497
8498         if (INTEL_GEN(dev_priv) >= 4) {
8499                 if (val & DISPPLANE_TILED) {
8500                         plane_config->tiling = I915_TILING_X;
8501                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8502                 }
8503         }
8504
8505         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8506         fourcc = i9xx_format_to_fourcc(pixel_format);
8507         fb->format = drm_format_info(fourcc);
8508
8509         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
8510         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8511                 offset = I915_READ(DSPOFFSET(pipe));
8512         } else {
8513                 if (plane_config->tiling)
8514                         offset = I915_READ(DSPTILEOFF(pipe));
8515                 else
8516                         offset = I915_READ(DSPLINOFF(pipe));
8517         }
8518         plane_config->base = base;
8519
8520         val = I915_READ(PIPESRC(pipe));
8521         fb->width = ((val >> 16) & 0xfff) + 1;
8522         fb->height = ((val >> 0) & 0xfff) + 1;
8523
8524         val = I915_READ(DSPSTRIDE(pipe));
8525         fb->pitches[0] = val & 0xffffffc0;
8526
8527         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8528
8529         plane_config->size = fb->pitches[0] * aligned_height;
8530
8531         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8532                       pipe_name(pipe), fb->width, fb->height,
8533                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8534                       plane_config->size);
8535
8536         plane_config->fb = intel_fb;
8537 }
8538
8539 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8540                                      struct intel_crtc_state *pipe_config)
8541 {
8542         struct drm_device *dev = crtc->base.dev;
8543         struct drm_i915_private *dev_priv = to_i915(dev);
8544         enum intel_display_power_domain power_domain;
8545         uint32_t tmp;
8546         bool ret;
8547
8548         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8549         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8550                 return false;
8551
8552         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8553         pipe_config->shared_dpll = NULL;
8554
8555         ret = false;
8556         tmp = I915_READ(PIPECONF(crtc->pipe));
8557         if (!(tmp & PIPECONF_ENABLE))
8558                 goto out;
8559
8560         switch (tmp & PIPECONF_BPC_MASK) {
8561         case PIPECONF_6BPC:
8562                 pipe_config->pipe_bpp = 18;
8563                 break;
8564         case PIPECONF_8BPC:
8565                 pipe_config->pipe_bpp = 24;
8566                 break;
8567         case PIPECONF_10BPC:
8568                 pipe_config->pipe_bpp = 30;
8569                 break;
8570         case PIPECONF_12BPC:
8571                 pipe_config->pipe_bpp = 36;
8572                 break;
8573         default:
8574                 break;
8575         }
8576
8577         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8578                 pipe_config->limited_color_range = true;
8579
8580         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8581                 struct intel_shared_dpll *pll;
8582                 enum intel_dpll_id pll_id;
8583
8584                 pipe_config->has_pch_encoder = true;
8585
8586                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8587                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8588                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8589
8590                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8591
8592                 if (HAS_PCH_IBX(dev_priv)) {
8593                         /*
8594                          * The pipe->pch transcoder and pch transcoder->pll
8595                          * mapping is fixed.
8596                          */
8597                         pll_id = (enum intel_dpll_id) crtc->pipe;
8598                 } else {
8599                         tmp = I915_READ(PCH_DPLL_SEL);
8600                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8601                                 pll_id = DPLL_ID_PCH_PLL_B;
8602                         else
8603                                 pll_id= DPLL_ID_PCH_PLL_A;
8604                 }
8605
8606                 pipe_config->shared_dpll =
8607                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8608                 pll = pipe_config->shared_dpll;
8609
8610                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
8611                                                  &pipe_config->dpll_hw_state));
8612
8613                 tmp = pipe_config->dpll_hw_state.dpll;
8614                 pipe_config->pixel_multiplier =
8615                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8616                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8617
8618                 ironlake_pch_clock_get(crtc, pipe_config);
8619         } else {
8620                 pipe_config->pixel_multiplier = 1;
8621         }
8622
8623         intel_get_pipe_timings(crtc, pipe_config);
8624         intel_get_pipe_src_size(crtc, pipe_config);
8625
8626         ironlake_get_pfit_config(crtc, pipe_config);
8627
8628         ret = true;
8629
8630 out:
8631         intel_display_power_put(dev_priv, power_domain);
8632
8633         return ret;
8634 }
8635
8636 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8637 {
8638         struct drm_device *dev = &dev_priv->drm;
8639         struct intel_crtc *crtc;
8640
8641         for_each_intel_crtc(dev, crtc)
8642                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8643                      pipe_name(crtc->pipe));
8644
8645         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
8646         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8647         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8648         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8649         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8650         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8651              "CPU PWM1 enabled\n");
8652         if (IS_HASWELL(dev_priv))
8653                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8654                      "CPU PWM2 enabled\n");
8655         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8656              "PCH PWM1 enabled\n");
8657         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8658              "Utility pin enabled\n");
8659         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8660
8661         /*
8662          * In theory we can still leave IRQs enabled, as long as only the HPD
8663          * interrupts remain enabled. We used to check for that, but since it's
8664          * gen-specific and since we only disable LCPLL after we fully disable
8665          * the interrupts, the check below should be enough.
8666          */
8667         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8668 }
8669
8670 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8671 {
8672         if (IS_HASWELL(dev_priv))
8673                 return I915_READ(D_COMP_HSW);
8674         else
8675                 return I915_READ(D_COMP_BDW);
8676 }
8677
8678 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8679 {
8680         if (IS_HASWELL(dev_priv)) {
8681                 mutex_lock(&dev_priv->rps.hw_lock);
8682                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8683                                             val))
8684                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8685                 mutex_unlock(&dev_priv->rps.hw_lock);
8686         } else {
8687                 I915_WRITE(D_COMP_BDW, val);
8688                 POSTING_READ(D_COMP_BDW);
8689         }
8690 }
8691
8692 /*
8693  * This function implements pieces of two sequences from BSpec:
8694  * - Sequence for display software to disable LCPLL
8695  * - Sequence for display software to allow package C8+
8696  * The steps implemented here are just the steps that actually touch the LCPLL
8697  * register. Callers should take care of disabling all the display engine
8698  * functions, doing the mode unset, fixing interrupts, etc.
8699  */
8700 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8701                               bool switch_to_fclk, bool allow_power_down)
8702 {
8703         uint32_t val;
8704
8705         assert_can_disable_lcpll(dev_priv);
8706
8707         val = I915_READ(LCPLL_CTL);
8708
8709         if (switch_to_fclk) {
8710                 val |= LCPLL_CD_SOURCE_FCLK;
8711                 I915_WRITE(LCPLL_CTL, val);
8712
8713                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8714                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8715                         DRM_ERROR("Switching to FCLK failed\n");
8716
8717                 val = I915_READ(LCPLL_CTL);
8718         }
8719
8720         val |= LCPLL_PLL_DISABLE;
8721         I915_WRITE(LCPLL_CTL, val);
8722         POSTING_READ(LCPLL_CTL);
8723
8724         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8725                 DRM_ERROR("LCPLL still locked\n");
8726
8727         val = hsw_read_dcomp(dev_priv);
8728         val |= D_COMP_COMP_DISABLE;
8729         hsw_write_dcomp(dev_priv, val);
8730         ndelay(100);
8731
8732         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8733                      1))
8734                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8735
8736         if (allow_power_down) {
8737                 val = I915_READ(LCPLL_CTL);
8738                 val |= LCPLL_POWER_DOWN_ALLOW;
8739                 I915_WRITE(LCPLL_CTL, val);
8740                 POSTING_READ(LCPLL_CTL);
8741         }
8742 }
8743
8744 /*
8745  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8746  * source.
8747  */
8748 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8749 {
8750         uint32_t val;
8751
8752         val = I915_READ(LCPLL_CTL);
8753
8754         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8755                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8756                 return;
8757
8758         /*
8759          * Make sure we're not on PC8 state before disabling PC8, otherwise
8760          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8761          */
8762         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8763
8764         if (val & LCPLL_POWER_DOWN_ALLOW) {
8765                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8766                 I915_WRITE(LCPLL_CTL, val);
8767                 POSTING_READ(LCPLL_CTL);
8768         }
8769
8770         val = hsw_read_dcomp(dev_priv);
8771         val |= D_COMP_COMP_FORCE;
8772         val &= ~D_COMP_COMP_DISABLE;
8773         hsw_write_dcomp(dev_priv, val);
8774
8775         val = I915_READ(LCPLL_CTL);
8776         val &= ~LCPLL_PLL_DISABLE;
8777         I915_WRITE(LCPLL_CTL, val);
8778
8779         if (intel_wait_for_register(dev_priv,
8780                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8781                                     5))
8782                 DRM_ERROR("LCPLL not locked yet\n");
8783
8784         if (val & LCPLL_CD_SOURCE_FCLK) {
8785                 val = I915_READ(LCPLL_CTL);
8786                 val &= ~LCPLL_CD_SOURCE_FCLK;
8787                 I915_WRITE(LCPLL_CTL, val);
8788
8789                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8790                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8791                         DRM_ERROR("Switching back to LCPLL failed\n");
8792         }
8793
8794         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8795         intel_update_cdclk(dev_priv);
8796 }
8797
8798 /*
8799  * Package states C8 and deeper are really deep PC states that can only be
8800  * reached when all the devices on the system allow it, so even if the graphics
8801  * device allows PC8+, it doesn't mean the system will actually get to these
8802  * states. Our driver only allows PC8+ when going into runtime PM.
8803  *
8804  * The requirements for PC8+ are that all the outputs are disabled, the power
8805  * well is disabled and most interrupts are disabled, and these are also
8806  * requirements for runtime PM. When these conditions are met, we manually do
8807  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8808  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8809  * hang the machine.
8810  *
8811  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8812  * the state of some registers, so when we come back from PC8+ we need to
8813  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8814  * need to take care of the registers kept by RC6. Notice that this happens even
8815  * if we don't put the device in PCI D3 state (which is what currently happens
8816  * because of the runtime PM support).
8817  *
8818  * For more, read "Display Sequences for Package C8" on the hardware
8819  * documentation.
8820  */
8821 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8822 {
8823         uint32_t val;
8824
8825         DRM_DEBUG_KMS("Enabling package C8+\n");
8826
8827         if (HAS_PCH_LPT_LP(dev_priv)) {
8828                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8829                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8830                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8831         }
8832
8833         lpt_disable_clkout_dp(dev_priv);
8834         hsw_disable_lcpll(dev_priv, true, true);
8835 }
8836
8837 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8838 {
8839         uint32_t val;
8840
8841         DRM_DEBUG_KMS("Disabling package C8+\n");
8842
8843         hsw_restore_lcpll(dev_priv);
8844         lpt_init_pch_refclk(dev_priv);
8845
8846         if (HAS_PCH_LPT_LP(dev_priv)) {
8847                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8848                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
8849                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8850         }
8851 }
8852
8853 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
8854                                       struct intel_crtc_state *crtc_state)
8855 {
8856         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
8857                 struct intel_encoder *encoder =
8858                         intel_ddi_get_crtc_new_encoder(crtc_state);
8859
8860                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
8861                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8862                                          pipe_name(crtc->pipe));
8863                         return -EINVAL;
8864                 }
8865         }
8866
8867         crtc->lowfreq_avail = false;
8868
8869         return 0;
8870 }
8871
8872 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
8873                                    enum port port,
8874                                    struct intel_crtc_state *pipe_config)
8875 {
8876         enum intel_dpll_id id;
8877         u32 temp;
8878
8879         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
8880         id = temp >> (port * 2);
8881
8882         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
8883                 return;
8884
8885         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8886 }
8887
8888 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
8889                                 enum port port,
8890                                 struct intel_crtc_state *pipe_config)
8891 {
8892         enum intel_dpll_id id;
8893
8894         switch (port) {
8895         case PORT_A:
8896                 id = DPLL_ID_SKL_DPLL0;
8897                 break;
8898         case PORT_B:
8899                 id = DPLL_ID_SKL_DPLL1;
8900                 break;
8901         case PORT_C:
8902                 id = DPLL_ID_SKL_DPLL2;
8903                 break;
8904         default:
8905                 DRM_ERROR("Incorrect port type\n");
8906                 return;
8907         }
8908
8909         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8910 }
8911
8912 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
8913                                 enum port port,
8914                                 struct intel_crtc_state *pipe_config)
8915 {
8916         enum intel_dpll_id id;
8917         u32 temp;
8918
8919         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
8920         id = temp >> (port * 3 + 1);
8921
8922         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
8923                 return;
8924
8925         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8926 }
8927
8928 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
8929                                 enum port port,
8930                                 struct intel_crtc_state *pipe_config)
8931 {
8932         enum intel_dpll_id id;
8933         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
8934
8935         switch (ddi_pll_sel) {
8936         case PORT_CLK_SEL_WRPLL1:
8937                 id = DPLL_ID_WRPLL1;
8938                 break;
8939         case PORT_CLK_SEL_WRPLL2:
8940                 id = DPLL_ID_WRPLL2;
8941                 break;
8942         case PORT_CLK_SEL_SPLL:
8943                 id = DPLL_ID_SPLL;
8944                 break;
8945         case PORT_CLK_SEL_LCPLL_810:
8946                 id = DPLL_ID_LCPLL_810;
8947                 break;
8948         case PORT_CLK_SEL_LCPLL_1350:
8949                 id = DPLL_ID_LCPLL_1350;
8950                 break;
8951         case PORT_CLK_SEL_LCPLL_2700:
8952                 id = DPLL_ID_LCPLL_2700;
8953                 break;
8954         default:
8955                 MISSING_CASE(ddi_pll_sel);
8956                 /* fall through */
8957         case PORT_CLK_SEL_NONE:
8958                 return;
8959         }
8960
8961         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8962 }
8963
8964 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
8965                                      struct intel_crtc_state *pipe_config,
8966                                      u64 *power_domain_mask)
8967 {
8968         struct drm_device *dev = crtc->base.dev;
8969         struct drm_i915_private *dev_priv = to_i915(dev);
8970         enum intel_display_power_domain power_domain;
8971         u32 tmp;
8972
8973         /*
8974          * The pipe->transcoder mapping is fixed with the exception of the eDP
8975          * transcoder handled below.
8976          */
8977         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8978
8979         /*
8980          * XXX: Do intel_display_power_get_if_enabled before reading this (for
8981          * consistency and less surprising code; it's in always on power).
8982          */
8983         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
8984         if (tmp & TRANS_DDI_FUNC_ENABLE) {
8985                 enum pipe trans_edp_pipe;
8986                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
8987                 default:
8988                         WARN(1, "unknown pipe linked to edp transcoder\n");
8989                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
8990                 case TRANS_DDI_EDP_INPUT_A_ON:
8991                         trans_edp_pipe = PIPE_A;
8992                         break;
8993                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
8994                         trans_edp_pipe = PIPE_B;
8995                         break;
8996                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
8997                         trans_edp_pipe = PIPE_C;
8998                         break;
8999                 }
9000
9001                 if (trans_edp_pipe == crtc->pipe)
9002                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9003         }
9004
9005         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9006         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9007                 return false;
9008         *power_domain_mask |= BIT_ULL(power_domain);
9009
9010         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9011
9012         return tmp & PIPECONF_ENABLE;
9013 }
9014
9015 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9016                                          struct intel_crtc_state *pipe_config,
9017                                          u64 *power_domain_mask)
9018 {
9019         struct drm_device *dev = crtc->base.dev;
9020         struct drm_i915_private *dev_priv = to_i915(dev);
9021         enum intel_display_power_domain power_domain;
9022         enum port port;
9023         enum transcoder cpu_transcoder;
9024         u32 tmp;
9025
9026         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9027                 if (port == PORT_A)
9028                         cpu_transcoder = TRANSCODER_DSI_A;
9029                 else
9030                         cpu_transcoder = TRANSCODER_DSI_C;
9031
9032                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9033                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9034                         continue;
9035                 *power_domain_mask |= BIT_ULL(power_domain);
9036
9037                 /*
9038                  * The PLL needs to be enabled with a valid divider
9039                  * configuration, otherwise accessing DSI registers will hang
9040                  * the machine. See BSpec North Display Engine
9041                  * registers/MIPI[BXT]. We can break out here early, since we
9042                  * need the same DSI PLL to be enabled for both DSI ports.
9043                  */
9044                 if (!intel_dsi_pll_is_enabled(dev_priv))
9045                         break;
9046
9047                 /* XXX: this works for video mode only */
9048                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9049                 if (!(tmp & DPI_ENABLE))
9050                         continue;
9051
9052                 tmp = I915_READ(MIPI_CTRL(port));
9053                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9054                         continue;
9055
9056                 pipe_config->cpu_transcoder = cpu_transcoder;
9057                 break;
9058         }
9059
9060         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9061 }
9062
9063 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9064                                        struct intel_crtc_state *pipe_config)
9065 {
9066         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9067         struct intel_shared_dpll *pll;
9068         enum port port;
9069         uint32_t tmp;
9070
9071         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9072
9073         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9074
9075         if (IS_CANNONLAKE(dev_priv))
9076                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9077         else if (IS_GEN9_BC(dev_priv))
9078                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9079         else if (IS_GEN9_LP(dev_priv))
9080                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9081         else
9082                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9083
9084         pll = pipe_config->shared_dpll;
9085         if (pll) {
9086                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9087                                                  &pipe_config->dpll_hw_state));
9088         }
9089
9090         /*
9091          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9092          * DDI E. So just check whether this pipe is wired to DDI E and whether
9093          * the PCH transcoder is on.
9094          */
9095         if (INTEL_GEN(dev_priv) < 9 &&
9096             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9097                 pipe_config->has_pch_encoder = true;
9098
9099                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9100                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9101                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9102
9103                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9104         }
9105 }
9106
9107 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9108                                     struct intel_crtc_state *pipe_config)
9109 {
9110         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9111         enum intel_display_power_domain power_domain;
9112         u64 power_domain_mask;
9113         bool active;
9114
9115         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9116         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9117                 return false;
9118         power_domain_mask = BIT_ULL(power_domain);
9119
9120         pipe_config->shared_dpll = NULL;
9121
9122         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9123
9124         if (IS_GEN9_LP(dev_priv) &&
9125             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9126                 WARN_ON(active);
9127                 active = true;
9128         }
9129
9130         if (!active)
9131                 goto out;
9132
9133         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9134                 haswell_get_ddi_port_state(crtc, pipe_config);
9135                 intel_get_pipe_timings(crtc, pipe_config);
9136         }
9137
9138         intel_get_pipe_src_size(crtc, pipe_config);
9139
9140         pipe_config->gamma_mode =
9141                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9142
9143         if (INTEL_GEN(dev_priv) >= 9) {
9144                 intel_crtc_init_scalers(crtc, pipe_config);
9145
9146                 pipe_config->scaler_state.scaler_id = -1;
9147                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9148         }
9149
9150         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9151         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9152                 power_domain_mask |= BIT_ULL(power_domain);
9153                 if (INTEL_GEN(dev_priv) >= 9)
9154                         skylake_get_pfit_config(crtc, pipe_config);
9155                 else
9156                         ironlake_get_pfit_config(crtc, pipe_config);
9157         }
9158
9159         if (IS_HASWELL(dev_priv))
9160                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9161                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9162
9163         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9164             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9165                 pipe_config->pixel_multiplier =
9166                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9167         } else {
9168                 pipe_config->pixel_multiplier = 1;
9169         }
9170
9171 out:
9172         for_each_power_domain(power_domain, power_domain_mask)
9173                 intel_display_power_put(dev_priv, power_domain);
9174
9175         return active;
9176 }
9177
9178 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9179 {
9180         struct drm_i915_private *dev_priv =
9181                 to_i915(plane_state->base.plane->dev);
9182         const struct drm_framebuffer *fb = plane_state->base.fb;
9183         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9184         u32 base;
9185
9186         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9187                 base = obj->phys_handle->busaddr;
9188         else
9189                 base = intel_plane_ggtt_offset(plane_state);
9190
9191         base += plane_state->main.offset;
9192
9193         /* ILK+ do this automagically */
9194         if (HAS_GMCH_DISPLAY(dev_priv) &&
9195             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9196                 base += (plane_state->base.crtc_h *
9197                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9198
9199         return base;
9200 }
9201
9202 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9203 {
9204         int x = plane_state->base.crtc_x;
9205         int y = plane_state->base.crtc_y;
9206         u32 pos = 0;
9207
9208         if (x < 0) {
9209                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9210                 x = -x;
9211         }
9212         pos |= x << CURSOR_X_SHIFT;
9213
9214         if (y < 0) {
9215                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9216                 y = -y;
9217         }
9218         pos |= y << CURSOR_Y_SHIFT;
9219
9220         return pos;
9221 }
9222
9223 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9224 {
9225         const struct drm_mode_config *config =
9226                 &plane_state->base.plane->dev->mode_config;
9227         int width = plane_state->base.crtc_w;
9228         int height = plane_state->base.crtc_h;
9229
9230         return width > 0 && width <= config->cursor_width &&
9231                 height > 0 && height <= config->cursor_height;
9232 }
9233
9234 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9235                               struct intel_plane_state *plane_state)
9236 {
9237         const struct drm_framebuffer *fb = plane_state->base.fb;
9238         int src_x, src_y;
9239         u32 offset;
9240         int ret;
9241
9242         ret = drm_plane_helper_check_state(&plane_state->base,
9243                                            &plane_state->clip,
9244                                            DRM_PLANE_HELPER_NO_SCALING,
9245                                            DRM_PLANE_HELPER_NO_SCALING,
9246                                            true, true);
9247         if (ret)
9248                 return ret;
9249
9250         if (!fb)
9251                 return 0;
9252
9253         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9254                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9255                 return -EINVAL;
9256         }
9257
9258         src_x = plane_state->base.src_x >> 16;
9259         src_y = plane_state->base.src_y >> 16;
9260
9261         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9262         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9263
9264         if (src_x != 0 || src_y != 0) {
9265                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9266                 return -EINVAL;
9267         }
9268
9269         plane_state->main.offset = offset;
9270
9271         return 0;
9272 }
9273
9274 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9275                            const struct intel_plane_state *plane_state)
9276 {
9277         const struct drm_framebuffer *fb = plane_state->base.fb;
9278
9279         return CURSOR_ENABLE |
9280                 CURSOR_GAMMA_ENABLE |
9281                 CURSOR_FORMAT_ARGB |
9282                 CURSOR_STRIDE(fb->pitches[0]);
9283 }
9284
9285 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9286 {
9287         int width = plane_state->base.crtc_w;
9288
9289         /*
9290          * 845g/865g are only limited by the width of their cursors,
9291          * the height is arbitrary up to the precision of the register.
9292          */
9293         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9294 }
9295
9296 static int i845_check_cursor(struct intel_plane *plane,
9297                              struct intel_crtc_state *crtc_state,
9298                              struct intel_plane_state *plane_state)
9299 {
9300         const struct drm_framebuffer *fb = plane_state->base.fb;
9301         int ret;
9302
9303         ret = intel_check_cursor(crtc_state, plane_state);
9304         if (ret)
9305                 return ret;
9306
9307         /* if we want to turn off the cursor ignore width and height */
9308         if (!fb)
9309                 return 0;
9310
9311         /* Check for which cursor types we support */
9312         if (!i845_cursor_size_ok(plane_state)) {
9313                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9314                           plane_state->base.crtc_w,
9315                           plane_state->base.crtc_h);
9316                 return -EINVAL;
9317         }
9318
9319         switch (fb->pitches[0]) {
9320         case 256:
9321         case 512:
9322         case 1024:
9323         case 2048:
9324                 break;
9325         default:
9326                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9327                               fb->pitches[0]);
9328                 return -EINVAL;
9329         }
9330
9331         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9332
9333         return 0;
9334 }
9335
9336 static void i845_update_cursor(struct intel_plane *plane,
9337                                const struct intel_crtc_state *crtc_state,
9338                                const struct intel_plane_state *plane_state)
9339 {
9340         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9341         u32 cntl = 0, base = 0, pos = 0, size = 0;
9342         unsigned long irqflags;
9343
9344         if (plane_state && plane_state->base.visible) {
9345                 unsigned int width = plane_state->base.crtc_w;
9346                 unsigned int height = plane_state->base.crtc_h;
9347
9348                 cntl = plane_state->ctl;
9349                 size = (height << 12) | width;
9350
9351                 base = intel_cursor_base(plane_state);
9352                 pos = intel_cursor_position(plane_state);
9353         }
9354
9355         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9356
9357         /* On these chipsets we can only modify the base/size/stride
9358          * whilst the cursor is disabled.
9359          */
9360         if (plane->cursor.base != base ||
9361             plane->cursor.size != size ||
9362             plane->cursor.cntl != cntl) {
9363                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9364                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9365                 I915_WRITE_FW(CURSIZE, size);
9366                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9367                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9368
9369                 plane->cursor.base = base;
9370                 plane->cursor.size = size;
9371                 plane->cursor.cntl = cntl;
9372         } else {
9373                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9374         }
9375
9376         POSTING_READ_FW(CURCNTR(PIPE_A));
9377
9378         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9379 }
9380
9381 static void i845_disable_cursor(struct intel_plane *plane,
9382                                 struct intel_crtc *crtc)
9383 {
9384         i845_update_cursor(plane, NULL, NULL);
9385 }
9386
9387 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9388                            const struct intel_plane_state *plane_state)
9389 {
9390         struct drm_i915_private *dev_priv =
9391                 to_i915(plane_state->base.plane->dev);
9392         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9393         u32 cntl;
9394
9395         cntl = MCURSOR_GAMMA_ENABLE;
9396
9397         if (HAS_DDI(dev_priv))
9398                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9399
9400         cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9401
9402         switch (plane_state->base.crtc_w) {
9403         case 64:
9404                 cntl |= CURSOR_MODE_64_ARGB_AX;
9405                 break;
9406         case 128:
9407                 cntl |= CURSOR_MODE_128_ARGB_AX;
9408                 break;
9409         case 256:
9410                 cntl |= CURSOR_MODE_256_ARGB_AX;
9411                 break;
9412         default:
9413                 MISSING_CASE(plane_state->base.crtc_w);
9414                 return 0;
9415         }
9416
9417         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9418                 cntl |= CURSOR_ROTATE_180;
9419
9420         return cntl;
9421 }
9422
9423 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9424 {
9425         struct drm_i915_private *dev_priv =
9426                 to_i915(plane_state->base.plane->dev);
9427         int width = plane_state->base.crtc_w;
9428         int height = plane_state->base.crtc_h;
9429
9430         if (!intel_cursor_size_ok(plane_state))
9431                 return false;
9432
9433         /* Cursor width is limited to a few power-of-two sizes */
9434         switch (width) {
9435         case 256:
9436         case 128:
9437         case 64:
9438                 break;
9439         default:
9440                 return false;
9441         }
9442
9443         /*
9444          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9445          * height from 8 lines up to the cursor width, when the
9446          * cursor is not rotated. Everything else requires square
9447          * cursors.
9448          */
9449         if (HAS_CUR_FBC(dev_priv) &&
9450             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9451                 if (height < 8 || height > width)
9452                         return false;
9453         } else {
9454                 if (height != width)
9455                         return false;
9456         }
9457
9458         return true;
9459 }
9460
9461 static int i9xx_check_cursor(struct intel_plane *plane,
9462                              struct intel_crtc_state *crtc_state,
9463                              struct intel_plane_state *plane_state)
9464 {
9465         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9466         const struct drm_framebuffer *fb = plane_state->base.fb;
9467         enum pipe pipe = plane->pipe;
9468         int ret;
9469
9470         ret = intel_check_cursor(crtc_state, plane_state);
9471         if (ret)
9472                 return ret;
9473
9474         /* if we want to turn off the cursor ignore width and height */
9475         if (!fb)
9476                 return 0;
9477
9478         /* Check for which cursor types we support */
9479         if (!i9xx_cursor_size_ok(plane_state)) {
9480                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9481                           plane_state->base.crtc_w,
9482                           plane_state->base.crtc_h);
9483                 return -EINVAL;
9484         }
9485
9486         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9487                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9488                               fb->pitches[0], plane_state->base.crtc_w);
9489                 return -EINVAL;
9490         }
9491
9492         /*
9493          * There's something wrong with the cursor on CHV pipe C.
9494          * If it straddles the left edge of the screen then
9495          * moving it away from the edge or disabling it often
9496          * results in a pipe underrun, and often that can lead to
9497          * dead pipe (constant underrun reported, and it scans
9498          * out just a solid color). To recover from that, the
9499          * display power well must be turned off and on again.
9500          * Refuse the put the cursor into that compromised position.
9501          */
9502         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9503             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9504                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9505                 return -EINVAL;
9506         }
9507
9508         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9509
9510         return 0;
9511 }
9512
9513 static void i9xx_update_cursor(struct intel_plane *plane,
9514                                const struct intel_crtc_state *crtc_state,
9515                                const struct intel_plane_state *plane_state)
9516 {
9517         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9518         enum pipe pipe = plane->pipe;
9519         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9520         unsigned long irqflags;
9521
9522         if (plane_state && plane_state->base.visible) {
9523                 cntl = plane_state->ctl;
9524
9525                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9526                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9527
9528                 base = intel_cursor_base(plane_state);
9529                 pos = intel_cursor_position(plane_state);
9530         }
9531
9532         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9533
9534         /*
9535          * On some platforms writing CURCNTR first will also
9536          * cause CURPOS to be armed by the CURBASE write.
9537          * Without the CURCNTR write the CURPOS write would
9538          * arm itself.
9539          *
9540          * CURCNTR and CUR_FBC_CTL are always
9541          * armed by the CURBASE write only.
9542          */
9543         if (plane->cursor.base != base ||
9544             plane->cursor.size != fbc_ctl ||
9545             plane->cursor.cntl != cntl) {
9546                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9547                 if (HAS_CUR_FBC(dev_priv))
9548                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9549                 I915_WRITE_FW(CURPOS(pipe), pos);
9550                 I915_WRITE_FW(CURBASE(pipe), base);
9551
9552                 plane->cursor.base = base;
9553                 plane->cursor.size = fbc_ctl;
9554                 plane->cursor.cntl = cntl;
9555         } else {
9556                 I915_WRITE_FW(CURPOS(pipe), pos);
9557         }
9558
9559         POSTING_READ_FW(CURBASE(pipe));
9560
9561         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9562 }
9563
9564 static void i9xx_disable_cursor(struct intel_plane *plane,
9565                                 struct intel_crtc *crtc)
9566 {
9567         i9xx_update_cursor(plane, NULL, NULL);
9568 }
9569
9570
9571 /* VESA 640x480x72Hz mode to set on the pipe */
9572 static struct drm_display_mode load_detect_mode = {
9573         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9574                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9575 };
9576
9577 struct drm_framebuffer *
9578 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9579                          struct drm_mode_fb_cmd2 *mode_cmd)
9580 {
9581         struct intel_framebuffer *intel_fb;
9582         int ret;
9583
9584         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9585         if (!intel_fb)
9586                 return ERR_PTR(-ENOMEM);
9587
9588         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9589         if (ret)
9590                 goto err;
9591
9592         return &intel_fb->base;
9593
9594 err:
9595         kfree(intel_fb);
9596         return ERR_PTR(ret);
9597 }
9598
9599 static u32
9600 intel_framebuffer_pitch_for_width(int width, int bpp)
9601 {
9602         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
9603         return ALIGN(pitch, 64);
9604 }
9605
9606 static u32
9607 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
9608 {
9609         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
9610         return PAGE_ALIGN(pitch * mode->vdisplay);
9611 }
9612
9613 static struct drm_framebuffer *
9614 intel_framebuffer_create_for_mode(struct drm_device *dev,
9615                                   struct drm_display_mode *mode,
9616                                   int depth, int bpp)
9617 {
9618         struct drm_framebuffer *fb;
9619         struct drm_i915_gem_object *obj;
9620         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
9621
9622         obj = i915_gem_object_create(to_i915(dev),
9623                                     intel_framebuffer_size_for_mode(mode, bpp));
9624         if (IS_ERR(obj))
9625                 return ERR_CAST(obj);
9626
9627         mode_cmd.width = mode->hdisplay;
9628         mode_cmd.height = mode->vdisplay;
9629         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
9630                                                                 bpp);
9631         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
9632
9633         fb = intel_framebuffer_create(obj, &mode_cmd);
9634         if (IS_ERR(fb))
9635                 i915_gem_object_put(obj);
9636
9637         return fb;
9638 }
9639
9640 static struct drm_framebuffer *
9641 mode_fits_in_fbdev(struct drm_device *dev,
9642                    struct drm_display_mode *mode)
9643 {
9644 #ifdef CONFIG_DRM_FBDEV_EMULATION
9645         struct drm_i915_private *dev_priv = to_i915(dev);
9646         struct drm_i915_gem_object *obj;
9647         struct drm_framebuffer *fb;
9648
9649         if (!dev_priv->fbdev)
9650                 return NULL;
9651
9652         if (!dev_priv->fbdev->fb)
9653                 return NULL;
9654
9655         obj = dev_priv->fbdev->fb->obj;
9656         BUG_ON(!obj);
9657
9658         fb = &dev_priv->fbdev->fb->base;
9659         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
9660                                                                fb->format->cpp[0] * 8))
9661                 return NULL;
9662
9663         if (obj->base.size < mode->vdisplay * fb->pitches[0])
9664                 return NULL;
9665
9666         drm_framebuffer_reference(fb);
9667         return fb;
9668 #else
9669         return NULL;
9670 #endif
9671 }
9672
9673 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
9674                                            struct drm_crtc *crtc,
9675                                            struct drm_display_mode *mode,
9676                                            struct drm_framebuffer *fb,
9677                                            int x, int y)
9678 {
9679         struct drm_plane_state *plane_state;
9680         int hdisplay, vdisplay;
9681         int ret;
9682
9683         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
9684         if (IS_ERR(plane_state))
9685                 return PTR_ERR(plane_state);
9686
9687         if (mode)
9688                 drm_mode_get_hv_timing(mode, &hdisplay, &vdisplay);
9689         else
9690                 hdisplay = vdisplay = 0;
9691
9692         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
9693         if (ret)
9694                 return ret;
9695         drm_atomic_set_fb_for_plane(plane_state, fb);
9696         plane_state->crtc_x = 0;
9697         plane_state->crtc_y = 0;
9698         plane_state->crtc_w = hdisplay;
9699         plane_state->crtc_h = vdisplay;
9700         plane_state->src_x = x << 16;
9701         plane_state->src_y = y << 16;
9702         plane_state->src_w = hdisplay << 16;
9703         plane_state->src_h = vdisplay << 16;
9704
9705         return 0;
9706 }
9707
9708 int intel_get_load_detect_pipe(struct drm_connector *connector,
9709                                struct drm_display_mode *mode,
9710                                struct intel_load_detect_pipe *old,
9711                                struct drm_modeset_acquire_ctx *ctx)
9712 {
9713         struct intel_crtc *intel_crtc;
9714         struct intel_encoder *intel_encoder =
9715                 intel_attached_encoder(connector);
9716         struct drm_crtc *possible_crtc;
9717         struct drm_encoder *encoder = &intel_encoder->base;
9718         struct drm_crtc *crtc = NULL;
9719         struct drm_device *dev = encoder->dev;
9720         struct drm_i915_private *dev_priv = to_i915(dev);
9721         struct drm_framebuffer *fb;
9722         struct drm_mode_config *config = &dev->mode_config;
9723         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9724         struct drm_connector_state *connector_state;
9725         struct intel_crtc_state *crtc_state;
9726         int ret, i = -1;
9727
9728         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9729                       connector->base.id, connector->name,
9730                       encoder->base.id, encoder->name);
9731
9732         old->restore_state = NULL;
9733
9734         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9735
9736         /*
9737          * Algorithm gets a little messy:
9738          *
9739          *   - if the connector already has an assigned crtc, use it (but make
9740          *     sure it's on first)
9741          *
9742          *   - try to find the first unused crtc that can drive this connector,
9743          *     and use that if we find one
9744          */
9745
9746         /* See if we already have a CRTC for this connector */
9747         if (connector->state->crtc) {
9748                 crtc = connector->state->crtc;
9749
9750                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9751                 if (ret)
9752                         goto fail;
9753
9754                 /* Make sure the crtc and connector are running */
9755                 goto found;
9756         }
9757
9758         /* Find an unused one (if possible) */
9759         for_each_crtc(dev, possible_crtc) {
9760                 i++;
9761                 if (!(encoder->possible_crtcs & (1 << i)))
9762                         continue;
9763
9764                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9765                 if (ret)
9766                         goto fail;
9767
9768                 if (possible_crtc->state->enable) {
9769                         drm_modeset_unlock(&possible_crtc->mutex);
9770                         continue;
9771                 }
9772
9773                 crtc = possible_crtc;
9774                 break;
9775         }
9776
9777         /*
9778          * If we didn't find an unused CRTC, don't use any.
9779          */
9780         if (!crtc) {
9781                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9782                 ret = -ENODEV;
9783                 goto fail;
9784         }
9785
9786 found:
9787         intel_crtc = to_intel_crtc(crtc);
9788
9789         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9790         if (ret)
9791                 goto fail;
9792
9793         state = drm_atomic_state_alloc(dev);
9794         restore_state = drm_atomic_state_alloc(dev);
9795         if (!state || !restore_state) {
9796                 ret = -ENOMEM;
9797                 goto fail;
9798         }
9799
9800         state->acquire_ctx = ctx;
9801         restore_state->acquire_ctx = ctx;
9802
9803         connector_state = drm_atomic_get_connector_state(state, connector);
9804         if (IS_ERR(connector_state)) {
9805                 ret = PTR_ERR(connector_state);
9806                 goto fail;
9807         }
9808
9809         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
9810         if (ret)
9811                 goto fail;
9812
9813         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9814         if (IS_ERR(crtc_state)) {
9815                 ret = PTR_ERR(crtc_state);
9816                 goto fail;
9817         }
9818
9819         crtc_state->base.active = crtc_state->base.enable = true;
9820
9821         if (!mode)
9822                 mode = &load_detect_mode;
9823
9824         /* We need a framebuffer large enough to accommodate all accesses
9825          * that the plane may generate whilst we perform load detection.
9826          * We can not rely on the fbcon either being present (we get called
9827          * during its initialisation to detect all boot displays, or it may
9828          * not even exist) or that it is large enough to satisfy the
9829          * requested mode.
9830          */
9831         fb = mode_fits_in_fbdev(dev, mode);
9832         if (fb == NULL) {
9833                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
9834                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
9835         } else
9836                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
9837         if (IS_ERR(fb)) {
9838                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
9839                 ret = PTR_ERR(fb);
9840                 goto fail;
9841         }
9842
9843         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
9844         if (ret)
9845                 goto fail;
9846
9847         drm_framebuffer_unreference(fb);
9848
9849         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
9850         if (ret)
9851                 goto fail;
9852
9853         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
9854         if (!ret)
9855                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
9856         if (!ret)
9857                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
9858         if (ret) {
9859                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
9860                 goto fail;
9861         }
9862
9863         ret = drm_atomic_commit(state);
9864         if (ret) {
9865                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9866                 goto fail;
9867         }
9868
9869         old->restore_state = restore_state;
9870         drm_atomic_state_put(state);
9871
9872         /* let the connector get through one full cycle before testing */
9873         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
9874         return true;
9875
9876 fail:
9877         if (state) {
9878                 drm_atomic_state_put(state);
9879                 state = NULL;
9880         }
9881         if (restore_state) {
9882                 drm_atomic_state_put(restore_state);
9883                 restore_state = NULL;
9884         }
9885
9886         if (ret == -EDEADLK)
9887                 return ret;
9888
9889         return false;
9890 }
9891
9892 void intel_release_load_detect_pipe(struct drm_connector *connector,
9893                                     struct intel_load_detect_pipe *old,
9894                                     struct drm_modeset_acquire_ctx *ctx)
9895 {
9896         struct intel_encoder *intel_encoder =
9897                 intel_attached_encoder(connector);
9898         struct drm_encoder *encoder = &intel_encoder->base;
9899         struct drm_atomic_state *state = old->restore_state;
9900         int ret;
9901
9902         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9903                       connector->base.id, connector->name,
9904                       encoder->base.id, encoder->name);
9905
9906         if (!state)
9907                 return;
9908
9909         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
9910         if (ret)
9911                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
9912         drm_atomic_state_put(state);
9913 }
9914
9915 static int i9xx_pll_refclk(struct drm_device *dev,
9916                            const struct intel_crtc_state *pipe_config)
9917 {
9918         struct drm_i915_private *dev_priv = to_i915(dev);
9919         u32 dpll = pipe_config->dpll_hw_state.dpll;
9920
9921         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
9922                 return dev_priv->vbt.lvds_ssc_freq;
9923         else if (HAS_PCH_SPLIT(dev_priv))
9924                 return 120000;
9925         else if (!IS_GEN2(dev_priv))
9926                 return 96000;
9927         else
9928                 return 48000;
9929 }
9930
9931 /* Returns the clock of the currently programmed mode of the given pipe. */
9932 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
9933                                 struct intel_crtc_state *pipe_config)
9934 {
9935         struct drm_device *dev = crtc->base.dev;
9936         struct drm_i915_private *dev_priv = to_i915(dev);
9937         int pipe = pipe_config->cpu_transcoder;
9938         u32 dpll = pipe_config->dpll_hw_state.dpll;
9939         u32 fp;
9940         struct dpll clock;
9941         int port_clock;
9942         int refclk = i9xx_pll_refclk(dev, pipe_config);
9943
9944         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
9945                 fp = pipe_config->dpll_hw_state.fp0;
9946         else
9947                 fp = pipe_config->dpll_hw_state.fp1;
9948
9949         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
9950         if (IS_PINEVIEW(dev_priv)) {
9951                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
9952                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
9953         } else {
9954                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
9955                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
9956         }
9957
9958         if (!IS_GEN2(dev_priv)) {
9959                 if (IS_PINEVIEW(dev_priv))
9960                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
9961                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
9962                 else
9963                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
9964                                DPLL_FPA01_P1_POST_DIV_SHIFT);
9965
9966                 switch (dpll & DPLL_MODE_MASK) {
9967                 case DPLLB_MODE_DAC_SERIAL:
9968                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
9969                                 5 : 10;
9970                         break;
9971                 case DPLLB_MODE_LVDS:
9972                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
9973                                 7 : 14;
9974                         break;
9975                 default:
9976                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
9977                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
9978                         return;
9979                 }
9980
9981                 if (IS_PINEVIEW(dev_priv))
9982                         port_clock = pnv_calc_dpll_params(refclk, &clock);
9983                 else
9984                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
9985         } else {
9986                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
9987                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
9988
9989                 if (is_lvds) {
9990                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
9991                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
9992
9993                         if (lvds & LVDS_CLKB_POWER_UP)
9994                                 clock.p2 = 7;
9995                         else
9996                                 clock.p2 = 14;
9997                 } else {
9998                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
9999                                 clock.p1 = 2;
10000                         else {
10001                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10002                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10003                         }
10004                         if (dpll & PLL_P2_DIVIDE_BY_4)
10005                                 clock.p2 = 4;
10006                         else
10007                                 clock.p2 = 2;
10008                 }
10009
10010                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10011         }
10012
10013         /*
10014          * This value includes pixel_multiplier. We will use
10015          * port_clock to compute adjusted_mode.crtc_clock in the
10016          * encoder's get_config() function.
10017          */
10018         pipe_config->port_clock = port_clock;
10019 }
10020
10021 int intel_dotclock_calculate(int link_freq,
10022                              const struct intel_link_m_n *m_n)
10023 {
10024         /*
10025          * The calculation for the data clock is:
10026          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10027          * But we want to avoid losing precison if possible, so:
10028          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10029          *
10030          * and the link clock is simpler:
10031          * link_clock = (m * link_clock) / n
10032          */
10033
10034         if (!m_n->link_n)
10035                 return 0;
10036
10037         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10038 }
10039
10040 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10041                                    struct intel_crtc_state *pipe_config)
10042 {
10043         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10044
10045         /* read out port_clock from the DPLL */
10046         i9xx_crtc_clock_get(crtc, pipe_config);
10047
10048         /*
10049          * In case there is an active pipe without active ports,
10050          * we may need some idea for the dotclock anyway.
10051          * Calculate one based on the FDI configuration.
10052          */
10053         pipe_config->base.adjusted_mode.crtc_clock =
10054                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10055                                          &pipe_config->fdi_m_n);
10056 }
10057
10058 /** Returns the currently programmed mode of the given pipe. */
10059 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10060                                              struct drm_crtc *crtc)
10061 {
10062         struct drm_i915_private *dev_priv = to_i915(dev);
10063         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10064         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10065         struct drm_display_mode *mode;
10066         struct intel_crtc_state *pipe_config;
10067         int htot = I915_READ(HTOTAL(cpu_transcoder));
10068         int hsync = I915_READ(HSYNC(cpu_transcoder));
10069         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10070         int vsync = I915_READ(VSYNC(cpu_transcoder));
10071         enum pipe pipe = intel_crtc->pipe;
10072
10073         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10074         if (!mode)
10075                 return NULL;
10076
10077         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10078         if (!pipe_config) {
10079                 kfree(mode);
10080                 return NULL;
10081         }
10082
10083         /*
10084          * Construct a pipe_config sufficient for getting the clock info
10085          * back out of crtc_clock_get.
10086          *
10087          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10088          * to use a real value here instead.
10089          */
10090         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10091         pipe_config->pixel_multiplier = 1;
10092         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10093         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10094         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10095         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10096
10097         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10098         mode->hdisplay = (htot & 0xffff) + 1;
10099         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10100         mode->hsync_start = (hsync & 0xffff) + 1;
10101         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10102         mode->vdisplay = (vtot & 0xffff) + 1;
10103         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10104         mode->vsync_start = (vsync & 0xffff) + 1;
10105         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10106
10107         drm_mode_set_name(mode);
10108
10109         kfree(pipe_config);
10110
10111         return mode;
10112 }
10113
10114 static void intel_crtc_destroy(struct drm_crtc *crtc)
10115 {
10116         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10117         struct drm_device *dev = crtc->dev;
10118         struct intel_flip_work *work;
10119
10120         spin_lock_irq(&dev->event_lock);
10121         work = intel_crtc->flip_work;
10122         intel_crtc->flip_work = NULL;
10123         spin_unlock_irq(&dev->event_lock);
10124
10125         if (work) {
10126                 cancel_work_sync(&work->mmio_work);
10127                 cancel_work_sync(&work->unpin_work);
10128                 kfree(work);
10129         }
10130
10131         drm_crtc_cleanup(crtc);
10132
10133         kfree(intel_crtc);
10134 }
10135
10136 static void intel_unpin_work_fn(struct work_struct *__work)
10137 {
10138         struct intel_flip_work *work =
10139                 container_of(__work, struct intel_flip_work, unpin_work);
10140         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10141         struct drm_device *dev = crtc->base.dev;
10142         struct drm_plane *primary = crtc->base.primary;
10143
10144         if (is_mmio_work(work))
10145                 flush_work(&work->mmio_work);
10146
10147         mutex_lock(&dev->struct_mutex);
10148         intel_unpin_fb_vma(work->old_vma);
10149         i915_gem_object_put(work->pending_flip_obj);
10150         mutex_unlock(&dev->struct_mutex);
10151
10152         i915_gem_request_put(work->flip_queued_req);
10153
10154         intel_frontbuffer_flip_complete(to_i915(dev),
10155                                         to_intel_plane(primary)->frontbuffer_bit);
10156         intel_fbc_post_update(crtc);
10157         drm_framebuffer_unreference(work->old_fb);
10158
10159         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10160         atomic_dec(&crtc->unpin_work_count);
10161
10162         kfree(work);
10163 }
10164
10165 /* Is 'a' after or equal to 'b'? */
10166 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10167 {
10168         return !((a - b) & 0x80000000);
10169 }
10170
10171 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
10172                                    struct intel_flip_work *work)
10173 {
10174         struct drm_device *dev = crtc->base.dev;
10175         struct drm_i915_private *dev_priv = to_i915(dev);
10176
10177         if (abort_flip_on_reset(crtc))
10178                 return true;
10179
10180         /*
10181          * The relevant registers doen't exist on pre-ctg.
10182          * As the flip done interrupt doesn't trigger for mmio
10183          * flips on gmch platforms, a flip count check isn't
10184          * really needed there. But since ctg has the registers,
10185          * include it in the check anyway.
10186          */
10187         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10188                 return true;
10189
10190         /*
10191          * BDW signals flip done immediately if the plane
10192          * is disabled, even if the plane enable is already
10193          * armed to occur at the next vblank :(
10194          */
10195
10196         /*
10197          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10198          * used the same base address. In that case the mmio flip might
10199          * have completed, but the CS hasn't even executed the flip yet.
10200          *
10201          * A flip count check isn't enough as the CS might have updated
10202          * the base address just after start of vblank, but before we
10203          * managed to process the interrupt. This means we'd complete the
10204          * CS flip too soon.
10205          *
10206          * Combining both checks should get us a good enough result. It may
10207          * still happen that the CS flip has been executed, but has not
10208          * yet actually completed. But in case the base address is the same
10209          * anyway, we don't really care.
10210          */
10211         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10212                 crtc->flip_work->gtt_offset &&
10213                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10214                                     crtc->flip_work->flip_count);
10215 }
10216
10217 static bool
10218 __pageflip_finished_mmio(struct intel_crtc *crtc,
10219                                struct intel_flip_work *work)
10220 {
10221         /*
10222          * MMIO work completes when vblank is different from
10223          * flip_queued_vblank.
10224          *
10225          * Reset counter value doesn't matter, this is handled by
10226          * i915_wait_request finishing early, so no need to handle
10227          * reset here.
10228          */
10229         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
10230 }
10231
10232
10233 static bool pageflip_finished(struct intel_crtc *crtc,
10234                               struct intel_flip_work *work)
10235 {
10236         if (!atomic_read(&work->pending))
10237                 return false;
10238
10239         smp_rmb();
10240
10241         if (is_mmio_work(work))
10242                 return __pageflip_finished_mmio(crtc, work);
10243         else
10244                 return __pageflip_finished_cs(crtc, work);
10245 }
10246
10247 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
10248 {
10249         struct drm_device *dev = &dev_priv->drm;
10250         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10251         struct intel_flip_work *work;
10252         unsigned long flags;
10253
10254         /* Ignore early vblank irqs */
10255         if (!crtc)
10256                 return;
10257
10258         /*
10259          * This is called both by irq handlers and the reset code (to complete
10260          * lost pageflips) so needs the full irqsave spinlocks.
10261          */
10262         spin_lock_irqsave(&dev->event_lock, flags);
10263         work = crtc->flip_work;
10264
10265         if (work != NULL &&
10266             !is_mmio_work(work) &&
10267             pageflip_finished(crtc, work))
10268                 page_flip_completed(crtc);
10269
10270         spin_unlock_irqrestore(&dev->event_lock, flags);
10271 }
10272
10273 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
10274 {
10275         struct drm_device *dev = &dev_priv->drm;
10276         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10277         struct intel_flip_work *work;
10278         unsigned long flags;
10279
10280         /* Ignore early vblank irqs */
10281         if (!crtc)
10282                 return;
10283
10284         /*
10285          * This is called both by irq handlers and the reset code (to complete
10286          * lost pageflips) so needs the full irqsave spinlocks.
10287          */
10288         spin_lock_irqsave(&dev->event_lock, flags);
10289         work = crtc->flip_work;
10290
10291         if (work != NULL &&
10292             is_mmio_work(work) &&
10293             pageflip_finished(crtc, work))
10294                 page_flip_completed(crtc);
10295
10296         spin_unlock_irqrestore(&dev->event_lock, flags);
10297 }
10298
10299 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
10300                                                struct intel_flip_work *work)
10301 {
10302         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
10303
10304         /* Ensure that the work item is consistent when activating it ... */
10305         smp_mb__before_atomic();
10306         atomic_set(&work->pending, 1);
10307 }
10308
10309 static int intel_gen2_queue_flip(struct drm_device *dev,
10310                                  struct drm_crtc *crtc,
10311                                  struct drm_framebuffer *fb,
10312                                  struct drm_i915_gem_object *obj,
10313                                  struct drm_i915_gem_request *req,
10314                                  uint32_t flags)
10315 {
10316         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10317         u32 flip_mask, *cs;
10318
10319         cs = intel_ring_begin(req, 6);
10320         if (IS_ERR(cs))
10321                 return PTR_ERR(cs);
10322
10323         /* Can't queue multiple flips, so wait for the previous
10324          * one to finish before executing the next.
10325          */
10326         if (intel_crtc->plane)
10327                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10328         else
10329                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10330         *cs++ = MI_WAIT_FOR_EVENT | flip_mask;
10331         *cs++ = MI_NOOP;
10332         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10333         *cs++ = fb->pitches[0];
10334         *cs++ = intel_crtc->flip_work->gtt_offset;
10335         *cs++ = 0; /* aux display base address, unused */
10336
10337         return 0;
10338 }
10339
10340 static int intel_gen3_queue_flip(struct drm_device *dev,
10341                                  struct drm_crtc *crtc,
10342                                  struct drm_framebuffer *fb,
10343                                  struct drm_i915_gem_object *obj,
10344                                  struct drm_i915_gem_request *req,
10345                                  uint32_t flags)
10346 {
10347         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10348         u32 flip_mask, *cs;
10349
10350         cs = intel_ring_begin(req, 6);
10351         if (IS_ERR(cs))
10352                 return PTR_ERR(cs);
10353
10354         if (intel_crtc->plane)
10355                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10356         else
10357                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10358         *cs++ = MI_WAIT_FOR_EVENT | flip_mask;
10359         *cs++ = MI_NOOP;
10360         *cs++ = MI_DISPLAY_FLIP_I915 | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10361         *cs++ = fb->pitches[0];
10362         *cs++ = intel_crtc->flip_work->gtt_offset;
10363         *cs++ = MI_NOOP;
10364
10365         return 0;
10366 }
10367
10368 static int intel_gen4_queue_flip(struct drm_device *dev,
10369                                  struct drm_crtc *crtc,
10370                                  struct drm_framebuffer *fb,
10371                                  struct drm_i915_gem_object *obj,
10372                                  struct drm_i915_gem_request *req,
10373                                  uint32_t flags)
10374 {
10375         struct drm_i915_private *dev_priv = to_i915(dev);
10376         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10377         u32 pf, pipesrc, *cs;
10378
10379         cs = intel_ring_begin(req, 4);
10380         if (IS_ERR(cs))
10381                 return PTR_ERR(cs);
10382
10383         /* i965+ uses the linear or tiled offsets from the
10384          * Display Registers (which do not change across a page-flip)
10385          * so we need only reprogram the base address.
10386          */
10387         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10388         *cs++ = fb->pitches[0];
10389         *cs++ = intel_crtc->flip_work->gtt_offset |
10390                 intel_fb_modifier_to_tiling(fb->modifier);
10391
10392         /* XXX Enabling the panel-fitter across page-flip is so far
10393          * untested on non-native modes, so ignore it for now.
10394          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10395          */
10396         pf = 0;
10397         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10398         *cs++ = pf | pipesrc;
10399
10400         return 0;
10401 }
10402
10403 static int intel_gen6_queue_flip(struct drm_device *dev,
10404                                  struct drm_crtc *crtc,
10405                                  struct drm_framebuffer *fb,
10406                                  struct drm_i915_gem_object *obj,
10407                                  struct drm_i915_gem_request *req,
10408                                  uint32_t flags)
10409 {
10410         struct drm_i915_private *dev_priv = to_i915(dev);
10411         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10412         u32 pf, pipesrc, *cs;
10413
10414         cs = intel_ring_begin(req, 4);
10415         if (IS_ERR(cs))
10416                 return PTR_ERR(cs);
10417
10418         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10419         *cs++ = fb->pitches[0] | intel_fb_modifier_to_tiling(fb->modifier);
10420         *cs++ = intel_crtc->flip_work->gtt_offset;
10421
10422         /* Contrary to the suggestions in the documentation,
10423          * "Enable Panel Fitter" does not seem to be required when page
10424          * flipping with a non-native mode, and worse causes a normal
10425          * modeset to fail.
10426          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10427          */
10428         pf = 0;
10429         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10430         *cs++ = pf | pipesrc;
10431
10432         return 0;
10433 }
10434
10435 static int intel_gen7_queue_flip(struct drm_device *dev,
10436                                  struct drm_crtc *crtc,
10437                                  struct drm_framebuffer *fb,
10438                                  struct drm_i915_gem_object *obj,
10439                                  struct drm_i915_gem_request *req,
10440                                  uint32_t flags)
10441 {
10442         struct drm_i915_private *dev_priv = to_i915(dev);
10443         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10444         u32 *cs, plane_bit = 0;
10445         int len, ret;
10446
10447         switch (intel_crtc->plane) {
10448         case PLANE_A:
10449                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10450                 break;
10451         case PLANE_B:
10452                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10453                 break;
10454         case PLANE_C:
10455                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10456                 break;
10457         default:
10458                 WARN_ONCE(1, "unknown plane in flip command\n");
10459                 return -ENODEV;
10460         }
10461
10462         len = 4;
10463         if (req->engine->id == RCS) {
10464                 len += 6;
10465                 /*
10466                  * On Gen 8, SRM is now taking an extra dword to accommodate
10467                  * 48bits addresses, and we need a NOOP for the batch size to
10468                  * stay even.
10469                  */
10470                 if (IS_GEN8(dev_priv))
10471                         len += 2;
10472         }
10473
10474         /*
10475          * BSpec MI_DISPLAY_FLIP for IVB:
10476          * "The full packet must be contained within the same cache line."
10477          *
10478          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10479          * cacheline, if we ever start emitting more commands before
10480          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10481          * then do the cacheline alignment, and finally emit the
10482          * MI_DISPLAY_FLIP.
10483          */
10484         ret = intel_ring_cacheline_align(req);
10485         if (ret)
10486                 return ret;
10487
10488         cs = intel_ring_begin(req, len);
10489         if (IS_ERR(cs))
10490                 return PTR_ERR(cs);
10491
10492         /* Unmask the flip-done completion message. Note that the bspec says that
10493          * we should do this for both the BCS and RCS, and that we must not unmask
10494          * more than one flip event at any time (or ensure that one flip message
10495          * can be sent by waiting for flip-done prior to queueing new flips).
10496          * Experimentation says that BCS works despite DERRMR masking all
10497          * flip-done completion events and that unmasking all planes at once
10498          * for the RCS also doesn't appear to drop events. Setting the DERRMR
10499          * to zero does lead to lockups within MI_DISPLAY_FLIP.
10500          */
10501         if (req->engine->id == RCS) {
10502                 *cs++ = MI_LOAD_REGISTER_IMM(1);
10503                 *cs++ = i915_mmio_reg_offset(DERRMR);
10504                 *cs++ = ~(DERRMR_PIPEA_PRI_FLIP_DONE |
10505                           DERRMR_PIPEB_PRI_FLIP_DONE |
10506                           DERRMR_PIPEC_PRI_FLIP_DONE);
10507                 if (IS_GEN8(dev_priv))
10508                         *cs++ = MI_STORE_REGISTER_MEM_GEN8 |
10509                                 MI_SRM_LRM_GLOBAL_GTT;
10510                 else
10511                         *cs++ = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
10512                 *cs++ = i915_mmio_reg_offset(DERRMR);
10513                 *cs++ = i915_ggtt_offset(req->engine->scratch) + 256;
10514                 if (IS_GEN8(dev_priv)) {
10515                         *cs++ = 0;
10516                         *cs++ = MI_NOOP;
10517                 }
10518         }
10519
10520         *cs++ = MI_DISPLAY_FLIP_I915 | plane_bit;
10521         *cs++ = fb->pitches[0] | intel_fb_modifier_to_tiling(fb->modifier);
10522         *cs++ = intel_crtc->flip_work->gtt_offset;
10523         *cs++ = MI_NOOP;
10524
10525         return 0;
10526 }
10527
10528 static bool use_mmio_flip(struct intel_engine_cs *engine,
10529                           struct drm_i915_gem_object *obj)
10530 {
10531         /*
10532          * This is not being used for older platforms, because
10533          * non-availability of flip done interrupt forces us to use
10534          * CS flips. Older platforms derive flip done using some clever
10535          * tricks involving the flip_pending status bits and vblank irqs.
10536          * So using MMIO flips there would disrupt this mechanism.
10537          */
10538
10539         if (engine == NULL)
10540                 return true;
10541
10542         if (INTEL_GEN(engine->i915) < 5)
10543                 return false;
10544
10545         if (i915.use_mmio_flip < 0)
10546                 return false;
10547         else if (i915.use_mmio_flip > 0)
10548                 return true;
10549         else if (i915.enable_execlists)
10550                 return true;
10551
10552         return engine != i915_gem_object_last_write_engine(obj);
10553 }
10554
10555 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
10556                              unsigned int rotation,
10557                              struct intel_flip_work *work)
10558 {
10559         struct drm_device *dev = intel_crtc->base.dev;
10560         struct drm_i915_private *dev_priv = to_i915(dev);
10561         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
10562         const enum pipe pipe = intel_crtc->pipe;
10563         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
10564
10565         ctl = I915_READ(PLANE_CTL(pipe, 0));
10566         ctl &= ~PLANE_CTL_TILED_MASK;
10567         switch (fb->modifier) {
10568         case DRM_FORMAT_MOD_LINEAR:
10569                 break;
10570         case I915_FORMAT_MOD_X_TILED:
10571                 ctl |= PLANE_CTL_TILED_X;
10572                 break;
10573         case I915_FORMAT_MOD_Y_TILED:
10574                 ctl |= PLANE_CTL_TILED_Y;
10575                 break;
10576         case I915_FORMAT_MOD_Yf_TILED:
10577                 ctl |= PLANE_CTL_TILED_YF;
10578                 break;
10579         default:
10580                 MISSING_CASE(fb->modifier);
10581         }
10582
10583         /*
10584          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
10585          * PLANE_SURF updates, the update is then guaranteed to be atomic.
10586          */
10587         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
10588         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
10589
10590         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
10591         POSTING_READ(PLANE_SURF(pipe, 0));
10592 }
10593
10594 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
10595                              struct intel_flip_work *work)
10596 {
10597         struct drm_device *dev = intel_crtc->base.dev;
10598         struct drm_i915_private *dev_priv = to_i915(dev);
10599         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
10600         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
10601         u32 dspcntr;
10602
10603         dspcntr = I915_READ(reg);
10604
10605         if (fb->modifier == I915_FORMAT_MOD_X_TILED)
10606                 dspcntr |= DISPPLANE_TILED;
10607         else
10608                 dspcntr &= ~DISPPLANE_TILED;
10609
10610         I915_WRITE(reg, dspcntr);
10611
10612         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
10613         POSTING_READ(DSPSURF(intel_crtc->plane));
10614 }
10615
10616 static void intel_mmio_flip_work_func(struct work_struct *w)
10617 {
10618         struct intel_flip_work *work =
10619                 container_of(w, struct intel_flip_work, mmio_work);
10620         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10621         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10622         struct intel_framebuffer *intel_fb =
10623                 to_intel_framebuffer(crtc->base.primary->fb);
10624         struct drm_i915_gem_object *obj = intel_fb->obj;
10625
10626         WARN_ON(i915_gem_object_wait(obj, 0, MAX_SCHEDULE_TIMEOUT, NULL) < 0);
10627
10628         intel_pipe_update_start(crtc);
10629
10630         if (INTEL_GEN(dev_priv) >= 9)
10631                 skl_do_mmio_flip(crtc, work->rotation, work);
10632         else
10633                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
10634                 ilk_do_mmio_flip(crtc, work);
10635
10636         intel_pipe_update_end(crtc, work);
10637 }
10638
10639 static int intel_default_queue_flip(struct drm_device *dev,
10640                                     struct drm_crtc *crtc,
10641                                     struct drm_framebuffer *fb,
10642                                     struct drm_i915_gem_object *obj,
10643                                     struct drm_i915_gem_request *req,
10644                                     uint32_t flags)
10645 {
10646         return -ENODEV;
10647 }
10648
10649 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
10650                                       struct intel_crtc *intel_crtc,
10651                                       struct intel_flip_work *work)
10652 {
10653         u32 addr, vblank;
10654
10655         if (!atomic_read(&work->pending))
10656                 return false;
10657
10658         smp_rmb();
10659
10660         vblank = intel_crtc_get_vblank_counter(intel_crtc);
10661         if (work->flip_ready_vblank == 0) {
10662                 if (work->flip_queued_req &&
10663                     !i915_gem_request_completed(work->flip_queued_req))
10664                         return false;
10665
10666                 work->flip_ready_vblank = vblank;
10667         }
10668
10669         if (vblank - work->flip_ready_vblank < 3)
10670                 return false;
10671
10672         /* Potential stall - if we see that the flip has happened,
10673          * assume a missed interrupt. */
10674         if (INTEL_GEN(dev_priv) >= 4)
10675                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
10676         else
10677                 addr = I915_READ(DSPADDR(intel_crtc->plane));
10678
10679         /* There is a potential issue here with a false positive after a flip
10680          * to the same address. We could address this by checking for a
10681          * non-incrementing frame counter.
10682          */
10683         return addr == work->gtt_offset;
10684 }
10685
10686 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
10687 {
10688         struct drm_device *dev = &dev_priv->drm;
10689         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10690         struct intel_flip_work *work;
10691
10692         WARN_ON(!in_interrupt());
10693
10694         if (crtc == NULL)
10695                 return;
10696
10697         spin_lock(&dev->event_lock);
10698         work = crtc->flip_work;
10699
10700         if (work != NULL && !is_mmio_work(work) &&
10701             __pageflip_stall_check_cs(dev_priv, crtc, work)) {
10702                 WARN_ONCE(1,
10703                           "Kicking stuck page flip: queued at %d, now %d\n",
10704                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(crtc));
10705                 page_flip_completed(crtc);
10706                 work = NULL;
10707         }
10708
10709         if (work != NULL && !is_mmio_work(work) &&
10710             intel_crtc_get_vblank_counter(crtc) - work->flip_queued_vblank > 1)
10711                 intel_queue_rps_boost_for_request(work->flip_queued_req);
10712         spin_unlock(&dev->event_lock);
10713 }
10714
10715 __maybe_unused
10716 static int intel_crtc_page_flip(struct drm_crtc *crtc,
10717                                 struct drm_framebuffer *fb,
10718                                 struct drm_pending_vblank_event *event,
10719                                 uint32_t page_flip_flags)
10720 {
10721         struct drm_device *dev = crtc->dev;
10722         struct drm_i915_private *dev_priv = to_i915(dev);
10723         struct drm_framebuffer *old_fb = crtc->primary->fb;
10724         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10725         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10726         struct drm_plane *primary = crtc->primary;
10727         enum pipe pipe = intel_crtc->pipe;
10728         struct intel_flip_work *work;
10729         struct intel_engine_cs *engine;
10730         bool mmio_flip;
10731         struct drm_i915_gem_request *request;
10732         struct i915_vma *vma;
10733         int ret;
10734
10735         /*
10736          * drm_mode_page_flip_ioctl() should already catch this, but double
10737          * check to be safe.  In the future we may enable pageflipping from
10738          * a disabled primary plane.
10739          */
10740         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
10741                 return -EBUSY;
10742
10743         /* Can't change pixel format via MI display flips. */
10744         if (fb->format != crtc->primary->fb->format)
10745                 return -EINVAL;
10746
10747         /*
10748          * TILEOFF/LINOFF registers can't be changed via MI display flips.
10749          * Note that pitch changes could also affect these register.
10750          */
10751         if (INTEL_GEN(dev_priv) > 3 &&
10752             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
10753              fb->pitches[0] != crtc->primary->fb->pitches[0]))
10754                 return -EINVAL;
10755
10756         if (i915_terminally_wedged(&dev_priv->gpu_error))
10757                 goto out_hang;
10758
10759         work = kzalloc(sizeof(*work), GFP_KERNEL);
10760         if (work == NULL)
10761                 return -ENOMEM;
10762
10763         work->event = event;
10764         work->crtc = crtc;
10765         work->old_fb = old_fb;
10766         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
10767
10768         ret = drm_crtc_vblank_get(crtc);
10769         if (ret)
10770                 goto free_work;
10771
10772         /* We borrow the event spin lock for protecting flip_work */
10773         spin_lock_irq(&dev->event_lock);
10774         if (intel_crtc->flip_work) {
10775                 /* Before declaring the flip queue wedged, check if
10776                  * the hardware completed the operation behind our backs.
10777                  */
10778                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
10779                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
10780                         page_flip_completed(intel_crtc);
10781                 } else {
10782                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
10783                         spin_unlock_irq(&dev->event_lock);
10784
10785                         drm_crtc_vblank_put(crtc);
10786                         kfree(work);
10787                         return -EBUSY;
10788                 }
10789         }
10790         intel_crtc->flip_work = work;
10791         spin_unlock_irq(&dev->event_lock);
10792
10793         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
10794                 flush_workqueue(dev_priv->wq);
10795
10796         /* Reference the objects for the scheduled work. */
10797         drm_framebuffer_reference(work->old_fb);
10798
10799         crtc->primary->fb = fb;
10800         update_state_fb(crtc->primary);
10801
10802         work->pending_flip_obj = i915_gem_object_get(obj);
10803
10804         ret = i915_mutex_lock_interruptible(dev);
10805         if (ret)
10806                 goto cleanup;
10807
10808         intel_crtc->reset_count = i915_reset_count(&dev_priv->gpu_error);
10809         if (i915_reset_backoff_or_wedged(&dev_priv->gpu_error)) {
10810                 ret = -EIO;
10811                 goto unlock;
10812         }
10813
10814         atomic_inc(&intel_crtc->unpin_work_count);
10815
10816         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10817                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
10818
10819         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
10820                 engine = dev_priv->engine[BCS];
10821                 if (fb->modifier != old_fb->modifier)
10822                         /* vlv: DISPLAY_FLIP fails to change tiling */
10823                         engine = NULL;
10824         } else if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv)) {
10825                 engine = dev_priv->engine[BCS];
10826         } else if (INTEL_GEN(dev_priv) >= 7) {
10827                 engine = i915_gem_object_last_write_engine(obj);
10828                 if (engine == NULL || engine->id != RCS)
10829                         engine = dev_priv->engine[BCS];
10830         } else {
10831                 engine = dev_priv->engine[RCS];
10832         }
10833
10834         mmio_flip = use_mmio_flip(engine, obj);
10835
10836         vma = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
10837         if (IS_ERR(vma)) {
10838                 ret = PTR_ERR(vma);
10839                 goto cleanup_pending;
10840         }
10841
10842         work->old_vma = to_intel_plane_state(primary->state)->vma;
10843         to_intel_plane_state(primary->state)->vma = vma;
10844
10845         work->gtt_offset = i915_ggtt_offset(vma) + intel_crtc->dspaddr_offset;
10846         work->rotation = crtc->primary->state->rotation;
10847
10848         /*
10849          * There's the potential that the next frame will not be compatible with
10850          * FBC, so we want to call pre_update() before the actual page flip.
10851          * The problem is that pre_update() caches some information about the fb
10852          * object, so we want to do this only after the object is pinned. Let's
10853          * be on the safe side and do this immediately before scheduling the
10854          * flip.
10855          */
10856         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
10857                              to_intel_plane_state(primary->state));
10858
10859         if (mmio_flip) {
10860                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
10861                 queue_work(system_unbound_wq, &work->mmio_work);
10862         } else {
10863                 request = i915_gem_request_alloc(engine,
10864                                                  dev_priv->kernel_context);
10865                 if (IS_ERR(request)) {
10866                         ret = PTR_ERR(request);
10867                         goto cleanup_unpin;
10868                 }
10869
10870                 ret = i915_gem_request_await_object(request, obj, false);
10871                 if (ret)
10872                         goto cleanup_request;
10873
10874                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
10875                                                    page_flip_flags);
10876                 if (ret)
10877                         goto cleanup_request;
10878
10879                 intel_mark_page_flip_active(intel_crtc, work);
10880
10881                 work->flip_queued_req = i915_gem_request_get(request);
10882                 i915_add_request(request);
10883         }
10884
10885         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
10886         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
10887                           to_intel_plane(primary)->frontbuffer_bit);
10888         mutex_unlock(&dev->struct_mutex);
10889
10890         intel_frontbuffer_flip_prepare(to_i915(dev),
10891                                        to_intel_plane(primary)->frontbuffer_bit);
10892
10893         trace_i915_flip_request(intel_crtc->plane, obj);
10894
10895         return 0;
10896
10897 cleanup_request:
10898         i915_add_request(request);
10899 cleanup_unpin:
10900         to_intel_plane_state(primary->state)->vma = work->old_vma;
10901         intel_unpin_fb_vma(vma);
10902 cleanup_pending:
10903         atomic_dec(&intel_crtc->unpin_work_count);
10904 unlock:
10905         mutex_unlock(&dev->struct_mutex);
10906 cleanup:
10907         crtc->primary->fb = old_fb;
10908         update_state_fb(crtc->primary);
10909
10910         i915_gem_object_put(obj);
10911         drm_framebuffer_unreference(work->old_fb);
10912
10913         spin_lock_irq(&dev->event_lock);
10914         intel_crtc->flip_work = NULL;
10915         spin_unlock_irq(&dev->event_lock);
10916
10917         drm_crtc_vblank_put(crtc);
10918 free_work:
10919         kfree(work);
10920
10921         if (ret == -EIO) {
10922                 struct drm_atomic_state *state;
10923                 struct drm_plane_state *plane_state;
10924
10925 out_hang:
10926                 state = drm_atomic_state_alloc(dev);
10927                 if (!state)
10928                         return -ENOMEM;
10929                 state->acquire_ctx = dev->mode_config.acquire_ctx;
10930
10931 retry:
10932                 plane_state = drm_atomic_get_plane_state(state, primary);
10933                 ret = PTR_ERR_OR_ZERO(plane_state);
10934                 if (!ret) {
10935                         drm_atomic_set_fb_for_plane(plane_state, fb);
10936
10937                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
10938                         if (!ret)
10939                                 ret = drm_atomic_commit(state);
10940                 }
10941
10942                 if (ret == -EDEADLK) {
10943                         drm_modeset_backoff(state->acquire_ctx);
10944                         drm_atomic_state_clear(state);
10945                         goto retry;
10946                 }
10947
10948                 drm_atomic_state_put(state);
10949
10950                 if (ret == 0 && event) {
10951                         spin_lock_irq(&dev->event_lock);
10952                         drm_crtc_send_vblank_event(crtc, event);
10953                         spin_unlock_irq(&dev->event_lock);
10954                 }
10955         }
10956         return ret;
10957 }
10958
10959
10960 /**
10961  * intel_wm_need_update - Check whether watermarks need updating
10962  * @plane: drm plane
10963  * @state: new plane state
10964  *
10965  * Check current plane state versus the new one to determine whether
10966  * watermarks need to be recalculated.
10967  *
10968  * Returns true or false.
10969  */
10970 static bool intel_wm_need_update(struct drm_plane *plane,
10971                                  struct drm_plane_state *state)
10972 {
10973         struct intel_plane_state *new = to_intel_plane_state(state);
10974         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10975
10976         /* Update watermarks on tiling or size changes. */
10977         if (new->base.visible != cur->base.visible)
10978                 return true;
10979
10980         if (!cur->base.fb || !new->base.fb)
10981                 return false;
10982
10983         if (cur->base.fb->modifier != new->base.fb->modifier ||
10984             cur->base.rotation != new->base.rotation ||
10985             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10986             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10987             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10988             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10989                 return true;
10990
10991         return false;
10992 }
10993
10994 static bool needs_scaling(struct intel_plane_state *state)
10995 {
10996         int src_w = drm_rect_width(&state->base.src) >> 16;
10997         int src_h = drm_rect_height(&state->base.src) >> 16;
10998         int dst_w = drm_rect_width(&state->base.dst);
10999         int dst_h = drm_rect_height(&state->base.dst);
11000
11001         return (src_w != dst_w || src_h != dst_h);
11002 }
11003
11004 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11005                                     struct drm_plane_state *plane_state)
11006 {
11007         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11008         struct drm_crtc *crtc = crtc_state->crtc;
11009         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11010         struct intel_plane *plane = to_intel_plane(plane_state->plane);
11011         struct drm_device *dev = crtc->dev;
11012         struct drm_i915_private *dev_priv = to_i915(dev);
11013         struct intel_plane_state *old_plane_state =
11014                 to_intel_plane_state(plane->base.state);
11015         bool mode_changed = needs_modeset(crtc_state);
11016         bool was_crtc_enabled = crtc->state->active;
11017         bool is_crtc_enabled = crtc_state->active;
11018         bool turn_off, turn_on, visible, was_visible;
11019         struct drm_framebuffer *fb = plane_state->fb;
11020         int ret;
11021
11022         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
11023                 ret = skl_update_scaler_plane(
11024                         to_intel_crtc_state(crtc_state),
11025                         to_intel_plane_state(plane_state));
11026                 if (ret)
11027                         return ret;
11028         }
11029
11030         was_visible = old_plane_state->base.visible;
11031         visible = plane_state->visible;
11032
11033         if (!was_crtc_enabled && WARN_ON(was_visible))
11034                 was_visible = false;
11035
11036         /*
11037          * Visibility is calculated as if the crtc was on, but
11038          * after scaler setup everything depends on it being off
11039          * when the crtc isn't active.
11040          *
11041          * FIXME this is wrong for watermarks. Watermarks should also
11042          * be computed as if the pipe would be active. Perhaps move
11043          * per-plane wm computation to the .check_plane() hook, and
11044          * only combine the results from all planes in the current place?
11045          */
11046         if (!is_crtc_enabled) {
11047                 plane_state->visible = visible = false;
11048                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
11049         }
11050
11051         if (!was_visible && !visible)
11052                 return 0;
11053
11054         if (fb != old_plane_state->base.fb)
11055                 pipe_config->fb_changed = true;
11056
11057         turn_off = was_visible && (!visible || mode_changed);
11058         turn_on = visible && (!was_visible || mode_changed);
11059
11060         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11061                          intel_crtc->base.base.id, intel_crtc->base.name,
11062                          plane->base.base.id, plane->base.name,
11063                          fb ? fb->base.id : -1);
11064
11065         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11066                          plane->base.base.id, plane->base.name,
11067                          was_visible, visible,
11068                          turn_off, turn_on, mode_changed);
11069
11070         if (turn_on) {
11071                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11072                         pipe_config->update_wm_pre = true;
11073
11074                 /* must disable cxsr around plane enable/disable */
11075                 if (plane->id != PLANE_CURSOR)
11076                         pipe_config->disable_cxsr = true;
11077         } else if (turn_off) {
11078                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11079                         pipe_config->update_wm_post = true;
11080
11081                 /* must disable cxsr around plane enable/disable */
11082                 if (plane->id != PLANE_CURSOR)
11083                         pipe_config->disable_cxsr = true;
11084         } else if (intel_wm_need_update(&plane->base, plane_state)) {
11085                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
11086                         /* FIXME bollocks */
11087                         pipe_config->update_wm_pre = true;
11088                         pipe_config->update_wm_post = true;
11089                 }
11090         }
11091
11092         if (visible || was_visible)
11093                 pipe_config->fb_bits |= plane->frontbuffer_bit;
11094
11095         /*
11096          * WaCxSRDisabledForSpriteScaling:ivb
11097          *
11098          * cstate->update_wm was already set above, so this flag will
11099          * take effect when we commit and program watermarks.
11100          */
11101         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
11102             needs_scaling(to_intel_plane_state(plane_state)) &&
11103             !needs_scaling(old_plane_state))
11104                 pipe_config->disable_lp_wm = true;
11105
11106         return 0;
11107 }
11108
11109 static bool encoders_cloneable(const struct intel_encoder *a,
11110                                const struct intel_encoder *b)
11111 {
11112         /* masks could be asymmetric, so check both ways */
11113         return a == b || (a->cloneable & (1 << b->type) &&
11114                           b->cloneable & (1 << a->type));
11115 }
11116
11117 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11118                                          struct intel_crtc *crtc,
11119                                          struct intel_encoder *encoder)
11120 {
11121         struct intel_encoder *source_encoder;
11122         struct drm_connector *connector;
11123         struct drm_connector_state *connector_state;
11124         int i;
11125
11126         for_each_new_connector_in_state(state, connector, connector_state, i) {
11127                 if (connector_state->crtc != &crtc->base)
11128                         continue;
11129
11130                 source_encoder =
11131                         to_intel_encoder(connector_state->best_encoder);
11132                 if (!encoders_cloneable(encoder, source_encoder))
11133                         return false;
11134         }
11135
11136         return true;
11137 }
11138
11139 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11140                                    struct drm_crtc_state *crtc_state)
11141 {
11142         struct drm_device *dev = crtc->dev;
11143         struct drm_i915_private *dev_priv = to_i915(dev);
11144         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11145         struct intel_crtc_state *pipe_config =
11146                 to_intel_crtc_state(crtc_state);
11147         struct drm_atomic_state *state = crtc_state->state;
11148         int ret;
11149         bool mode_changed = needs_modeset(crtc_state);
11150
11151         if (mode_changed && !crtc_state->active)
11152                 pipe_config->update_wm_post = true;
11153
11154         if (mode_changed && crtc_state->enable &&
11155             dev_priv->display.crtc_compute_clock &&
11156             !WARN_ON(pipe_config->shared_dpll)) {
11157                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11158                                                            pipe_config);
11159                 if (ret)
11160                         return ret;
11161         }
11162
11163         if (crtc_state->color_mgmt_changed) {
11164                 ret = intel_color_check(crtc, crtc_state);
11165                 if (ret)
11166                         return ret;
11167
11168                 /*
11169                  * Changing color management on Intel hardware is
11170                  * handled as part of planes update.
11171                  */
11172                 crtc_state->planes_changed = true;
11173         }
11174
11175         ret = 0;
11176         if (dev_priv->display.compute_pipe_wm) {
11177                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11178                 if (ret) {
11179                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11180                         return ret;
11181                 }
11182         }
11183
11184         if (dev_priv->display.compute_intermediate_wm &&
11185             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11186                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11187                         return 0;
11188
11189                 /*
11190                  * Calculate 'intermediate' watermarks that satisfy both the
11191                  * old state and the new state.  We can program these
11192                  * immediately.
11193                  */
11194                 ret = dev_priv->display.compute_intermediate_wm(dev,
11195                                                                 intel_crtc,
11196                                                                 pipe_config);
11197                 if (ret) {
11198                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11199                         return ret;
11200                 }
11201         } else if (dev_priv->display.compute_intermediate_wm) {
11202                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
11203                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
11204         }
11205
11206         if (INTEL_GEN(dev_priv) >= 9) {
11207                 if (mode_changed)
11208                         ret = skl_update_scaler_crtc(pipe_config);
11209
11210                 if (!ret)
11211                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11212                                                             pipe_config);
11213                 if (!ret)
11214                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11215                                                          pipe_config);
11216         }
11217
11218         return ret;
11219 }
11220
11221 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11222         .atomic_begin = intel_begin_crtc_commit,
11223         .atomic_flush = intel_finish_crtc_commit,
11224         .atomic_check = intel_crtc_atomic_check,
11225 };
11226
11227 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11228 {
11229         struct intel_connector *connector;
11230         struct drm_connector_list_iter conn_iter;
11231
11232         drm_connector_list_iter_begin(dev, &conn_iter);
11233         for_each_intel_connector_iter(connector, &conn_iter) {
11234                 if (connector->base.state->crtc)
11235                         drm_connector_unreference(&connector->base);
11236
11237                 if (connector->base.encoder) {
11238                         connector->base.state->best_encoder =
11239                                 connector->base.encoder;
11240                         connector->base.state->crtc =
11241                                 connector->base.encoder->crtc;
11242
11243                         drm_connector_reference(&connector->base);
11244                 } else {
11245                         connector->base.state->best_encoder = NULL;
11246                         connector->base.state->crtc = NULL;
11247                 }
11248         }
11249         drm_connector_list_iter_end(&conn_iter);
11250 }
11251
11252 static void
11253 connected_sink_compute_bpp(struct intel_connector *connector,
11254                            struct intel_crtc_state *pipe_config)
11255 {
11256         const struct drm_display_info *info = &connector->base.display_info;
11257         int bpp = pipe_config->pipe_bpp;
11258
11259         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11260                       connector->base.base.id,
11261                       connector->base.name);
11262
11263         /* Don't use an invalid EDID bpc value */
11264         if (info->bpc != 0 && info->bpc * 3 < bpp) {
11265                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11266                               bpp, info->bpc * 3);
11267                 pipe_config->pipe_bpp = info->bpc * 3;
11268         }
11269
11270         /* Clamp bpp to 8 on screens without EDID 1.4 */
11271         if (info->bpc == 0 && bpp > 24) {
11272                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11273                               bpp);
11274                 pipe_config->pipe_bpp = 24;
11275         }
11276 }
11277
11278 static int
11279 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11280                           struct intel_crtc_state *pipe_config)
11281 {
11282         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11283         struct drm_atomic_state *state;
11284         struct drm_connector *connector;
11285         struct drm_connector_state *connector_state;
11286         int bpp, i;
11287
11288         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11289             IS_CHERRYVIEW(dev_priv)))
11290                 bpp = 10*3;
11291         else if (INTEL_GEN(dev_priv) >= 5)
11292                 bpp = 12*3;
11293         else
11294                 bpp = 8*3;
11295
11296
11297         pipe_config->pipe_bpp = bpp;
11298
11299         state = pipe_config->base.state;
11300
11301         /* Clamp display bpp to EDID value */
11302         for_each_new_connector_in_state(state, connector, connector_state, i) {
11303                 if (connector_state->crtc != &crtc->base)
11304                         continue;
11305
11306                 connected_sink_compute_bpp(to_intel_connector(connector),
11307                                            pipe_config);
11308         }
11309
11310         return bpp;
11311 }
11312
11313 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11314 {
11315         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11316                         "type: 0x%x flags: 0x%x\n",
11317                 mode->crtc_clock,
11318                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11319                 mode->crtc_hsync_end, mode->crtc_htotal,
11320                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11321                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11322 }
11323
11324 static inline void
11325 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11326                       unsigned int lane_count, struct intel_link_m_n *m_n)
11327 {
11328         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11329                       id, lane_count,
11330                       m_n->gmch_m, m_n->gmch_n,
11331                       m_n->link_m, m_n->link_n, m_n->tu);
11332 }
11333
11334 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11335                                    struct intel_crtc_state *pipe_config,
11336                                    const char *context)
11337 {
11338         struct drm_device *dev = crtc->base.dev;
11339         struct drm_i915_private *dev_priv = to_i915(dev);
11340         struct drm_plane *plane;
11341         struct intel_plane *intel_plane;
11342         struct intel_plane_state *state;
11343         struct drm_framebuffer *fb;
11344
11345         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11346                       crtc->base.base.id, crtc->base.name, context);
11347
11348         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11349                       transcoder_name(pipe_config->cpu_transcoder),
11350                       pipe_config->pipe_bpp, pipe_config->dither);
11351
11352         if (pipe_config->has_pch_encoder)
11353                 intel_dump_m_n_config(pipe_config, "fdi",
11354                                       pipe_config->fdi_lanes,
11355                                       &pipe_config->fdi_m_n);
11356
11357         if (intel_crtc_has_dp_encoder(pipe_config)) {
11358                 intel_dump_m_n_config(pipe_config, "dp m_n",
11359                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11360                 if (pipe_config->has_drrs)
11361                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11362                                               pipe_config->lane_count,
11363                                               &pipe_config->dp_m2_n2);
11364         }
11365
11366         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11367                       pipe_config->has_audio, pipe_config->has_infoframe);
11368
11369         DRM_DEBUG_KMS("requested mode:\n");
11370         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11371         DRM_DEBUG_KMS("adjusted mode:\n");
11372         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11373         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11374         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11375                       pipe_config->port_clock,
11376                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11377                       pipe_config->pixel_rate);
11378
11379         if (INTEL_GEN(dev_priv) >= 9)
11380                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11381                               crtc->num_scalers,
11382                               pipe_config->scaler_state.scaler_users,
11383                               pipe_config->scaler_state.scaler_id);
11384
11385         if (HAS_GMCH_DISPLAY(dev_priv))
11386                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11387                               pipe_config->gmch_pfit.control,
11388                               pipe_config->gmch_pfit.pgm_ratios,
11389                               pipe_config->gmch_pfit.lvds_border_bits);
11390         else
11391                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11392                               pipe_config->pch_pfit.pos,
11393                               pipe_config->pch_pfit.size,
11394                               enableddisabled(pipe_config->pch_pfit.enabled));
11395
11396         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11397                       pipe_config->ips_enabled, pipe_config->double_wide);
11398
11399         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11400
11401         DRM_DEBUG_KMS("planes on this crtc\n");
11402         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11403                 struct drm_format_name_buf format_name;
11404                 intel_plane = to_intel_plane(plane);
11405                 if (intel_plane->pipe != crtc->pipe)
11406                         continue;
11407
11408                 state = to_intel_plane_state(plane->state);
11409                 fb = state->base.fb;
11410                 if (!fb) {
11411                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11412                                       plane->base.id, plane->name, state->scaler_id);
11413                         continue;
11414                 }
11415
11416                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11417                               plane->base.id, plane->name,
11418                               fb->base.id, fb->width, fb->height,
11419                               drm_get_format_name(fb->format->format, &format_name));
11420                 if (INTEL_GEN(dev_priv) >= 9)
11421                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11422                                       state->scaler_id,
11423                                       state->base.src.x1 >> 16,
11424                                       state->base.src.y1 >> 16,
11425                                       drm_rect_width(&state->base.src) >> 16,
11426                                       drm_rect_height(&state->base.src) >> 16,
11427                                       state->base.dst.x1, state->base.dst.y1,
11428                                       drm_rect_width(&state->base.dst),
11429                                       drm_rect_height(&state->base.dst));
11430         }
11431 }
11432
11433 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11434 {
11435         struct drm_device *dev = state->dev;
11436         struct drm_connector *connector;
11437         unsigned int used_ports = 0;
11438         unsigned int used_mst_ports = 0;
11439
11440         /*
11441          * Walk the connector list instead of the encoder
11442          * list to detect the problem on ddi platforms
11443          * where there's just one encoder per digital port.
11444          */
11445         drm_for_each_connector(connector, dev) {
11446                 struct drm_connector_state *connector_state;
11447                 struct intel_encoder *encoder;
11448
11449                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
11450                 if (!connector_state)
11451                         connector_state = connector->state;
11452
11453                 if (!connector_state->best_encoder)
11454                         continue;
11455
11456                 encoder = to_intel_encoder(connector_state->best_encoder);
11457
11458                 WARN_ON(!connector_state->crtc);
11459
11460                 switch (encoder->type) {
11461                         unsigned int port_mask;
11462                 case INTEL_OUTPUT_UNKNOWN:
11463                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11464                                 break;
11465                 case INTEL_OUTPUT_DP:
11466                 case INTEL_OUTPUT_HDMI:
11467                 case INTEL_OUTPUT_EDP:
11468                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
11469
11470                         /* the same port mustn't appear more than once */
11471                         if (used_ports & port_mask)
11472                                 return false;
11473
11474                         used_ports |= port_mask;
11475                         break;
11476                 case INTEL_OUTPUT_DP_MST:
11477                         used_mst_ports |=
11478                                 1 << enc_to_mst(&encoder->base)->primary->port;
11479                         break;
11480                 default:
11481                         break;
11482                 }
11483         }
11484
11485         /* can't mix MST and SST/HDMI on the same port */
11486         if (used_ports & used_mst_ports)
11487                 return false;
11488
11489         return true;
11490 }
11491
11492 static void
11493 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11494 {
11495         struct drm_i915_private *dev_priv =
11496                 to_i915(crtc_state->base.crtc->dev);
11497         struct intel_crtc_scaler_state scaler_state;
11498         struct intel_dpll_hw_state dpll_hw_state;
11499         struct intel_shared_dpll *shared_dpll;
11500         struct intel_crtc_wm_state wm_state;
11501         bool force_thru;
11502
11503         /* FIXME: before the switch to atomic started, a new pipe_config was
11504          * kzalloc'd. Code that depends on any field being zero should be
11505          * fixed, so that the crtc_state can be safely duplicated. For now,
11506          * only fields that are know to not cause problems are preserved. */
11507
11508         scaler_state = crtc_state->scaler_state;
11509         shared_dpll = crtc_state->shared_dpll;
11510         dpll_hw_state = crtc_state->dpll_hw_state;
11511         force_thru = crtc_state->pch_pfit.force_thru;
11512         if (IS_G4X(dev_priv) ||
11513             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11514                 wm_state = crtc_state->wm;
11515
11516         /* Keep base drm_crtc_state intact, only clear our extended struct */
11517         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11518         memset(&crtc_state->base + 1, 0,
11519                sizeof(*crtc_state) - sizeof(crtc_state->base));
11520
11521         crtc_state->scaler_state = scaler_state;
11522         crtc_state->shared_dpll = shared_dpll;
11523         crtc_state->dpll_hw_state = dpll_hw_state;
11524         crtc_state->pch_pfit.force_thru = force_thru;
11525         if (IS_G4X(dev_priv) ||
11526             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11527                 crtc_state->wm = wm_state;
11528 }
11529
11530 static int
11531 intel_modeset_pipe_config(struct drm_crtc *crtc,
11532                           struct intel_crtc_state *pipe_config)
11533 {
11534         struct drm_atomic_state *state = pipe_config->base.state;
11535         struct intel_encoder *encoder;
11536         struct drm_connector *connector;
11537         struct drm_connector_state *connector_state;
11538         int base_bpp, ret = -EINVAL;
11539         int i;
11540         bool retry = true;
11541
11542         clear_intel_crtc_state(pipe_config);
11543
11544         pipe_config->cpu_transcoder =
11545                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11546
11547         /*
11548          * Sanitize sync polarity flags based on requested ones. If neither
11549          * positive or negative polarity is requested, treat this as meaning
11550          * negative polarity.
11551          */
11552         if (!(pipe_config->base.adjusted_mode.flags &
11553               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11554                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11555
11556         if (!(pipe_config->base.adjusted_mode.flags &
11557               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11558                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11559
11560         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11561                                              pipe_config);
11562         if (base_bpp < 0)
11563                 goto fail;
11564
11565         /*
11566          * Determine the real pipe dimensions. Note that stereo modes can
11567          * increase the actual pipe size due to the frame doubling and
11568          * insertion of additional space for blanks between the frame. This
11569          * is stored in the crtc timings. We use the requested mode to do this
11570          * computation to clearly distinguish it from the adjusted mode, which
11571          * can be changed by the connectors in the below retry loop.
11572          */
11573         drm_mode_get_hv_timing(&pipe_config->base.mode,
11574                                &pipe_config->pipe_src_w,
11575                                &pipe_config->pipe_src_h);
11576
11577         for_each_new_connector_in_state(state, connector, connector_state, i) {
11578                 if (connector_state->crtc != crtc)
11579                         continue;
11580
11581                 encoder = to_intel_encoder(connector_state->best_encoder);
11582
11583                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11584                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11585                         goto fail;
11586                 }
11587
11588                 /*
11589                  * Determine output_types before calling the .compute_config()
11590                  * hooks so that the hooks can use this information safely.
11591                  */
11592                 pipe_config->output_types |= 1 << encoder->type;
11593         }
11594
11595 encoder_retry:
11596         /* Ensure the port clock defaults are reset when retrying. */
11597         pipe_config->port_clock = 0;
11598         pipe_config->pixel_multiplier = 1;
11599
11600         /* Fill in default crtc timings, allow encoders to overwrite them. */
11601         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11602                               CRTC_STEREO_DOUBLE);
11603
11604         /* Pass our mode to the connectors and the CRTC to give them a chance to
11605          * adjust it according to limitations or connector properties, and also
11606          * a chance to reject the mode entirely.
11607          */
11608         for_each_new_connector_in_state(state, connector, connector_state, i) {
11609                 if (connector_state->crtc != crtc)
11610                         continue;
11611
11612                 encoder = to_intel_encoder(connector_state->best_encoder);
11613
11614                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11615                         DRM_DEBUG_KMS("Encoder config failure\n");
11616                         goto fail;
11617                 }
11618         }
11619
11620         /* Set default port clock if not overwritten by the encoder. Needs to be
11621          * done afterwards in case the encoder adjusts the mode. */
11622         if (!pipe_config->port_clock)
11623                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11624                         * pipe_config->pixel_multiplier;
11625
11626         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11627         if (ret < 0) {
11628                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11629                 goto fail;
11630         }
11631
11632         if (ret == RETRY) {
11633                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11634                         ret = -EINVAL;
11635                         goto fail;
11636                 }
11637
11638                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11639                 retry = false;
11640                 goto encoder_retry;
11641         }
11642
11643         /* Dithering seems to not pass-through bits correctly when it should, so
11644          * only enable it on 6bpc panels and when its not a compliance
11645          * test requesting 6bpc video pattern.
11646          */
11647         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11648                 !pipe_config->dither_force_disable;
11649         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11650                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11651
11652 fail:
11653         return ret;
11654 }
11655
11656 static void
11657 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
11658 {
11659         struct drm_crtc *crtc;
11660         struct drm_crtc_state *new_crtc_state;
11661         int i;
11662
11663         /* Double check state. */
11664         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11665                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
11666
11667                 /*
11668                  * Update legacy state to satisfy fbc code. This can
11669                  * be removed when fbc uses the atomic state.
11670                  */
11671                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
11672                         struct drm_plane_state *plane_state = crtc->primary->state;
11673
11674                         crtc->primary->fb = plane_state->fb;
11675                         crtc->x = plane_state->src_x >> 16;
11676                         crtc->y = plane_state->src_y >> 16;
11677                 }
11678         }
11679 }
11680
11681 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11682 {
11683         int diff;
11684
11685         if (clock1 == clock2)
11686                 return true;
11687
11688         if (!clock1 || !clock2)
11689                 return false;
11690
11691         diff = abs(clock1 - clock2);
11692
11693         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11694                 return true;
11695
11696         return false;
11697 }
11698
11699 static bool
11700 intel_compare_m_n(unsigned int m, unsigned int n,
11701                   unsigned int m2, unsigned int n2,
11702                   bool exact)
11703 {
11704         if (m == m2 && n == n2)
11705                 return true;
11706
11707         if (exact || !m || !n || !m2 || !n2)
11708                 return false;
11709
11710         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11711
11712         if (n > n2) {
11713                 while (n > n2) {
11714                         m2 <<= 1;
11715                         n2 <<= 1;
11716                 }
11717         } else if (n < n2) {
11718                 while (n < n2) {
11719                         m <<= 1;
11720                         n <<= 1;
11721                 }
11722         }
11723
11724         if (n != n2)
11725                 return false;
11726
11727         return intel_fuzzy_clock_check(m, m2);
11728 }
11729
11730 static bool
11731 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11732                        struct intel_link_m_n *m2_n2,
11733                        bool adjust)
11734 {
11735         if (m_n->tu == m2_n2->tu &&
11736             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11737                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11738             intel_compare_m_n(m_n->link_m, m_n->link_n,
11739                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11740                 if (adjust)
11741                         *m2_n2 = *m_n;
11742
11743                 return true;
11744         }
11745
11746         return false;
11747 }
11748
11749 static void __printf(3, 4)
11750 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11751 {
11752         char *level;
11753         unsigned int category;
11754         struct va_format vaf;
11755         va_list args;
11756
11757         if (adjust) {
11758                 level = KERN_DEBUG;
11759                 category = DRM_UT_KMS;
11760         } else {
11761                 level = KERN_ERR;
11762                 category = DRM_UT_NONE;
11763         }
11764
11765         va_start(args, format);
11766         vaf.fmt = format;
11767         vaf.va = &args;
11768
11769         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
11770
11771         va_end(args);
11772 }
11773
11774 static bool
11775 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11776                           struct intel_crtc_state *current_config,
11777                           struct intel_crtc_state *pipe_config,
11778                           bool adjust)
11779 {
11780         bool ret = true;
11781
11782 #define PIPE_CONF_CHECK_X(name) \
11783         if (current_config->name != pipe_config->name) { \
11784                 pipe_config_err(adjust, __stringify(name), \
11785                           "(expected 0x%08x, found 0x%08x)\n", \
11786                           current_config->name, \
11787                           pipe_config->name); \
11788                 ret = false; \
11789         }
11790
11791 #define PIPE_CONF_CHECK_I(name) \
11792         if (current_config->name != pipe_config->name) { \
11793                 pipe_config_err(adjust, __stringify(name), \
11794                           "(expected %i, found %i)\n", \
11795                           current_config->name, \
11796                           pipe_config->name); \
11797                 ret = false; \
11798         }
11799
11800 #define PIPE_CONF_CHECK_P(name) \
11801         if (current_config->name != pipe_config->name) { \
11802                 pipe_config_err(adjust, __stringify(name), \
11803                           "(expected %p, found %p)\n", \
11804                           current_config->name, \
11805                           pipe_config->name); \
11806                 ret = false; \
11807         }
11808
11809 #define PIPE_CONF_CHECK_M_N(name) \
11810         if (!intel_compare_link_m_n(&current_config->name, \
11811                                     &pipe_config->name,\
11812                                     adjust)) { \
11813                 pipe_config_err(adjust, __stringify(name), \
11814                           "(expected tu %i gmch %i/%i link %i/%i, " \
11815                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11816                           current_config->name.tu, \
11817                           current_config->name.gmch_m, \
11818                           current_config->name.gmch_n, \
11819                           current_config->name.link_m, \
11820                           current_config->name.link_n, \
11821                           pipe_config->name.tu, \
11822                           pipe_config->name.gmch_m, \
11823                           pipe_config->name.gmch_n, \
11824                           pipe_config->name.link_m, \
11825                           pipe_config->name.link_n); \
11826                 ret = false; \
11827         }
11828
11829 /* This is required for BDW+ where there is only one set of registers for
11830  * switching between high and low RR.
11831  * This macro can be used whenever a comparison has to be made between one
11832  * hw state and multiple sw state variables.
11833  */
11834 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11835         if (!intel_compare_link_m_n(&current_config->name, \
11836                                     &pipe_config->name, adjust) && \
11837             !intel_compare_link_m_n(&current_config->alt_name, \
11838                                     &pipe_config->name, adjust)) { \
11839                 pipe_config_err(adjust, __stringify(name), \
11840                           "(expected tu %i gmch %i/%i link %i/%i, " \
11841                           "or tu %i gmch %i/%i link %i/%i, " \
11842                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11843                           current_config->name.tu, \
11844                           current_config->name.gmch_m, \
11845                           current_config->name.gmch_n, \
11846                           current_config->name.link_m, \
11847                           current_config->name.link_n, \
11848                           current_config->alt_name.tu, \
11849                           current_config->alt_name.gmch_m, \
11850                           current_config->alt_name.gmch_n, \
11851                           current_config->alt_name.link_m, \
11852                           current_config->alt_name.link_n, \
11853                           pipe_config->name.tu, \
11854                           pipe_config->name.gmch_m, \
11855                           pipe_config->name.gmch_n, \
11856                           pipe_config->name.link_m, \
11857                           pipe_config->name.link_n); \
11858                 ret = false; \
11859         }
11860
11861 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11862         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11863                 pipe_config_err(adjust, __stringify(name), \
11864                           "(%x) (expected %i, found %i)\n", \
11865                           (mask), \
11866                           current_config->name & (mask), \
11867                           pipe_config->name & (mask)); \
11868                 ret = false; \
11869         }
11870
11871 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11872         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11873                 pipe_config_err(adjust, __stringify(name), \
11874                           "(expected %i, found %i)\n", \
11875                           current_config->name, \
11876                           pipe_config->name); \
11877                 ret = false; \
11878         }
11879
11880 #define PIPE_CONF_QUIRK(quirk)  \
11881         ((current_config->quirks | pipe_config->quirks) & (quirk))
11882
11883         PIPE_CONF_CHECK_I(cpu_transcoder);
11884
11885         PIPE_CONF_CHECK_I(has_pch_encoder);
11886         PIPE_CONF_CHECK_I(fdi_lanes);
11887         PIPE_CONF_CHECK_M_N(fdi_m_n);
11888
11889         PIPE_CONF_CHECK_I(lane_count);
11890         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11891
11892         if (INTEL_GEN(dev_priv) < 8) {
11893                 PIPE_CONF_CHECK_M_N(dp_m_n);
11894
11895                 if (current_config->has_drrs)
11896                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11897         } else
11898                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11899
11900         PIPE_CONF_CHECK_X(output_types);
11901
11902         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11903         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11904         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11905         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11906         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11907         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11908
11909         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11910         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11911         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11912         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11913         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11914         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11915
11916         PIPE_CONF_CHECK_I(pixel_multiplier);
11917         PIPE_CONF_CHECK_I(has_hdmi_sink);
11918         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11919             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11920                 PIPE_CONF_CHECK_I(limited_color_range);
11921
11922         PIPE_CONF_CHECK_I(hdmi_scrambling);
11923         PIPE_CONF_CHECK_I(hdmi_high_tmds_clock_ratio);
11924         PIPE_CONF_CHECK_I(has_infoframe);
11925
11926         PIPE_CONF_CHECK_I(has_audio);
11927
11928         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11929                               DRM_MODE_FLAG_INTERLACE);
11930
11931         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11932                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11933                                       DRM_MODE_FLAG_PHSYNC);
11934                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11935                                       DRM_MODE_FLAG_NHSYNC);
11936                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11937                                       DRM_MODE_FLAG_PVSYNC);
11938                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11939                                       DRM_MODE_FLAG_NVSYNC);
11940         }
11941
11942         PIPE_CONF_CHECK_X(gmch_pfit.control);
11943         /* pfit ratios are autocomputed by the hw on gen4+ */
11944         if (INTEL_GEN(dev_priv) < 4)
11945                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11946         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11947
11948         if (!adjust) {
11949                 PIPE_CONF_CHECK_I(pipe_src_w);
11950                 PIPE_CONF_CHECK_I(pipe_src_h);
11951
11952                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
11953                 if (current_config->pch_pfit.enabled) {
11954                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11955                         PIPE_CONF_CHECK_X(pch_pfit.size);
11956                 }
11957
11958                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11959                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11960         }
11961
11962         /* BDW+ don't expose a synchronous way to read the state */
11963         if (IS_HASWELL(dev_priv))
11964                 PIPE_CONF_CHECK_I(ips_enabled);
11965
11966         PIPE_CONF_CHECK_I(double_wide);
11967
11968         PIPE_CONF_CHECK_P(shared_dpll);
11969         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11970         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11971         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11972         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11973         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11974         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11975         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11976         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11977         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11978
11979         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11980         PIPE_CONF_CHECK_X(dsi_pll.div);
11981
11982         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11983                 PIPE_CONF_CHECK_I(pipe_bpp);
11984
11985         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11986         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11987
11988 #undef PIPE_CONF_CHECK_X
11989 #undef PIPE_CONF_CHECK_I
11990 #undef PIPE_CONF_CHECK_P
11991 #undef PIPE_CONF_CHECK_FLAGS
11992 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11993 #undef PIPE_CONF_QUIRK
11994
11995         return ret;
11996 }
11997
11998 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11999                                            const struct intel_crtc_state *pipe_config)
12000 {
12001         if (pipe_config->has_pch_encoder) {
12002                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12003                                                             &pipe_config->fdi_m_n);
12004                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12005
12006                 /*
12007                  * FDI already provided one idea for the dotclock.
12008                  * Yell if the encoder disagrees.
12009                  */
12010                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12011                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12012                      fdi_dotclock, dotclock);
12013         }
12014 }
12015
12016 static void verify_wm_state(struct drm_crtc *crtc,
12017                             struct drm_crtc_state *new_state)
12018 {
12019         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12020         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12021         struct skl_pipe_wm hw_wm, *sw_wm;
12022         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12023         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12024         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12025         const enum pipe pipe = intel_crtc->pipe;
12026         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12027
12028         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12029                 return;
12030
12031         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
12032         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12033
12034         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12035         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12036
12037         /* planes */
12038         for_each_universal_plane(dev_priv, pipe, plane) {
12039                 hw_plane_wm = &hw_wm.planes[plane];
12040                 sw_plane_wm = &sw_wm->planes[plane];
12041
12042                 /* Watermarks */
12043                 for (level = 0; level <= max_level; level++) {
12044                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12045                                                 &sw_plane_wm->wm[level]))
12046                                 continue;
12047
12048                         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",
12049                                   pipe_name(pipe), plane + 1, level,
12050                                   sw_plane_wm->wm[level].plane_en,
12051                                   sw_plane_wm->wm[level].plane_res_b,
12052                                   sw_plane_wm->wm[level].plane_res_l,
12053                                   hw_plane_wm->wm[level].plane_en,
12054                                   hw_plane_wm->wm[level].plane_res_b,
12055                                   hw_plane_wm->wm[level].plane_res_l);
12056                 }
12057
12058                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12059                                          &sw_plane_wm->trans_wm)) {
12060                         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",
12061                                   pipe_name(pipe), plane + 1,
12062                                   sw_plane_wm->trans_wm.plane_en,
12063                                   sw_plane_wm->trans_wm.plane_res_b,
12064                                   sw_plane_wm->trans_wm.plane_res_l,
12065                                   hw_plane_wm->trans_wm.plane_en,
12066                                   hw_plane_wm->trans_wm.plane_res_b,
12067                                   hw_plane_wm->trans_wm.plane_res_l);
12068                 }
12069
12070                 /* DDB */
12071                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
12072                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
12073
12074                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12075                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12076                                   pipe_name(pipe), plane + 1,
12077                                   sw_ddb_entry->start, sw_ddb_entry->end,
12078                                   hw_ddb_entry->start, hw_ddb_entry->end);
12079                 }
12080         }
12081
12082         /*
12083          * cursor
12084          * If the cursor plane isn't active, we may not have updated it's ddb
12085          * allocation. In that case since the ddb allocation will be updated
12086          * once the plane becomes visible, we can skip this check
12087          */
12088         if (1) {
12089                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
12090                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12091
12092                 /* Watermarks */
12093                 for (level = 0; level <= max_level; level++) {
12094                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12095                                                 &sw_plane_wm->wm[level]))
12096                                 continue;
12097
12098                         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",
12099                                   pipe_name(pipe), level,
12100                                   sw_plane_wm->wm[level].plane_en,
12101                                   sw_plane_wm->wm[level].plane_res_b,
12102                                   sw_plane_wm->wm[level].plane_res_l,
12103                                   hw_plane_wm->wm[level].plane_en,
12104                                   hw_plane_wm->wm[level].plane_res_b,
12105                                   hw_plane_wm->wm[level].plane_res_l);
12106                 }
12107
12108                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12109                                          &sw_plane_wm->trans_wm)) {
12110                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12111                                   pipe_name(pipe),
12112                                   sw_plane_wm->trans_wm.plane_en,
12113                                   sw_plane_wm->trans_wm.plane_res_b,
12114                                   sw_plane_wm->trans_wm.plane_res_l,
12115                                   hw_plane_wm->trans_wm.plane_en,
12116                                   hw_plane_wm->trans_wm.plane_res_b,
12117                                   hw_plane_wm->trans_wm.plane_res_l);
12118                 }
12119
12120                 /* DDB */
12121                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12122                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12123
12124                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12125                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12126                                   pipe_name(pipe),
12127                                   sw_ddb_entry->start, sw_ddb_entry->end,
12128                                   hw_ddb_entry->start, hw_ddb_entry->end);
12129                 }
12130         }
12131 }
12132
12133 static void
12134 verify_connector_state(struct drm_device *dev,
12135                        struct drm_atomic_state *state,
12136                        struct drm_crtc *crtc)
12137 {
12138         struct drm_connector *connector;
12139         struct drm_connector_state *new_conn_state;
12140         int i;
12141
12142         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12143                 struct drm_encoder *encoder = connector->encoder;
12144                 struct drm_crtc_state *crtc_state = NULL;
12145
12146                 if (new_conn_state->crtc != crtc)
12147                         continue;
12148
12149                 if (crtc)
12150                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12151
12152                 intel_connector_verify_state(crtc_state, new_conn_state);
12153
12154                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12155                      "connector's atomic encoder doesn't match legacy encoder\n");
12156         }
12157 }
12158
12159 static void
12160 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12161 {
12162         struct intel_encoder *encoder;
12163         struct drm_connector *connector;
12164         struct drm_connector_state *old_conn_state, *new_conn_state;
12165         int i;
12166
12167         for_each_intel_encoder(dev, encoder) {
12168                 bool enabled = false, found = false;
12169                 enum pipe pipe;
12170
12171                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12172                               encoder->base.base.id,
12173                               encoder->base.name);
12174
12175                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12176                                                    new_conn_state, i) {
12177                         if (old_conn_state->best_encoder == &encoder->base)
12178                                 found = true;
12179
12180                         if (new_conn_state->best_encoder != &encoder->base)
12181                                 continue;
12182                         found = enabled = true;
12183
12184                         I915_STATE_WARN(new_conn_state->crtc !=
12185                                         encoder->base.crtc,
12186                              "connector's crtc doesn't match encoder crtc\n");
12187                 }
12188
12189                 if (!found)
12190                         continue;
12191
12192                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12193                      "encoder's enabled state mismatch "
12194                      "(expected %i, found %i)\n",
12195                      !!encoder->base.crtc, enabled);
12196
12197                 if (!encoder->base.crtc) {
12198                         bool active;
12199
12200                         active = encoder->get_hw_state(encoder, &pipe);
12201                         I915_STATE_WARN(active,
12202                              "encoder detached but still enabled on pipe %c.\n",
12203                              pipe_name(pipe));
12204                 }
12205         }
12206 }
12207
12208 static void
12209 verify_crtc_state(struct drm_crtc *crtc,
12210                   struct drm_crtc_state *old_crtc_state,
12211                   struct drm_crtc_state *new_crtc_state)
12212 {
12213         struct drm_device *dev = crtc->dev;
12214         struct drm_i915_private *dev_priv = to_i915(dev);
12215         struct intel_encoder *encoder;
12216         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12217         struct intel_crtc_state *pipe_config, *sw_config;
12218         struct drm_atomic_state *old_state;
12219         bool active;
12220
12221         old_state = old_crtc_state->state;
12222         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12223         pipe_config = to_intel_crtc_state(old_crtc_state);
12224         memset(pipe_config, 0, sizeof(*pipe_config));
12225         pipe_config->base.crtc = crtc;
12226         pipe_config->base.state = old_state;
12227
12228         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12229
12230         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12231
12232         /* hw state is inconsistent with the pipe quirk */
12233         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12234             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12235                 active = new_crtc_state->active;
12236
12237         I915_STATE_WARN(new_crtc_state->active != active,
12238              "crtc active state doesn't match with hw state "
12239              "(expected %i, found %i)\n", new_crtc_state->active, active);
12240
12241         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12242              "transitional active state does not match atomic hw state "
12243              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12244
12245         for_each_encoder_on_crtc(dev, crtc, encoder) {
12246                 enum pipe pipe;
12247
12248                 active = encoder->get_hw_state(encoder, &pipe);
12249                 I915_STATE_WARN(active != new_crtc_state->active,
12250                         "[ENCODER:%i] active %i with crtc active %i\n",
12251                         encoder->base.base.id, active, new_crtc_state->active);
12252
12253                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12254                                 "Encoder connected to wrong pipe %c\n",
12255                                 pipe_name(pipe));
12256
12257                 if (active) {
12258                         pipe_config->output_types |= 1 << encoder->type;
12259                         encoder->get_config(encoder, pipe_config);
12260                 }
12261         }
12262
12263         intel_crtc_compute_pixel_rate(pipe_config);
12264
12265         if (!new_crtc_state->active)
12266                 return;
12267
12268         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12269
12270         sw_config = to_intel_crtc_state(new_crtc_state);
12271         if (!intel_pipe_config_compare(dev_priv, sw_config,
12272                                        pipe_config, false)) {
12273                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12274                 intel_dump_pipe_config(intel_crtc, pipe_config,
12275                                        "[hw state]");
12276                 intel_dump_pipe_config(intel_crtc, sw_config,
12277                                        "[sw state]");
12278         }
12279 }
12280
12281 static void
12282 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12283                          struct intel_shared_dpll *pll,
12284                          struct drm_crtc *crtc,
12285                          struct drm_crtc_state *new_state)
12286 {
12287         struct intel_dpll_hw_state dpll_hw_state;
12288         unsigned crtc_mask;
12289         bool active;
12290
12291         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12292
12293         DRM_DEBUG_KMS("%s\n", pll->name);
12294
12295         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12296
12297         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12298                 I915_STATE_WARN(!pll->on && pll->active_mask,
12299                      "pll in active use but not on in sw tracking\n");
12300                 I915_STATE_WARN(pll->on && !pll->active_mask,
12301                      "pll is on but not used by any active crtc\n");
12302                 I915_STATE_WARN(pll->on != active,
12303                      "pll on state mismatch (expected %i, found %i)\n",
12304                      pll->on, active);
12305         }
12306
12307         if (!crtc) {
12308                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12309                                 "more active pll users than references: %x vs %x\n",
12310                                 pll->active_mask, pll->state.crtc_mask);
12311
12312                 return;
12313         }
12314
12315         crtc_mask = 1 << drm_crtc_index(crtc);
12316
12317         if (new_state->active)
12318                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12319                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12320                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12321         else
12322                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12323                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12324                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12325
12326         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12327                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12328                         crtc_mask, pll->state.crtc_mask);
12329
12330         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12331                                           &dpll_hw_state,
12332                                           sizeof(dpll_hw_state)),
12333                         "pll hw state mismatch\n");
12334 }
12335
12336 static void
12337 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12338                          struct drm_crtc_state *old_crtc_state,
12339                          struct drm_crtc_state *new_crtc_state)
12340 {
12341         struct drm_i915_private *dev_priv = to_i915(dev);
12342         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12343         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12344
12345         if (new_state->shared_dpll)
12346                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12347
12348         if (old_state->shared_dpll &&
12349             old_state->shared_dpll != new_state->shared_dpll) {
12350                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
12351                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12352
12353                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12354                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12355                                 pipe_name(drm_crtc_index(crtc)));
12356                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12357                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12358                                 pipe_name(drm_crtc_index(crtc)));
12359         }
12360 }
12361
12362 static void
12363 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12364                           struct drm_atomic_state *state,
12365                           struct drm_crtc_state *old_state,
12366                           struct drm_crtc_state *new_state)
12367 {
12368         if (!needs_modeset(new_state) &&
12369             !to_intel_crtc_state(new_state)->update_pipe)
12370                 return;
12371
12372         verify_wm_state(crtc, new_state);
12373         verify_connector_state(crtc->dev, state, crtc);
12374         verify_crtc_state(crtc, old_state, new_state);
12375         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12376 }
12377
12378 static void
12379 verify_disabled_dpll_state(struct drm_device *dev)
12380 {
12381         struct drm_i915_private *dev_priv = to_i915(dev);
12382         int i;
12383
12384         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12385                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12386 }
12387
12388 static void
12389 intel_modeset_verify_disabled(struct drm_device *dev,
12390                               struct drm_atomic_state *state)
12391 {
12392         verify_encoder_state(dev, state);
12393         verify_connector_state(dev, state, NULL);
12394         verify_disabled_dpll_state(dev);
12395 }
12396
12397 static void update_scanline_offset(struct intel_crtc *crtc)
12398 {
12399         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12400
12401         /*
12402          * The scanline counter increments at the leading edge of hsync.
12403          *
12404          * On most platforms it starts counting from vtotal-1 on the
12405          * first active line. That means the scanline counter value is
12406          * always one less than what we would expect. Ie. just after
12407          * start of vblank, which also occurs at start of hsync (on the
12408          * last active line), the scanline counter will read vblank_start-1.
12409          *
12410          * On gen2 the scanline counter starts counting from 1 instead
12411          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12412          * to keep the value positive), instead of adding one.
12413          *
12414          * On HSW+ the behaviour of the scanline counter depends on the output
12415          * type. For DP ports it behaves like most other platforms, but on HDMI
12416          * there's an extra 1 line difference. So we need to add two instead of
12417          * one to the value.
12418          *
12419          * On VLV/CHV DSI the scanline counter would appear to increment
12420          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12421          * that means we can't tell whether we're in vblank or not while
12422          * we're on that particular line. We must still set scanline_offset
12423          * to 1 so that the vblank timestamps come out correct when we query
12424          * the scanline counter from within the vblank interrupt handler.
12425          * However if queried just before the start of vblank we'll get an
12426          * answer that's slightly in the future.
12427          */
12428         if (IS_GEN2(dev_priv)) {
12429                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12430                 int vtotal;
12431
12432                 vtotal = adjusted_mode->crtc_vtotal;
12433                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12434                         vtotal /= 2;
12435
12436                 crtc->scanline_offset = vtotal - 1;
12437         } else if (HAS_DDI(dev_priv) &&
12438                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12439                 crtc->scanline_offset = 2;
12440         } else
12441                 crtc->scanline_offset = 1;
12442 }
12443
12444 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12445 {
12446         struct drm_device *dev = state->dev;
12447         struct drm_i915_private *dev_priv = to_i915(dev);
12448         struct drm_crtc *crtc;
12449         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12450         int i;
12451
12452         if (!dev_priv->display.crtc_compute_clock)
12453                 return;
12454
12455         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12456                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12457                 struct intel_shared_dpll *old_dpll =
12458                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12459
12460                 if (!needs_modeset(new_crtc_state))
12461                         continue;
12462
12463                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12464
12465                 if (!old_dpll)
12466                         continue;
12467
12468                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12469         }
12470 }
12471
12472 /*
12473  * This implements the workaround described in the "notes" section of the mode
12474  * set sequence documentation. When going from no pipes or single pipe to
12475  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12476  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12477  */
12478 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12479 {
12480         struct drm_crtc_state *crtc_state;
12481         struct intel_crtc *intel_crtc;
12482         struct drm_crtc *crtc;
12483         struct intel_crtc_state *first_crtc_state = NULL;
12484         struct intel_crtc_state *other_crtc_state = NULL;
12485         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12486         int i;
12487
12488         /* look at all crtc's that are going to be enabled in during modeset */
12489         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12490                 intel_crtc = to_intel_crtc(crtc);
12491
12492                 if (!crtc_state->active || !needs_modeset(crtc_state))
12493                         continue;
12494
12495                 if (first_crtc_state) {
12496                         other_crtc_state = to_intel_crtc_state(crtc_state);
12497                         break;
12498                 } else {
12499                         first_crtc_state = to_intel_crtc_state(crtc_state);
12500                         first_pipe = intel_crtc->pipe;
12501                 }
12502         }
12503
12504         /* No workaround needed? */
12505         if (!first_crtc_state)
12506                 return 0;
12507
12508         /* w/a possibly needed, check how many crtc's are already enabled. */
12509         for_each_intel_crtc(state->dev, intel_crtc) {
12510                 struct intel_crtc_state *pipe_config;
12511
12512                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12513                 if (IS_ERR(pipe_config))
12514                         return PTR_ERR(pipe_config);
12515
12516                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12517
12518                 if (!pipe_config->base.active ||
12519                     needs_modeset(&pipe_config->base))
12520                         continue;
12521
12522                 /* 2 or more enabled crtcs means no need for w/a */
12523                 if (enabled_pipe != INVALID_PIPE)
12524                         return 0;
12525
12526                 enabled_pipe = intel_crtc->pipe;
12527         }
12528
12529         if (enabled_pipe != INVALID_PIPE)
12530                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12531         else if (other_crtc_state)
12532                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12533
12534         return 0;
12535 }
12536
12537 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12538 {
12539         struct drm_crtc *crtc;
12540
12541         /* Add all pipes to the state */
12542         for_each_crtc(state->dev, crtc) {
12543                 struct drm_crtc_state *crtc_state;
12544
12545                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12546                 if (IS_ERR(crtc_state))
12547                         return PTR_ERR(crtc_state);
12548         }
12549
12550         return 0;
12551 }
12552
12553 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12554 {
12555         struct drm_crtc *crtc;
12556
12557         /*
12558          * Add all pipes to the state, and force
12559          * a modeset on all the active ones.
12560          */
12561         for_each_crtc(state->dev, crtc) {
12562                 struct drm_crtc_state *crtc_state;
12563                 int ret;
12564
12565                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12566                 if (IS_ERR(crtc_state))
12567                         return PTR_ERR(crtc_state);
12568
12569                 if (!crtc_state->active || needs_modeset(crtc_state))
12570                         continue;
12571
12572                 crtc_state->mode_changed = true;
12573
12574                 ret = drm_atomic_add_affected_connectors(state, crtc);
12575                 if (ret)
12576                         return ret;
12577
12578                 ret = drm_atomic_add_affected_planes(state, crtc);
12579                 if (ret)
12580                         return ret;
12581         }
12582
12583         return 0;
12584 }
12585
12586 static int intel_modeset_checks(struct drm_atomic_state *state)
12587 {
12588         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12589         struct drm_i915_private *dev_priv = to_i915(state->dev);
12590         struct drm_crtc *crtc;
12591         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12592         int ret = 0, i;
12593
12594         if (!check_digital_port_conflicts(state)) {
12595                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12596                 return -EINVAL;
12597         }
12598
12599         intel_state->modeset = true;
12600         intel_state->active_crtcs = dev_priv->active_crtcs;
12601         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12602         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12603
12604         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12605                 if (new_crtc_state->active)
12606                         intel_state->active_crtcs |= 1 << i;
12607                 else
12608                         intel_state->active_crtcs &= ~(1 << i);
12609
12610                 if (old_crtc_state->active != new_crtc_state->active)
12611                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12612         }
12613
12614         /*
12615          * See if the config requires any additional preparation, e.g.
12616          * to adjust global state with pipes off.  We need to do this
12617          * here so we can get the modeset_pipe updated config for the new
12618          * mode set on this crtc.  For other crtcs we need to use the
12619          * adjusted_mode bits in the crtc directly.
12620          */
12621         if (dev_priv->display.modeset_calc_cdclk) {
12622                 ret = dev_priv->display.modeset_calc_cdclk(state);
12623                 if (ret < 0)
12624                         return ret;
12625
12626                 /*
12627                  * Writes to dev_priv->cdclk.logical must protected by
12628                  * holding all the crtc locks, even if we don't end up
12629                  * touching the hardware
12630                  */
12631                 if (!intel_cdclk_state_compare(&dev_priv->cdclk.logical,
12632                                                &intel_state->cdclk.logical)) {
12633                         ret = intel_lock_all_pipes(state);
12634                         if (ret < 0)
12635                                 return ret;
12636                 }
12637
12638                 /* All pipes must be switched off while we change the cdclk. */
12639                 if (!intel_cdclk_state_compare(&dev_priv->cdclk.actual,
12640                                                &intel_state->cdclk.actual)) {
12641                         ret = intel_modeset_all_pipes(state);
12642                         if (ret < 0)
12643                                 return ret;
12644                 }
12645
12646                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12647                               intel_state->cdclk.logical.cdclk,
12648                               intel_state->cdclk.actual.cdclk);
12649         } else {
12650                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12651         }
12652
12653         intel_modeset_clear_plls(state);
12654
12655         if (IS_HASWELL(dev_priv))
12656                 return haswell_mode_set_planes_workaround(state);
12657
12658         return 0;
12659 }
12660
12661 /*
12662  * Handle calculation of various watermark data at the end of the atomic check
12663  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12664  * handlers to ensure that all derived state has been updated.
12665  */
12666 static int calc_watermark_data(struct drm_atomic_state *state)
12667 {
12668         struct drm_device *dev = state->dev;
12669         struct drm_i915_private *dev_priv = to_i915(dev);
12670
12671         /* Is there platform-specific watermark information to calculate? */
12672         if (dev_priv->display.compute_global_watermarks)
12673                 return dev_priv->display.compute_global_watermarks(state);
12674
12675         return 0;
12676 }
12677
12678 /**
12679  * intel_atomic_check - validate state object
12680  * @dev: drm device
12681  * @state: state to validate
12682  */
12683 static int intel_atomic_check(struct drm_device *dev,
12684                               struct drm_atomic_state *state)
12685 {
12686         struct drm_i915_private *dev_priv = to_i915(dev);
12687         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12688         struct drm_crtc *crtc;
12689         struct drm_crtc_state *old_crtc_state, *crtc_state;
12690         int ret, i;
12691         bool any_ms = false;
12692
12693         ret = drm_atomic_helper_check_modeset(dev, state);
12694         if (ret)
12695                 return ret;
12696
12697         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12698                 struct intel_crtc_state *pipe_config =
12699                         to_intel_crtc_state(crtc_state);
12700
12701                 /* Catch I915_MODE_FLAG_INHERITED */
12702                 if (crtc_state->mode.private_flags != old_crtc_state->mode.private_flags)
12703                         crtc_state->mode_changed = true;
12704
12705                 if (!needs_modeset(crtc_state))
12706                         continue;
12707
12708                 if (!crtc_state->enable) {
12709                         any_ms = true;
12710                         continue;
12711                 }
12712
12713                 /* FIXME: For only active_changed we shouldn't need to do any
12714                  * state recomputation at all. */
12715
12716                 ret = drm_atomic_add_affected_connectors(state, crtc);
12717                 if (ret)
12718                         return ret;
12719
12720                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12721                 if (ret) {
12722                         intel_dump_pipe_config(to_intel_crtc(crtc),
12723                                                pipe_config, "[failed]");
12724                         return ret;
12725                 }
12726
12727                 if (i915.fastboot &&
12728                     intel_pipe_config_compare(dev_priv,
12729                                         to_intel_crtc_state(old_crtc_state),
12730                                         pipe_config, true)) {
12731                         crtc_state->mode_changed = false;
12732                         pipe_config->update_pipe = true;
12733                 }
12734
12735                 if (needs_modeset(crtc_state))
12736                         any_ms = true;
12737
12738                 ret = drm_atomic_add_affected_planes(state, crtc);
12739                 if (ret)
12740                         return ret;
12741
12742                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12743                                        needs_modeset(crtc_state) ?
12744                                        "[modeset]" : "[fastset]");
12745         }
12746
12747         if (any_ms) {
12748                 ret = intel_modeset_checks(state);
12749
12750                 if (ret)
12751                         return ret;
12752         } else {
12753                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12754         }
12755
12756         ret = drm_atomic_helper_check_planes(dev, state);
12757         if (ret)
12758                 return ret;
12759
12760         intel_fbc_choose_crtc(dev_priv, state);
12761         return calc_watermark_data(state);
12762 }
12763
12764 static int intel_atomic_prepare_commit(struct drm_device *dev,
12765                                        struct drm_atomic_state *state)
12766 {
12767         struct drm_i915_private *dev_priv = to_i915(dev);
12768         struct drm_crtc_state *crtc_state;
12769         struct drm_crtc *crtc;
12770         int i, ret;
12771
12772         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12773                 if (state->legacy_cursor_update)
12774                         continue;
12775
12776                 ret = intel_crtc_wait_for_pending_flips(crtc);
12777                 if (ret)
12778                         return ret;
12779
12780                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
12781                         flush_workqueue(dev_priv->wq);
12782         }
12783
12784         ret = mutex_lock_interruptible(&dev->struct_mutex);
12785         if (ret)
12786                 return ret;
12787
12788         ret = drm_atomic_helper_prepare_planes(dev, state);
12789         mutex_unlock(&dev->struct_mutex);
12790
12791         return ret;
12792 }
12793
12794 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12795 {
12796         struct drm_device *dev = crtc->base.dev;
12797
12798         if (!dev->max_vblank_count)
12799                 return drm_accurate_vblank_count(&crtc->base);
12800
12801         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12802 }
12803
12804 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
12805                                           struct drm_i915_private *dev_priv,
12806                                           unsigned crtc_mask)
12807 {
12808         unsigned last_vblank_count[I915_MAX_PIPES];
12809         enum pipe pipe;
12810         int ret;
12811
12812         if (!crtc_mask)
12813                 return;
12814
12815         for_each_pipe(dev_priv, pipe) {
12816                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
12817                                                                   pipe);
12818
12819                 if (!((1 << pipe) & crtc_mask))
12820                         continue;
12821
12822                 ret = drm_crtc_vblank_get(&crtc->base);
12823                 if (WARN_ON(ret != 0)) {
12824                         crtc_mask &= ~(1 << pipe);
12825                         continue;
12826                 }
12827
12828                 last_vblank_count[pipe] = drm_crtc_vblank_count(&crtc->base);
12829         }
12830
12831         for_each_pipe(dev_priv, pipe) {
12832                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
12833                                                                   pipe);
12834                 long lret;
12835
12836                 if (!((1 << pipe) & crtc_mask))
12837                         continue;
12838
12839                 lret = wait_event_timeout(dev->vblank[pipe].queue,
12840                                 last_vblank_count[pipe] !=
12841                                         drm_crtc_vblank_count(&crtc->base),
12842                                 msecs_to_jiffies(50));
12843
12844                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
12845
12846                 drm_crtc_vblank_put(&crtc->base);
12847         }
12848 }
12849
12850 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
12851 {
12852         /* fb updated, need to unpin old fb */
12853         if (crtc_state->fb_changed)
12854                 return true;
12855
12856         /* wm changes, need vblank before final wm's */
12857         if (crtc_state->update_wm_post)
12858                 return true;
12859
12860         if (crtc_state->wm.need_postvbl_update)
12861                 return true;
12862
12863         return false;
12864 }
12865
12866 static void intel_update_crtc(struct drm_crtc *crtc,
12867                               struct drm_atomic_state *state,
12868                               struct drm_crtc_state *old_crtc_state,
12869                               struct drm_crtc_state *new_crtc_state,
12870                               unsigned int *crtc_vblank_mask)
12871 {
12872         struct drm_device *dev = crtc->dev;
12873         struct drm_i915_private *dev_priv = to_i915(dev);
12874         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12875         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12876         bool modeset = needs_modeset(new_crtc_state);
12877
12878         if (modeset) {
12879                 update_scanline_offset(intel_crtc);
12880                 dev_priv->display.crtc_enable(pipe_config, state);
12881         } else {
12882                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12883                                        pipe_config);
12884         }
12885
12886         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12887                 intel_fbc_enable(
12888                     intel_crtc, pipe_config,
12889                     to_intel_plane_state(crtc->primary->state));
12890         }
12891
12892         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12893
12894         if (needs_vblank_wait(pipe_config))
12895                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
12896 }
12897
12898 static void intel_update_crtcs(struct drm_atomic_state *state,
12899                                unsigned int *crtc_vblank_mask)
12900 {
12901         struct drm_crtc *crtc;
12902         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12903         int i;
12904
12905         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12906                 if (!new_crtc_state->active)
12907                         continue;
12908
12909                 intel_update_crtc(crtc, state, old_crtc_state,
12910                                   new_crtc_state, crtc_vblank_mask);
12911         }
12912 }
12913
12914 static void skl_update_crtcs(struct drm_atomic_state *state,
12915                              unsigned int *crtc_vblank_mask)
12916 {
12917         struct drm_i915_private *dev_priv = to_i915(state->dev);
12918         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12919         struct drm_crtc *crtc;
12920         struct intel_crtc *intel_crtc;
12921         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12922         struct intel_crtc_state *cstate;
12923         unsigned int updated = 0;
12924         bool progress;
12925         enum pipe pipe;
12926         int i;
12927
12928         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12929
12930         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12931                 /* ignore allocations for crtc's that have been turned off. */
12932                 if (new_crtc_state->active)
12933                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12934
12935         /*
12936          * Whenever the number of active pipes changes, we need to make sure we
12937          * update the pipes in the right order so that their ddb allocations
12938          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12939          * cause pipe underruns and other bad stuff.
12940          */
12941         do {
12942                 progress = false;
12943
12944                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12945                         bool vbl_wait = false;
12946                         unsigned int cmask = drm_crtc_mask(crtc);
12947
12948                         intel_crtc = to_intel_crtc(crtc);
12949                         cstate = to_intel_crtc_state(crtc->state);
12950                         pipe = intel_crtc->pipe;
12951
12952                         if (updated & cmask || !cstate->base.active)
12953                                 continue;
12954
12955                         if (skl_ddb_allocation_overlaps(entries, &cstate->wm.skl.ddb, i))
12956                                 continue;
12957
12958                         updated |= cmask;
12959                         entries[i] = &cstate->wm.skl.ddb;
12960
12961                         /*
12962                          * If this is an already active pipe, it's DDB changed,
12963                          * and this isn't the last pipe that needs updating
12964                          * then we need to wait for a vblank to pass for the
12965                          * new ddb allocation to take effect.
12966                          */
12967                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12968                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12969                             !new_crtc_state->active_changed &&
12970                             intel_state->wm_results.dirty_pipes != updated)
12971                                 vbl_wait = true;
12972
12973                         intel_update_crtc(crtc, state, old_crtc_state,
12974                                           new_crtc_state, crtc_vblank_mask);
12975
12976                         if (vbl_wait)
12977                                 intel_wait_for_vblank(dev_priv, pipe);
12978
12979                         progress = true;
12980                 }
12981         } while (progress);
12982 }
12983
12984 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12985 {
12986         struct intel_atomic_state *state, *next;
12987         struct llist_node *freed;
12988
12989         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12990         llist_for_each_entry_safe(state, next, freed, freed)
12991                 drm_atomic_state_put(&state->base);
12992 }
12993
12994 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12995 {
12996         struct drm_i915_private *dev_priv =
12997                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12998
12999         intel_atomic_helper_free_state(dev_priv);
13000 }
13001
13002 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13003 {
13004         struct drm_device *dev = state->dev;
13005         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13006         struct drm_i915_private *dev_priv = to_i915(dev);
13007         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13008         struct drm_crtc *crtc;
13009         struct intel_crtc_state *intel_cstate;
13010         bool hw_check = intel_state->modeset;
13011         u64 put_domains[I915_MAX_PIPES] = {};
13012         unsigned crtc_vblank_mask = 0;
13013         int i;
13014
13015         drm_atomic_helper_wait_for_dependencies(state);
13016
13017         if (intel_state->modeset)
13018                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13019
13020         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13021                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13022
13023                 if (needs_modeset(new_crtc_state) ||
13024                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13025                         hw_check = true;
13026
13027                         put_domains[to_intel_crtc(crtc)->pipe] =
13028                                 modeset_get_crtc_power_domains(crtc,
13029                                         to_intel_crtc_state(new_crtc_state));
13030                 }
13031
13032                 if (!needs_modeset(new_crtc_state))
13033                         continue;
13034
13035                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
13036                                        to_intel_crtc_state(new_crtc_state));
13037
13038                 if (old_crtc_state->active) {
13039                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13040                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
13041                         intel_crtc->active = false;
13042                         intel_fbc_disable(intel_crtc);
13043                         intel_disable_shared_dpll(intel_crtc);
13044
13045                         /*
13046                          * Underruns don't always raise
13047                          * interrupts, so check manually.
13048                          */
13049                         intel_check_cpu_fifo_underruns(dev_priv);
13050                         intel_check_pch_fifo_underruns(dev_priv);
13051
13052                         if (!crtc->state->active) {
13053                                 /*
13054                                  * Make sure we don't call initial_watermarks
13055                                  * for ILK-style watermark updates.
13056                                  *
13057                                  * No clue what this is supposed to achieve.
13058                                  */
13059                                 if (INTEL_GEN(dev_priv) >= 9)
13060                                         dev_priv->display.initial_watermarks(intel_state,
13061                                                                              to_intel_crtc_state(crtc->state));
13062                         }
13063                 }
13064         }
13065
13066         /* Only after disabling all output pipelines that will be changed can we
13067          * update the the output configuration. */
13068         intel_modeset_update_crtc_state(state);
13069
13070         if (intel_state->modeset) {
13071                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13072
13073                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
13074
13075                 /*
13076                  * SKL workaround: bspec recommends we disable the SAGV when we
13077                  * have more then one pipe enabled
13078                  */
13079                 if (!intel_can_enable_sagv(state))
13080                         intel_disable_sagv(dev_priv);
13081
13082                 intel_modeset_verify_disabled(dev, state);
13083         }
13084
13085         /* Complete the events for pipes that have now been disabled */
13086         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13087                 bool modeset = needs_modeset(new_crtc_state);
13088
13089                 /* Complete events for now disable pipes here. */
13090                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13091                         spin_lock_irq(&dev->event_lock);
13092                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13093                         spin_unlock_irq(&dev->event_lock);
13094
13095                         new_crtc_state->event = NULL;
13096                 }
13097         }
13098
13099         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13100         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
13101
13102         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13103          * already, but still need the state for the delayed optimization. To
13104          * fix this:
13105          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13106          * - schedule that vblank worker _before_ calling hw_done
13107          * - at the start of commit_tail, cancel it _synchrously
13108          * - switch over to the vblank wait helper in the core after that since
13109          *   we don't need out special handling any more.
13110          */
13111         if (!state->legacy_cursor_update)
13112                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13113
13114         /*
13115          * Now that the vblank has passed, we can go ahead and program the
13116          * optimal watermarks on platforms that need two-step watermark
13117          * programming.
13118          *
13119          * TODO: Move this (and other cleanup) to an async worker eventually.
13120          */
13121         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13122                 intel_cstate = to_intel_crtc_state(new_crtc_state);
13123
13124                 if (dev_priv->display.optimize_watermarks)
13125                         dev_priv->display.optimize_watermarks(intel_state,
13126                                                               intel_cstate);
13127         }
13128
13129         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13130                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13131
13132                 if (put_domains[i])
13133                         modeset_put_power_domains(dev_priv, put_domains[i]);
13134
13135                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13136         }
13137
13138         if (intel_state->modeset && intel_can_enable_sagv(state))
13139                 intel_enable_sagv(dev_priv);
13140
13141         drm_atomic_helper_commit_hw_done(state);
13142
13143         if (intel_state->modeset) {
13144                 /* As one of the primary mmio accessors, KMS has a high
13145                  * likelihood of triggering bugs in unclaimed access. After we
13146                  * finish modesetting, see if an error has been flagged, and if
13147                  * so enable debugging for the next modeset - and hope we catch
13148                  * the culprit.
13149                  */
13150                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13151                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13152         }
13153
13154         mutex_lock(&dev->struct_mutex);
13155         drm_atomic_helper_cleanup_planes(dev, state);
13156         mutex_unlock(&dev->struct_mutex);
13157
13158         drm_atomic_helper_commit_cleanup_done(state);
13159
13160         drm_atomic_state_put(state);
13161
13162         intel_atomic_helper_free_state(dev_priv);
13163 }
13164
13165 static void intel_atomic_commit_work(struct work_struct *work)
13166 {
13167         struct drm_atomic_state *state =
13168                 container_of(work, struct drm_atomic_state, commit_work);
13169
13170         intel_atomic_commit_tail(state);
13171 }
13172
13173 static int __i915_sw_fence_call
13174 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13175                           enum i915_sw_fence_notify notify)
13176 {
13177         struct intel_atomic_state *state =
13178                 container_of(fence, struct intel_atomic_state, commit_ready);
13179
13180         switch (notify) {
13181         case FENCE_COMPLETE:
13182                 if (state->base.commit_work.func)
13183                         queue_work(system_unbound_wq, &state->base.commit_work);
13184                 break;
13185
13186         case FENCE_FREE:
13187                 {
13188                         struct intel_atomic_helper *helper =
13189                                 &to_i915(state->base.dev)->atomic_helper;
13190
13191                         if (llist_add(&state->freed, &helper->free_list))
13192                                 schedule_work(&helper->free_work);
13193                         break;
13194                 }
13195         }
13196
13197         return NOTIFY_DONE;
13198 }
13199
13200 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13201 {
13202         struct drm_plane_state *old_plane_state, *new_plane_state;
13203         struct drm_plane *plane;
13204         int i;
13205
13206         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13207                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13208                                   intel_fb_obj(new_plane_state->fb),
13209                                   to_intel_plane(plane)->frontbuffer_bit);
13210 }
13211
13212 /**
13213  * intel_atomic_commit - commit validated state object
13214  * @dev: DRM device
13215  * @state: the top-level driver state object
13216  * @nonblock: nonblocking commit
13217  *
13218  * This function commits a top-level state object that has been validated
13219  * with drm_atomic_helper_check().
13220  *
13221  * RETURNS
13222  * Zero for success or -errno.
13223  */
13224 static int intel_atomic_commit(struct drm_device *dev,
13225                                struct drm_atomic_state *state,
13226                                bool nonblock)
13227 {
13228         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13229         struct drm_i915_private *dev_priv = to_i915(dev);
13230         int ret = 0;
13231
13232         ret = drm_atomic_helper_setup_commit(state, nonblock);
13233         if (ret)
13234                 return ret;
13235
13236         drm_atomic_state_get(state);
13237         i915_sw_fence_init(&intel_state->commit_ready,
13238                            intel_atomic_commit_ready);
13239
13240         ret = intel_atomic_prepare_commit(dev, state);
13241         if (ret) {
13242                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13243                 i915_sw_fence_commit(&intel_state->commit_ready);
13244                 return ret;
13245         }
13246
13247         /*
13248          * The intel_legacy_cursor_update() fast path takes care
13249          * of avoiding the vblank waits for simple cursor
13250          * movement and flips. For cursor on/off and size changes,
13251          * we want to perform the vblank waits so that watermark
13252          * updates happen during the correct frames. Gen9+ have
13253          * double buffered watermarks and so shouldn't need this.
13254          *
13255          * Do this after drm_atomic_helper_setup_commit() and
13256          * intel_atomic_prepare_commit() because we still want
13257          * to skip the flip and fb cleanup waits. Although that
13258          * does risk yanking the mapping from under the display
13259          * engine.
13260          *
13261          * FIXME doing watermarks and fb cleanup from a vblank worker
13262          * (assuming we had any) would solve these problems.
13263          */
13264         if (INTEL_GEN(dev_priv) < 9)
13265                 state->legacy_cursor_update = false;
13266
13267         drm_atomic_helper_swap_state(state, true);
13268         dev_priv->wm.distrust_bios_wm = false;
13269         intel_shared_dpll_swap_state(state);
13270         intel_atomic_track_fbs(state);
13271
13272         if (intel_state->modeset) {
13273                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13274                        sizeof(intel_state->min_pixclk));
13275                 dev_priv->active_crtcs = intel_state->active_crtcs;
13276                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
13277                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
13278         }
13279
13280         drm_atomic_state_get(state);
13281         INIT_WORK(&state->commit_work,
13282                   nonblock ? intel_atomic_commit_work : NULL);
13283
13284         i915_sw_fence_commit(&intel_state->commit_ready);
13285         if (!nonblock) {
13286                 i915_sw_fence_wait(&intel_state->commit_ready);
13287                 intel_atomic_commit_tail(state);
13288         }
13289
13290         return 0;
13291 }
13292
13293 static const struct drm_crtc_funcs intel_crtc_funcs = {
13294         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13295         .set_config = drm_atomic_helper_set_config,
13296         .set_property = drm_atomic_helper_crtc_set_property,
13297         .destroy = intel_crtc_destroy,
13298         .page_flip = drm_atomic_helper_page_flip,
13299         .atomic_duplicate_state = intel_crtc_duplicate_state,
13300         .atomic_destroy_state = intel_crtc_destroy_state,
13301         .set_crc_source = intel_crtc_set_crc_source,
13302 };
13303
13304 /**
13305  * intel_prepare_plane_fb - Prepare fb for usage on plane
13306  * @plane: drm plane to prepare for
13307  * @fb: framebuffer to prepare for presentation
13308  *
13309  * Prepares a framebuffer for usage on a display plane.  Generally this
13310  * involves pinning the underlying object and updating the frontbuffer tracking
13311  * bits.  Some older platforms need special physical address handling for
13312  * cursor planes.
13313  *
13314  * Must be called with struct_mutex held.
13315  *
13316  * Returns 0 on success, negative error code on failure.
13317  */
13318 int
13319 intel_prepare_plane_fb(struct drm_plane *plane,
13320                        struct drm_plane_state *new_state)
13321 {
13322         struct intel_atomic_state *intel_state =
13323                 to_intel_atomic_state(new_state->state);
13324         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13325         struct drm_framebuffer *fb = new_state->fb;
13326         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13327         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13328         int ret;
13329
13330         if (obj) {
13331                 if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13332                     INTEL_INFO(dev_priv)->cursor_needs_physical) {
13333                         const int align = intel_cursor_alignment(dev_priv);
13334
13335                         ret = i915_gem_object_attach_phys(obj, align);
13336                         if (ret) {
13337                                 DRM_DEBUG_KMS("failed to attach phys object\n");
13338                                 return ret;
13339                         }
13340                 } else {
13341                         struct i915_vma *vma;
13342
13343                         vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13344                         if (IS_ERR(vma)) {
13345                                 DRM_DEBUG_KMS("failed to pin object\n");
13346                                 return PTR_ERR(vma);
13347                         }
13348
13349                         to_intel_plane_state(new_state)->vma = vma;
13350                 }
13351         }
13352
13353         if (!obj && !old_obj)
13354                 return 0;
13355
13356         if (old_obj) {
13357                 struct drm_crtc_state *crtc_state =
13358                         drm_atomic_get_existing_crtc_state(new_state->state,
13359                                                            plane->state->crtc);
13360
13361                 /* Big Hammer, we also need to ensure that any pending
13362                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13363                  * current scanout is retired before unpinning the old
13364                  * framebuffer. Note that we rely on userspace rendering
13365                  * into the buffer attached to the pipe they are waiting
13366                  * on. If not, userspace generates a GPU hang with IPEHR
13367                  * point to the MI_WAIT_FOR_EVENT.
13368                  *
13369                  * This should only fail upon a hung GPU, in which case we
13370                  * can safely continue.
13371                  */
13372                 if (needs_modeset(crtc_state)) {
13373                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13374                                                               old_obj->resv, NULL,
13375                                                               false, 0,
13376                                                               GFP_KERNEL);
13377                         if (ret < 0)
13378                                 return ret;
13379                 }
13380         }
13381
13382         if (new_state->fence) { /* explicit fencing */
13383                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13384                                                     new_state->fence,
13385                                                     I915_FENCE_TIMEOUT,
13386                                                     GFP_KERNEL);
13387                 if (ret < 0)
13388                         return ret;
13389         }
13390
13391         if (!obj)
13392                 return 0;
13393
13394         if (!new_state->fence) { /* implicit fencing */
13395                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13396                                                       obj->resv, NULL,
13397                                                       false, I915_FENCE_TIMEOUT,
13398                                                       GFP_KERNEL);
13399                 if (ret < 0)
13400                         return ret;
13401
13402                 i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
13403         }
13404
13405         return 0;
13406 }
13407
13408 /**
13409  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13410  * @plane: drm plane to clean up for
13411  * @fb: old framebuffer that was on plane
13412  *
13413  * Cleans up a framebuffer that has just been removed from a plane.
13414  *
13415  * Must be called with struct_mutex held.
13416  */
13417 void
13418 intel_cleanup_plane_fb(struct drm_plane *plane,
13419                        struct drm_plane_state *old_state)
13420 {
13421         struct i915_vma *vma;
13422
13423         /* Should only be called after a successful intel_prepare_plane_fb()! */
13424         vma = fetch_and_zero(&to_intel_plane_state(old_state)->vma);
13425         if (vma)
13426                 intel_unpin_fb_vma(vma);
13427 }
13428
13429 int
13430 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13431 {
13432         struct drm_i915_private *dev_priv;
13433         int max_scale;
13434         int crtc_clock, max_dotclk;
13435
13436         if (!intel_crtc || !crtc_state->base.enable)
13437                 return DRM_PLANE_HELPER_NO_SCALING;
13438
13439         dev_priv = to_i915(intel_crtc->base.dev);
13440
13441         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13442         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13443
13444         if (IS_GEMINILAKE(dev_priv))
13445                 max_dotclk *= 2;
13446
13447         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13448                 return DRM_PLANE_HELPER_NO_SCALING;
13449
13450         /*
13451          * skl max scale is lower of:
13452          *    close to 3 but not 3, -1 is for that purpose
13453          *            or
13454          *    cdclk/crtc_clock
13455          */
13456         max_scale = min((1 << 16) * 3 - 1,
13457                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
13458
13459         return max_scale;
13460 }
13461
13462 static int
13463 intel_check_primary_plane(struct intel_plane *plane,
13464                           struct intel_crtc_state *crtc_state,
13465                           struct intel_plane_state *state)
13466 {
13467         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13468         struct drm_crtc *crtc = state->base.crtc;
13469         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13470         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13471         bool can_position = false;
13472         int ret;
13473
13474         if (INTEL_GEN(dev_priv) >= 9) {
13475                 /* use scaler when colorkey is not required */
13476                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13477                         min_scale = 1;
13478                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13479                 }
13480                 can_position = true;
13481         }
13482
13483         ret = drm_plane_helper_check_state(&state->base,
13484                                            &state->clip,
13485                                            min_scale, max_scale,
13486                                            can_position, true);
13487         if (ret)
13488                 return ret;
13489
13490         if (!state->base.fb)
13491                 return 0;
13492
13493         if (INTEL_GEN(dev_priv) >= 9) {
13494                 ret = skl_check_plane_surface(state);
13495                 if (ret)
13496                         return ret;
13497
13498                 state->ctl = skl_plane_ctl(crtc_state, state);
13499         } else {
13500                 ret = i9xx_check_plane_surface(state);
13501                 if (ret)
13502                         return ret;
13503
13504                 state->ctl = i9xx_plane_ctl(crtc_state, state);
13505         }
13506
13507         return 0;
13508 }
13509
13510 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13511                                     struct drm_crtc_state *old_crtc_state)
13512 {
13513         struct drm_device *dev = crtc->dev;
13514         struct drm_i915_private *dev_priv = to_i915(dev);
13515         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13516         struct intel_crtc_state *intel_cstate =
13517                 to_intel_crtc_state(crtc->state);
13518         struct intel_crtc_state *old_intel_cstate =
13519                 to_intel_crtc_state(old_crtc_state);
13520         struct intel_atomic_state *old_intel_state =
13521                 to_intel_atomic_state(old_crtc_state->state);
13522         bool modeset = needs_modeset(crtc->state);
13523
13524         if (!modeset &&
13525             (intel_cstate->base.color_mgmt_changed ||
13526              intel_cstate->update_pipe)) {
13527                 intel_color_set_csc(crtc->state);
13528                 intel_color_load_luts(crtc->state);
13529         }
13530
13531         /* Perform vblank evasion around commit operation */
13532         intel_pipe_update_start(intel_crtc);
13533
13534         if (modeset)
13535                 goto out;
13536
13537         if (intel_cstate->update_pipe)
13538                 intel_update_pipe_config(intel_crtc, old_intel_cstate);
13539         else if (INTEL_GEN(dev_priv) >= 9)
13540                 skl_detach_scalers(intel_crtc);
13541
13542 out:
13543         if (dev_priv->display.atomic_update_watermarks)
13544                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13545                                                            intel_cstate);
13546 }
13547
13548 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13549                                      struct drm_crtc_state *old_crtc_state)
13550 {
13551         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13552
13553         intel_pipe_update_end(intel_crtc, NULL);
13554 }
13555
13556 /**
13557  * intel_plane_destroy - destroy a plane
13558  * @plane: plane to destroy
13559  *
13560  * Common destruction function for all types of planes (primary, cursor,
13561  * sprite).
13562  */
13563 void intel_plane_destroy(struct drm_plane *plane)
13564 {
13565         drm_plane_cleanup(plane);
13566         kfree(to_intel_plane(plane));
13567 }
13568
13569 const struct drm_plane_funcs intel_plane_funcs = {
13570         .update_plane = drm_atomic_helper_update_plane,
13571         .disable_plane = drm_atomic_helper_disable_plane,
13572         .destroy = intel_plane_destroy,
13573         .set_property = drm_atomic_helper_plane_set_property,
13574         .atomic_get_property = intel_plane_atomic_get_property,
13575         .atomic_set_property = intel_plane_atomic_set_property,
13576         .atomic_duplicate_state = intel_plane_duplicate_state,
13577         .atomic_destroy_state = intel_plane_destroy_state,
13578 };
13579
13580 static int
13581 intel_legacy_cursor_update(struct drm_plane *plane,
13582                            struct drm_crtc *crtc,
13583                            struct drm_framebuffer *fb,
13584                            int crtc_x, int crtc_y,
13585                            unsigned int crtc_w, unsigned int crtc_h,
13586                            uint32_t src_x, uint32_t src_y,
13587                            uint32_t src_w, uint32_t src_h,
13588                            struct drm_modeset_acquire_ctx *ctx)
13589 {
13590         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13591         int ret;
13592         struct drm_plane_state *old_plane_state, *new_plane_state;
13593         struct intel_plane *intel_plane = to_intel_plane(plane);
13594         struct drm_framebuffer *old_fb;
13595         struct drm_crtc_state *crtc_state = crtc->state;
13596         struct i915_vma *old_vma;
13597
13598         /*
13599          * When crtc is inactive or there is a modeset pending,
13600          * wait for it to complete in the slowpath
13601          */
13602         if (!crtc_state->active || needs_modeset(crtc_state) ||
13603             to_intel_crtc_state(crtc_state)->update_pipe)
13604                 goto slow;
13605
13606         old_plane_state = plane->state;
13607
13608         /*
13609          * If any parameters change that may affect watermarks,
13610          * take the slowpath. Only changing fb or position should be
13611          * in the fastpath.
13612          */
13613         if (old_plane_state->crtc != crtc ||
13614             old_plane_state->src_w != src_w ||
13615             old_plane_state->src_h != src_h ||
13616             old_plane_state->crtc_w != crtc_w ||
13617             old_plane_state->crtc_h != crtc_h ||
13618             !old_plane_state->fb != !fb)
13619                 goto slow;
13620
13621         new_plane_state = intel_plane_duplicate_state(plane);
13622         if (!new_plane_state)
13623                 return -ENOMEM;
13624
13625         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13626
13627         new_plane_state->src_x = src_x;
13628         new_plane_state->src_y = src_y;
13629         new_plane_state->src_w = src_w;
13630         new_plane_state->src_h = src_h;
13631         new_plane_state->crtc_x = crtc_x;
13632         new_plane_state->crtc_y = crtc_y;
13633         new_plane_state->crtc_w = crtc_w;
13634         new_plane_state->crtc_h = crtc_h;
13635
13636         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13637                                                   to_intel_plane_state(new_plane_state));
13638         if (ret)
13639                 goto out_free;
13640
13641         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13642         if (ret)
13643                 goto out_free;
13644
13645         if (INTEL_INFO(dev_priv)->cursor_needs_physical) {
13646                 int align = intel_cursor_alignment(dev_priv);
13647
13648                 ret = i915_gem_object_attach_phys(intel_fb_obj(fb), align);
13649                 if (ret) {
13650                         DRM_DEBUG_KMS("failed to attach phys object\n");
13651                         goto out_unlock;
13652                 }
13653         } else {
13654                 struct i915_vma *vma;
13655
13656                 vma = intel_pin_and_fence_fb_obj(fb, new_plane_state->rotation);
13657                 if (IS_ERR(vma)) {
13658                         DRM_DEBUG_KMS("failed to pin object\n");
13659
13660                         ret = PTR_ERR(vma);
13661                         goto out_unlock;
13662                 }
13663
13664                 to_intel_plane_state(new_plane_state)->vma = vma;
13665         }
13666
13667         old_fb = old_plane_state->fb;
13668         old_vma = to_intel_plane_state(old_plane_state)->vma;
13669
13670         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13671                           intel_plane->frontbuffer_bit);
13672
13673         /* Swap plane state */
13674         new_plane_state->fence = old_plane_state->fence;
13675         *to_intel_plane_state(old_plane_state) = *to_intel_plane_state(new_plane_state);
13676         new_plane_state->fence = NULL;
13677         new_plane_state->fb = old_fb;
13678         to_intel_plane_state(new_plane_state)->vma = old_vma;
13679
13680         if (plane->state->visible) {
13681                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13682                 intel_plane->update_plane(intel_plane,
13683                                           to_intel_crtc_state(crtc->state),
13684                                           to_intel_plane_state(plane->state));
13685         } else {
13686                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13687                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13688         }
13689
13690         intel_cleanup_plane_fb(plane, new_plane_state);
13691
13692 out_unlock:
13693         mutex_unlock(&dev_priv->drm.struct_mutex);
13694 out_free:
13695         intel_plane_destroy_state(plane, new_plane_state);
13696         return ret;
13697
13698 slow:
13699         return drm_atomic_helper_update_plane(plane, crtc, fb,
13700                                               crtc_x, crtc_y, crtc_w, crtc_h,
13701                                               src_x, src_y, src_w, src_h, ctx);
13702 }
13703
13704 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13705         .update_plane = intel_legacy_cursor_update,
13706         .disable_plane = drm_atomic_helper_disable_plane,
13707         .destroy = intel_plane_destroy,
13708         .set_property = drm_atomic_helper_plane_set_property,
13709         .atomic_get_property = intel_plane_atomic_get_property,
13710         .atomic_set_property = intel_plane_atomic_set_property,
13711         .atomic_duplicate_state = intel_plane_duplicate_state,
13712         .atomic_destroy_state = intel_plane_destroy_state,
13713 };
13714
13715 static struct intel_plane *
13716 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13717 {
13718         struct intel_plane *primary = NULL;
13719         struct intel_plane_state *state = NULL;
13720         const uint32_t *intel_primary_formats;
13721         unsigned int supported_rotations;
13722         unsigned int num_formats;
13723         int ret;
13724
13725         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13726         if (!primary) {
13727                 ret = -ENOMEM;
13728                 goto fail;
13729         }
13730
13731         state = intel_create_plane_state(&primary->base);
13732         if (!state) {
13733                 ret = -ENOMEM;
13734                 goto fail;
13735         }
13736
13737         primary->base.state = &state->base;
13738
13739         primary->can_scale = false;
13740         primary->max_downscale = 1;
13741         if (INTEL_GEN(dev_priv) >= 9) {
13742                 primary->can_scale = true;
13743                 state->scaler_id = -1;
13744         }
13745         primary->pipe = pipe;
13746         /*
13747          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13748          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13749          */
13750         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13751                 primary->plane = (enum plane) !pipe;
13752         else
13753                 primary->plane = (enum plane) pipe;
13754         primary->id = PLANE_PRIMARY;
13755         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13756         primary->check_plane = intel_check_primary_plane;
13757
13758         if (INTEL_GEN(dev_priv) >= 9) {
13759                 intel_primary_formats = skl_primary_formats;
13760                 num_formats = ARRAY_SIZE(skl_primary_formats);
13761
13762                 primary->update_plane = skylake_update_primary_plane;
13763                 primary->disable_plane = skylake_disable_primary_plane;
13764         } else if (INTEL_GEN(dev_priv) >= 4) {
13765                 intel_primary_formats = i965_primary_formats;
13766                 num_formats = ARRAY_SIZE(i965_primary_formats);
13767
13768                 primary->update_plane = i9xx_update_primary_plane;
13769                 primary->disable_plane = i9xx_disable_primary_plane;
13770         } else {
13771                 intel_primary_formats = i8xx_primary_formats;
13772                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13773
13774                 primary->update_plane = i9xx_update_primary_plane;
13775                 primary->disable_plane = i9xx_disable_primary_plane;
13776         }
13777
13778         if (INTEL_GEN(dev_priv) >= 9)
13779                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13780                                                0, &intel_plane_funcs,
13781                                                intel_primary_formats, num_formats,
13782                                                DRM_PLANE_TYPE_PRIMARY,
13783                                                "plane 1%c", pipe_name(pipe));
13784         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13785                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13786                                                0, &intel_plane_funcs,
13787                                                intel_primary_formats, num_formats,
13788                                                DRM_PLANE_TYPE_PRIMARY,
13789                                                "primary %c", pipe_name(pipe));
13790         else
13791                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13792                                                0, &intel_plane_funcs,
13793                                                intel_primary_formats, num_formats,
13794                                                DRM_PLANE_TYPE_PRIMARY,
13795                                                "plane %c", plane_name(primary->plane));
13796         if (ret)
13797                 goto fail;
13798
13799         if (INTEL_GEN(dev_priv) >= 9) {
13800                 supported_rotations =
13801                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13802                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13803         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13804                 supported_rotations =
13805                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13806                         DRM_MODE_REFLECT_X;
13807         } else if (INTEL_GEN(dev_priv) >= 4) {
13808                 supported_rotations =
13809                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13810         } else {
13811                 supported_rotations = DRM_MODE_ROTATE_0;
13812         }
13813
13814         if (INTEL_GEN(dev_priv) >= 4)
13815                 drm_plane_create_rotation_property(&primary->base,
13816                                                    DRM_MODE_ROTATE_0,
13817                                                    supported_rotations);
13818
13819         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13820
13821         return primary;
13822
13823 fail:
13824         kfree(state);
13825         kfree(primary);
13826
13827         return ERR_PTR(ret);
13828 }
13829
13830 static struct intel_plane *
13831 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13832                           enum pipe pipe)
13833 {
13834         struct intel_plane *cursor = NULL;
13835         struct intel_plane_state *state = NULL;
13836         int ret;
13837
13838         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13839         if (!cursor) {
13840                 ret = -ENOMEM;
13841                 goto fail;
13842         }
13843
13844         state = intel_create_plane_state(&cursor->base);
13845         if (!state) {
13846                 ret = -ENOMEM;
13847                 goto fail;
13848         }
13849
13850         cursor->base.state = &state->base;
13851
13852         cursor->can_scale = false;
13853         cursor->max_downscale = 1;
13854         cursor->pipe = pipe;
13855         cursor->plane = pipe;
13856         cursor->id = PLANE_CURSOR;
13857         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13858
13859         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13860                 cursor->update_plane = i845_update_cursor;
13861                 cursor->disable_plane = i845_disable_cursor;
13862                 cursor->check_plane = i845_check_cursor;
13863         } else {
13864                 cursor->update_plane = i9xx_update_cursor;
13865                 cursor->disable_plane = i9xx_disable_cursor;
13866                 cursor->check_plane = i9xx_check_cursor;
13867         }
13868
13869         cursor->cursor.base = ~0;
13870         cursor->cursor.cntl = ~0;
13871
13872         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13873                 cursor->cursor.size = ~0;
13874
13875         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13876                                        0, &intel_cursor_plane_funcs,
13877                                        intel_cursor_formats,
13878                                        ARRAY_SIZE(intel_cursor_formats),
13879                                        DRM_PLANE_TYPE_CURSOR,
13880                                        "cursor %c", pipe_name(pipe));
13881         if (ret)
13882                 goto fail;
13883
13884         if (INTEL_GEN(dev_priv) >= 4)
13885                 drm_plane_create_rotation_property(&cursor->base,
13886                                                    DRM_MODE_ROTATE_0,
13887                                                    DRM_MODE_ROTATE_0 |
13888                                                    DRM_MODE_ROTATE_180);
13889
13890         if (INTEL_GEN(dev_priv) >= 9)
13891                 state->scaler_id = -1;
13892
13893         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13894
13895         return cursor;
13896
13897 fail:
13898         kfree(state);
13899         kfree(cursor);
13900
13901         return ERR_PTR(ret);
13902 }
13903
13904 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13905                                     struct intel_crtc_state *crtc_state)
13906 {
13907         struct intel_crtc_scaler_state *scaler_state =
13908                 &crtc_state->scaler_state;
13909         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13910         int i;
13911
13912         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13913         if (!crtc->num_scalers)
13914                 return;
13915
13916         for (i = 0; i < crtc->num_scalers; i++) {
13917                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13918
13919                 scaler->in_use = 0;
13920                 scaler->mode = PS_SCALER_MODE_DYN;
13921         }
13922
13923         scaler_state->scaler_id = -1;
13924 }
13925
13926 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13927 {
13928         struct intel_crtc *intel_crtc;
13929         struct intel_crtc_state *crtc_state = NULL;
13930         struct intel_plane *primary = NULL;
13931         struct intel_plane *cursor = NULL;
13932         int sprite, ret;
13933
13934         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13935         if (!intel_crtc)
13936                 return -ENOMEM;
13937
13938         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13939         if (!crtc_state) {
13940                 ret = -ENOMEM;
13941                 goto fail;
13942         }
13943         intel_crtc->config = crtc_state;
13944         intel_crtc->base.state = &crtc_state->base;
13945         crtc_state->base.crtc = &intel_crtc->base;
13946
13947         primary = intel_primary_plane_create(dev_priv, pipe);
13948         if (IS_ERR(primary)) {
13949                 ret = PTR_ERR(primary);
13950                 goto fail;
13951         }
13952         intel_crtc->plane_ids_mask |= BIT(primary->id);
13953
13954         for_each_sprite(dev_priv, pipe, sprite) {
13955                 struct intel_plane *plane;
13956
13957                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13958                 if (IS_ERR(plane)) {
13959                         ret = PTR_ERR(plane);
13960                         goto fail;
13961                 }
13962                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13963         }
13964
13965         cursor = intel_cursor_plane_create(dev_priv, pipe);
13966         if (IS_ERR(cursor)) {
13967                 ret = PTR_ERR(cursor);
13968                 goto fail;
13969         }
13970         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13971
13972         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13973                                         &primary->base, &cursor->base,
13974                                         &intel_crtc_funcs,
13975                                         "pipe %c", pipe_name(pipe));
13976         if (ret)
13977                 goto fail;
13978
13979         intel_crtc->pipe = pipe;
13980         intel_crtc->plane = primary->plane;
13981
13982         /* initialize shared scalers */
13983         intel_crtc_init_scalers(intel_crtc, crtc_state);
13984
13985         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13986                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13987         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = intel_crtc;
13988         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
13989
13990         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13991
13992         intel_color_init(&intel_crtc->base);
13993
13994         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13995
13996         return 0;
13997
13998 fail:
13999         /*
14000          * drm_mode_config_cleanup() will free up any
14001          * crtcs/planes already initialized.
14002          */
14003         kfree(crtc_state);
14004         kfree(intel_crtc);
14005
14006         return ret;
14007 }
14008
14009 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14010 {
14011         struct drm_device *dev = connector->base.dev;
14012
14013         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14014
14015         if (!connector->base.state->crtc)
14016                 return INVALID_PIPE;
14017
14018         return to_intel_crtc(connector->base.state->crtc)->pipe;
14019 }
14020
14021 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14022                                 struct drm_file *file)
14023 {
14024         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14025         struct drm_crtc *drmmode_crtc;
14026         struct intel_crtc *crtc;
14027
14028         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14029         if (!drmmode_crtc)
14030                 return -ENOENT;
14031
14032         crtc = to_intel_crtc(drmmode_crtc);
14033         pipe_from_crtc_id->pipe = crtc->pipe;
14034
14035         return 0;
14036 }
14037
14038 static int intel_encoder_clones(struct intel_encoder *encoder)
14039 {
14040         struct drm_device *dev = encoder->base.dev;
14041         struct intel_encoder *source_encoder;
14042         int index_mask = 0;
14043         int entry = 0;
14044
14045         for_each_intel_encoder(dev, source_encoder) {
14046                 if (encoders_cloneable(encoder, source_encoder))
14047                         index_mask |= (1 << entry);
14048
14049                 entry++;
14050         }
14051
14052         return index_mask;
14053 }
14054
14055 static bool has_edp_a(struct drm_i915_private *dev_priv)
14056 {
14057         if (!IS_MOBILE(dev_priv))
14058                 return false;
14059
14060         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14061                 return false;
14062
14063         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14064                 return false;
14065
14066         return true;
14067 }
14068
14069 static bool intel_crt_present(struct drm_i915_private *dev_priv)
14070 {
14071         if (INTEL_GEN(dev_priv) >= 9)
14072                 return false;
14073
14074         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14075                 return false;
14076
14077         if (IS_CHERRYVIEW(dev_priv))
14078                 return false;
14079
14080         if (HAS_PCH_LPT_H(dev_priv) &&
14081             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14082                 return false;
14083
14084         /* DDI E can't be used if DDI A requires 4 lanes */
14085         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14086                 return false;
14087
14088         if (!dev_priv->vbt.int_crt_support)
14089                 return false;
14090
14091         return true;
14092 }
14093
14094 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14095 {
14096         int pps_num;
14097         int pps_idx;
14098
14099         if (HAS_DDI(dev_priv))
14100                 return;
14101         /*
14102          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14103          * everywhere where registers can be write protected.
14104          */
14105         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14106                 pps_num = 2;
14107         else
14108                 pps_num = 1;
14109
14110         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14111                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14112
14113                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14114                 I915_WRITE(PP_CONTROL(pps_idx), val);
14115         }
14116 }
14117
14118 static void intel_pps_init(struct drm_i915_private *dev_priv)
14119 {
14120         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14121                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14122         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14123                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14124         else
14125                 dev_priv->pps_mmio_base = PPS_BASE;
14126
14127         intel_pps_unlock_regs_wa(dev_priv);
14128 }
14129
14130 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14131 {
14132         struct intel_encoder *encoder;
14133         bool dpd_is_edp = false;
14134
14135         intel_pps_init(dev_priv);
14136
14137         /*
14138          * intel_edp_init_connector() depends on this completing first, to
14139          * prevent the registeration of both eDP and LVDS and the incorrect
14140          * sharing of the PPS.
14141          */
14142         intel_lvds_init(dev_priv);
14143
14144         if (intel_crt_present(dev_priv))
14145                 intel_crt_init(dev_priv);
14146
14147         if (IS_GEN9_LP(dev_priv)) {
14148                 /*
14149                  * FIXME: Broxton doesn't support port detection via the
14150                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14151                  * detect the ports.
14152                  */
14153                 intel_ddi_init(dev_priv, PORT_A);
14154                 intel_ddi_init(dev_priv, PORT_B);
14155                 intel_ddi_init(dev_priv, PORT_C);
14156
14157                 intel_dsi_init(dev_priv);
14158         } else if (HAS_DDI(dev_priv)) {
14159                 int found;
14160
14161                 /*
14162                  * Haswell uses DDI functions to detect digital outputs.
14163                  * On SKL pre-D0 the strap isn't connected, so we assume
14164                  * it's there.
14165                  */
14166                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14167                 /* WaIgnoreDDIAStrap: skl */
14168                 if (found || IS_GEN9_BC(dev_priv))
14169                         intel_ddi_init(dev_priv, PORT_A);
14170
14171                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14172                  * register */
14173                 found = I915_READ(SFUSE_STRAP);
14174
14175                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14176                         intel_ddi_init(dev_priv, PORT_B);
14177                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14178                         intel_ddi_init(dev_priv, PORT_C);
14179                 if (found & SFUSE_STRAP_DDID_DETECTED)
14180                         intel_ddi_init(dev_priv, PORT_D);
14181                 /*
14182                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14183                  */
14184                 if (IS_GEN9_BC(dev_priv) &&
14185                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14186                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14187                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14188                         intel_ddi_init(dev_priv, PORT_E);
14189
14190         } else if (HAS_PCH_SPLIT(dev_priv)) {
14191                 int found;
14192                 dpd_is_edp = intel_dp_is_edp(dev_priv, PORT_D);
14193
14194                 if (has_edp_a(dev_priv))
14195                         intel_dp_init(dev_priv, DP_A, PORT_A);
14196
14197                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14198                         /* PCH SDVOB multiplex with HDMIB */
14199                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14200                         if (!found)
14201                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14202                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14203                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14204                 }
14205
14206                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14207                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14208
14209                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14210                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14211
14212                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14213                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14214
14215                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14216                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14217         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14218                 bool has_edp, has_port;
14219
14220                 /*
14221                  * The DP_DETECTED bit is the latched state of the DDC
14222                  * SDA pin at boot. However since eDP doesn't require DDC
14223                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14224                  * eDP ports may have been muxed to an alternate function.
14225                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14226                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14227                  * detect eDP ports.
14228                  *
14229                  * Sadly the straps seem to be missing sometimes even for HDMI
14230                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14231                  * and VBT for the presence of the port. Additionally we can't
14232                  * trust the port type the VBT declares as we've seen at least
14233                  * HDMI ports that the VBT claim are DP or eDP.
14234                  */
14235                 has_edp = intel_dp_is_edp(dev_priv, PORT_B);
14236                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14237                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14238                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14239                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14240                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14241
14242                 has_edp = intel_dp_is_edp(dev_priv, PORT_C);
14243                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14244                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14245                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14246                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14247                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14248
14249                 if (IS_CHERRYVIEW(dev_priv)) {
14250                         /*
14251                          * eDP not supported on port D,
14252                          * so no need to worry about it
14253                          */
14254                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14255                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14256                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14257                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14258                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14259                 }
14260
14261                 intel_dsi_init(dev_priv);
14262         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14263                 bool found = false;
14264
14265                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14266                         DRM_DEBUG_KMS("probing SDVOB\n");
14267                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14268                         if (!found && IS_G4X(dev_priv)) {
14269                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14270                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14271                         }
14272
14273                         if (!found && IS_G4X(dev_priv))
14274                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14275                 }
14276
14277                 /* Before G4X SDVOC doesn't have its own detect register */
14278
14279                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14280                         DRM_DEBUG_KMS("probing SDVOC\n");
14281                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14282                 }
14283
14284                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14285
14286                         if (IS_G4X(dev_priv)) {
14287                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14288                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14289                         }
14290                         if (IS_G4X(dev_priv))
14291                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14292                 }
14293
14294                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14295                         intel_dp_init(dev_priv, DP_D, PORT_D);
14296         } else if (IS_GEN2(dev_priv))
14297                 intel_dvo_init(dev_priv);
14298
14299         if (SUPPORTS_TV(dev_priv))
14300                 intel_tv_init(dev_priv);
14301
14302         intel_psr_init(dev_priv);
14303
14304         for_each_intel_encoder(&dev_priv->drm, encoder) {
14305                 encoder->base.possible_crtcs = encoder->crtc_mask;
14306                 encoder->base.possible_clones =
14307                         intel_encoder_clones(encoder);
14308         }
14309
14310         intel_init_pch_refclk(dev_priv);
14311
14312         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14313 }
14314
14315 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14316 {
14317         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14318
14319         drm_framebuffer_cleanup(fb);
14320
14321         i915_gem_object_lock(intel_fb->obj);
14322         WARN_ON(!intel_fb->obj->framebuffer_references--);
14323         i915_gem_object_unlock(intel_fb->obj);
14324
14325         i915_gem_object_put(intel_fb->obj);
14326
14327         kfree(intel_fb);
14328 }
14329
14330 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14331                                                 struct drm_file *file,
14332                                                 unsigned int *handle)
14333 {
14334         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14335         struct drm_i915_gem_object *obj = intel_fb->obj;
14336
14337         if (obj->userptr.mm) {
14338                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14339                 return -EINVAL;
14340         }
14341
14342         return drm_gem_handle_create(file, &obj->base, handle);
14343 }
14344
14345 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14346                                         struct drm_file *file,
14347                                         unsigned flags, unsigned color,
14348                                         struct drm_clip_rect *clips,
14349                                         unsigned num_clips)
14350 {
14351         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14352
14353         i915_gem_object_flush_if_display(obj);
14354         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14355
14356         return 0;
14357 }
14358
14359 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14360         .destroy = intel_user_framebuffer_destroy,
14361         .create_handle = intel_user_framebuffer_create_handle,
14362         .dirty = intel_user_framebuffer_dirty,
14363 };
14364
14365 static
14366 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14367                          uint64_t fb_modifier, uint32_t pixel_format)
14368 {
14369         u32 gen = INTEL_GEN(dev_priv);
14370
14371         if (gen >= 9) {
14372                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14373
14374                 /* "The stride in bytes must not exceed the of the size of 8K
14375                  *  pixels and 32K bytes."
14376                  */
14377                 return min(8192 * cpp, 32768);
14378         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
14379                 return 32*1024;
14380         } else if (gen >= 4) {
14381                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14382                         return 16*1024;
14383                 else
14384                         return 32*1024;
14385         } else if (gen >= 3) {
14386                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14387                         return 8*1024;
14388                 else
14389                         return 16*1024;
14390         } else {
14391                 /* XXX DSPC is limited to 4k tiled */
14392                 return 8*1024;
14393         }
14394 }
14395
14396 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14397                                   struct drm_i915_gem_object *obj,
14398                                   struct drm_mode_fb_cmd2 *mode_cmd)
14399 {
14400         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14401         struct drm_format_name_buf format_name;
14402         u32 pitch_limit, stride_alignment;
14403         unsigned int tiling, stride;
14404         int ret = -EINVAL;
14405
14406         i915_gem_object_lock(obj);
14407         obj->framebuffer_references++;
14408         tiling = i915_gem_object_get_tiling(obj);
14409         stride = i915_gem_object_get_stride(obj);
14410         i915_gem_object_unlock(obj);
14411
14412         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14413                 /*
14414                  * If there's a fence, enforce that
14415                  * the fb modifier and tiling mode match.
14416                  */
14417                 if (tiling != I915_TILING_NONE &&
14418                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14419                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14420                         goto err;
14421                 }
14422         } else {
14423                 if (tiling == I915_TILING_X) {
14424                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14425                 } else if (tiling == I915_TILING_Y) {
14426                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14427                         goto err;
14428                 }
14429         }
14430
14431         /* Passed in modifier sanity checking. */
14432         switch (mode_cmd->modifier[0]) {
14433         case I915_FORMAT_MOD_Y_TILED:
14434         case I915_FORMAT_MOD_Yf_TILED:
14435                 if (INTEL_GEN(dev_priv) < 9) {
14436                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14437                                       mode_cmd->modifier[0]);
14438                         goto err;
14439                 }
14440         case DRM_FORMAT_MOD_LINEAR:
14441         case I915_FORMAT_MOD_X_TILED:
14442                 break;
14443         default:
14444                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14445                               mode_cmd->modifier[0]);
14446                 goto err;
14447         }
14448
14449         /*
14450          * gen2/3 display engine uses the fence if present,
14451          * so the tiling mode must match the fb modifier exactly.
14452          */
14453         if (INTEL_INFO(dev_priv)->gen < 4 &&
14454             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14455                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14456                 goto err;
14457         }
14458
14459         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14460                                            mode_cmd->pixel_format);
14461         if (mode_cmd->pitches[0] > pitch_limit) {
14462                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14463                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14464                               "tiled" : "linear",
14465                               mode_cmd->pitches[0], pitch_limit);
14466                 goto err;
14467         }
14468
14469         /*
14470          * If there's a fence, enforce that
14471          * the fb pitch and fence stride match.
14472          */
14473         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14474                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14475                               mode_cmd->pitches[0], stride);
14476                 goto err;
14477         }
14478
14479         /* Reject formats not supported by any plane early. */
14480         switch (mode_cmd->pixel_format) {
14481         case DRM_FORMAT_C8:
14482         case DRM_FORMAT_RGB565:
14483         case DRM_FORMAT_XRGB8888:
14484         case DRM_FORMAT_ARGB8888:
14485                 break;
14486         case DRM_FORMAT_XRGB1555:
14487                 if (INTEL_GEN(dev_priv) > 3) {
14488                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14489                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14490                         goto err;
14491                 }
14492                 break;
14493         case DRM_FORMAT_ABGR8888:
14494                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14495                     INTEL_GEN(dev_priv) < 9) {
14496                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14497                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14498                         goto err;
14499                 }
14500                 break;
14501         case DRM_FORMAT_XBGR8888:
14502         case DRM_FORMAT_XRGB2101010:
14503         case DRM_FORMAT_XBGR2101010:
14504                 if (INTEL_GEN(dev_priv) < 4) {
14505                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14506                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14507                         goto err;
14508                 }
14509                 break;
14510         case DRM_FORMAT_ABGR2101010:
14511                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14512                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14513                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14514                         goto err;
14515                 }
14516                 break;
14517         case DRM_FORMAT_YUYV:
14518         case DRM_FORMAT_UYVY:
14519         case DRM_FORMAT_YVYU:
14520         case DRM_FORMAT_VYUY:
14521                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14522                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14523                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14524                         goto err;
14525                 }
14526                 break;
14527         default:
14528                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14529                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14530                 goto err;
14531         }
14532
14533         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14534         if (mode_cmd->offsets[0] != 0)
14535                 goto err;
14536
14537         drm_helper_mode_fill_fb_struct(&dev_priv->drm,
14538                                        &intel_fb->base, mode_cmd);
14539
14540         stride_alignment = intel_fb_stride_alignment(&intel_fb->base, 0);
14541         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14542                 DRM_DEBUG_KMS("pitch (%d) must be at least %u byte aligned\n",
14543                               mode_cmd->pitches[0], stride_alignment);
14544                 goto err;
14545         }
14546
14547         intel_fb->obj = obj;
14548
14549         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
14550         if (ret)
14551                 goto err;
14552
14553         ret = drm_framebuffer_init(obj->base.dev,
14554                                    &intel_fb->base,
14555                                    &intel_fb_funcs);
14556         if (ret) {
14557                 DRM_ERROR("framebuffer init failed %d\n", ret);
14558                 goto err;
14559         }
14560
14561         return 0;
14562
14563 err:
14564         i915_gem_object_lock(obj);
14565         obj->framebuffer_references--;
14566         i915_gem_object_unlock(obj);
14567         return ret;
14568 }
14569
14570 static struct drm_framebuffer *
14571 intel_user_framebuffer_create(struct drm_device *dev,
14572                               struct drm_file *filp,
14573                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14574 {
14575         struct drm_framebuffer *fb;
14576         struct drm_i915_gem_object *obj;
14577         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14578
14579         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14580         if (!obj)
14581                 return ERR_PTR(-ENOENT);
14582
14583         fb = intel_framebuffer_create(obj, &mode_cmd);
14584         if (IS_ERR(fb))
14585                 i915_gem_object_put(obj);
14586
14587         return fb;
14588 }
14589
14590 static void intel_atomic_state_free(struct drm_atomic_state *state)
14591 {
14592         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14593
14594         drm_atomic_state_default_release(state);
14595
14596         i915_sw_fence_fini(&intel_state->commit_ready);
14597
14598         kfree(state);
14599 }
14600
14601 static const struct drm_mode_config_funcs intel_mode_funcs = {
14602         .fb_create = intel_user_framebuffer_create,
14603         .output_poll_changed = intel_fbdev_output_poll_changed,
14604         .atomic_check = intel_atomic_check,
14605         .atomic_commit = intel_atomic_commit,
14606         .atomic_state_alloc = intel_atomic_state_alloc,
14607         .atomic_state_clear = intel_atomic_state_clear,
14608         .atomic_state_free = intel_atomic_state_free,
14609 };
14610
14611 /**
14612  * intel_init_display_hooks - initialize the display modesetting hooks
14613  * @dev_priv: device private
14614  */
14615 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14616 {
14617         intel_init_cdclk_hooks(dev_priv);
14618
14619         if (INTEL_INFO(dev_priv)->gen >= 9) {
14620                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14621                 dev_priv->display.get_initial_plane_config =
14622                         skylake_get_initial_plane_config;
14623                 dev_priv->display.crtc_compute_clock =
14624                         haswell_crtc_compute_clock;
14625                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14626                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14627         } else if (HAS_DDI(dev_priv)) {
14628                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14629                 dev_priv->display.get_initial_plane_config =
14630                         ironlake_get_initial_plane_config;
14631                 dev_priv->display.crtc_compute_clock =
14632                         haswell_crtc_compute_clock;
14633                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14634                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14635         } else if (HAS_PCH_SPLIT(dev_priv)) {
14636                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14637                 dev_priv->display.get_initial_plane_config =
14638                         ironlake_get_initial_plane_config;
14639                 dev_priv->display.crtc_compute_clock =
14640                         ironlake_crtc_compute_clock;
14641                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14642                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14643         } else if (IS_CHERRYVIEW(dev_priv)) {
14644                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14645                 dev_priv->display.get_initial_plane_config =
14646                         i9xx_get_initial_plane_config;
14647                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14648                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14649                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14650         } else if (IS_VALLEYVIEW(dev_priv)) {
14651                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14652                 dev_priv->display.get_initial_plane_config =
14653                         i9xx_get_initial_plane_config;
14654                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14655                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14656                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14657         } else if (IS_G4X(dev_priv)) {
14658                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14659                 dev_priv->display.get_initial_plane_config =
14660                         i9xx_get_initial_plane_config;
14661                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14662                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14663                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14664         } else if (IS_PINEVIEW(dev_priv)) {
14665                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14666                 dev_priv->display.get_initial_plane_config =
14667                         i9xx_get_initial_plane_config;
14668                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14669                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14670                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14671         } else if (!IS_GEN2(dev_priv)) {
14672                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14673                 dev_priv->display.get_initial_plane_config =
14674                         i9xx_get_initial_plane_config;
14675                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14676                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14677                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14678         } else {
14679                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14680                 dev_priv->display.get_initial_plane_config =
14681                         i9xx_get_initial_plane_config;
14682                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14683                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14684                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14685         }
14686
14687         if (IS_GEN5(dev_priv)) {
14688                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14689         } else if (IS_GEN6(dev_priv)) {
14690                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14691         } else if (IS_IVYBRIDGE(dev_priv)) {
14692                 /* FIXME: detect B0+ stepping and use auto training */
14693                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14694         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14695                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14696         }
14697
14698         if (dev_priv->info.gen >= 9)
14699                 dev_priv->display.update_crtcs = skl_update_crtcs;
14700         else
14701                 dev_priv->display.update_crtcs = intel_update_crtcs;
14702
14703         switch (INTEL_INFO(dev_priv)->gen) {
14704         case 2:
14705                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14706                 break;
14707
14708         case 3:
14709                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14710                 break;
14711
14712         case 4:
14713         case 5:
14714                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14715                 break;
14716
14717         case 6:
14718                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14719                 break;
14720         case 7:
14721         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14722                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14723                 break;
14724         case 9:
14725                 /* Drop through - unsupported since execlist only. */
14726         default:
14727                 /* Default just returns -ENODEV to indicate unsupported */
14728                 dev_priv->display.queue_flip = intel_default_queue_flip;
14729         }
14730 }
14731
14732 /*
14733  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
14734  * resume, or other times.  This quirk makes sure that's the case for
14735  * affected systems.
14736  */
14737 static void quirk_pipea_force(struct drm_device *dev)
14738 {
14739         struct drm_i915_private *dev_priv = to_i915(dev);
14740
14741         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
14742         DRM_INFO("applying pipe a force quirk\n");
14743 }
14744
14745 static void quirk_pipeb_force(struct drm_device *dev)
14746 {
14747         struct drm_i915_private *dev_priv = to_i915(dev);
14748
14749         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
14750         DRM_INFO("applying pipe b force quirk\n");
14751 }
14752
14753 /*
14754  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14755  */
14756 static void quirk_ssc_force_disable(struct drm_device *dev)
14757 {
14758         struct drm_i915_private *dev_priv = to_i915(dev);
14759         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14760         DRM_INFO("applying lvds SSC disable quirk\n");
14761 }
14762
14763 /*
14764  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14765  * brightness value
14766  */
14767 static void quirk_invert_brightness(struct drm_device *dev)
14768 {
14769         struct drm_i915_private *dev_priv = to_i915(dev);
14770         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14771         DRM_INFO("applying inverted panel brightness quirk\n");
14772 }
14773
14774 /* Some VBT's incorrectly indicate no backlight is present */
14775 static void quirk_backlight_present(struct drm_device *dev)
14776 {
14777         struct drm_i915_private *dev_priv = to_i915(dev);
14778         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14779         DRM_INFO("applying backlight present quirk\n");
14780 }
14781
14782 struct intel_quirk {
14783         int device;
14784         int subsystem_vendor;
14785         int subsystem_device;
14786         void (*hook)(struct drm_device *dev);
14787 };
14788
14789 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14790 struct intel_dmi_quirk {
14791         void (*hook)(struct drm_device *dev);
14792         const struct dmi_system_id (*dmi_id_list)[];
14793 };
14794
14795 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14796 {
14797         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14798         return 1;
14799 }
14800
14801 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14802         {
14803                 .dmi_id_list = &(const struct dmi_system_id[]) {
14804                         {
14805                                 .callback = intel_dmi_reverse_brightness,
14806                                 .ident = "NCR Corporation",
14807                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14808                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14809                                 },
14810                         },
14811                         { }  /* terminating entry */
14812                 },
14813                 .hook = quirk_invert_brightness,
14814         },
14815 };
14816
14817 static struct intel_quirk intel_quirks[] = {
14818         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
14819         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
14820
14821         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
14822         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
14823
14824         /* 830 needs to leave pipe A & dpll A up */
14825         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
14826
14827         /* 830 needs to leave pipe B & dpll B up */
14828         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
14829
14830         /* Lenovo U160 cannot use SSC on LVDS */
14831         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14832
14833         /* Sony Vaio Y cannot use SSC on LVDS */
14834         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14835
14836         /* Acer Aspire 5734Z must invert backlight brightness */
14837         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14838
14839         /* Acer/eMachines G725 */
14840         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14841
14842         /* Acer/eMachines e725 */
14843         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14844
14845         /* Acer/Packard Bell NCL20 */
14846         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14847
14848         /* Acer Aspire 4736Z */
14849         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14850
14851         /* Acer Aspire 5336 */
14852         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14853
14854         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14855         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14856
14857         /* Acer C720 Chromebook (Core i3 4005U) */
14858         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14859
14860         /* Apple Macbook 2,1 (Core 2 T7400) */
14861         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14862
14863         /* Apple Macbook 4,1 */
14864         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14865
14866         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14867         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14868
14869         /* HP Chromebook 14 (Celeron 2955U) */
14870         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14871
14872         /* Dell Chromebook 11 */
14873         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14874
14875         /* Dell Chromebook 11 (2015 version) */
14876         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14877 };
14878
14879 static void intel_init_quirks(struct drm_device *dev)
14880 {
14881         struct pci_dev *d = dev->pdev;
14882         int i;
14883
14884         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14885                 struct intel_quirk *q = &intel_quirks[i];
14886
14887                 if (d->device == q->device &&
14888                     (d->subsystem_vendor == q->subsystem_vendor ||
14889                      q->subsystem_vendor == PCI_ANY_ID) &&
14890                     (d->subsystem_device == q->subsystem_device ||
14891                      q->subsystem_device == PCI_ANY_ID))
14892                         q->hook(dev);
14893         }
14894         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14895                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14896                         intel_dmi_quirks[i].hook(dev);
14897         }
14898 }
14899
14900 /* Disable the VGA plane that we never use */
14901 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14902 {
14903         struct pci_dev *pdev = dev_priv->drm.pdev;
14904         u8 sr1;
14905         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14906
14907         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14908         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14909         outb(SR01, VGA_SR_INDEX);
14910         sr1 = inb(VGA_SR_DATA);
14911         outb(sr1 | 1<<5, VGA_SR_DATA);
14912         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14913         udelay(300);
14914
14915         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14916         POSTING_READ(vga_reg);
14917 }
14918
14919 void intel_modeset_init_hw(struct drm_device *dev)
14920 {
14921         struct drm_i915_private *dev_priv = to_i915(dev);
14922
14923         intel_update_cdclk(dev_priv);
14924         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14925
14926         intel_init_clock_gating(dev_priv);
14927 }
14928
14929 /*
14930  * Calculate what we think the watermarks should be for the state we've read
14931  * out of the hardware and then immediately program those watermarks so that
14932  * we ensure the hardware settings match our internal state.
14933  *
14934  * We can calculate what we think WM's should be by creating a duplicate of the
14935  * current state (which was constructed during hardware readout) and running it
14936  * through the atomic check code to calculate new watermark values in the
14937  * state object.
14938  */
14939 static void sanitize_watermarks(struct drm_device *dev)
14940 {
14941         struct drm_i915_private *dev_priv = to_i915(dev);
14942         struct drm_atomic_state *state;
14943         struct intel_atomic_state *intel_state;
14944         struct drm_crtc *crtc;
14945         struct drm_crtc_state *cstate;
14946         struct drm_modeset_acquire_ctx ctx;
14947         int ret;
14948         int i;
14949
14950         /* Only supported on platforms that use atomic watermark design */
14951         if (!dev_priv->display.optimize_watermarks)
14952                 return;
14953
14954         /*
14955          * We need to hold connection_mutex before calling duplicate_state so
14956          * that the connector loop is protected.
14957          */
14958         drm_modeset_acquire_init(&ctx, 0);
14959 retry:
14960         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14961         if (ret == -EDEADLK) {
14962                 drm_modeset_backoff(&ctx);
14963                 goto retry;
14964         } else if (WARN_ON(ret)) {
14965                 goto fail;
14966         }
14967
14968         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14969         if (WARN_ON(IS_ERR(state)))
14970                 goto fail;
14971
14972         intel_state = to_intel_atomic_state(state);
14973
14974         /*
14975          * Hardware readout is the only time we don't want to calculate
14976          * intermediate watermarks (since we don't trust the current
14977          * watermarks).
14978          */
14979         if (!HAS_GMCH_DISPLAY(dev_priv))
14980                 intel_state->skip_intermediate_wm = true;
14981
14982         ret = intel_atomic_check(dev, state);
14983         if (ret) {
14984                 /*
14985                  * If we fail here, it means that the hardware appears to be
14986                  * programmed in a way that shouldn't be possible, given our
14987                  * understanding of watermark requirements.  This might mean a
14988                  * mistake in the hardware readout code or a mistake in the
14989                  * watermark calculations for a given platform.  Raise a WARN
14990                  * so that this is noticeable.
14991                  *
14992                  * If this actually happens, we'll have to just leave the
14993                  * BIOS-programmed watermarks untouched and hope for the best.
14994                  */
14995                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14996                 goto put_state;
14997         }
14998
14999         /* Write calculated watermark values back */
15000         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15001                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15002
15003                 cs->wm.need_postvbl_update = true;
15004                 dev_priv->display.optimize_watermarks(intel_state, cs);
15005         }
15006
15007 put_state:
15008         drm_atomic_state_put(state);
15009 fail:
15010         drm_modeset_drop_locks(&ctx);
15011         drm_modeset_acquire_fini(&ctx);
15012 }
15013
15014 int intel_modeset_init(struct drm_device *dev)
15015 {
15016         struct drm_i915_private *dev_priv = to_i915(dev);
15017         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15018         enum pipe pipe;
15019         struct intel_crtc *crtc;
15020
15021         drm_mode_config_init(dev);
15022
15023         dev->mode_config.min_width = 0;
15024         dev->mode_config.min_height = 0;
15025
15026         dev->mode_config.preferred_depth = 24;
15027         dev->mode_config.prefer_shadow = 1;
15028
15029         dev->mode_config.allow_fb_modifiers = true;
15030
15031         dev->mode_config.funcs = &intel_mode_funcs;
15032
15033         init_llist_head(&dev_priv->atomic_helper.free_list);
15034         INIT_WORK(&dev_priv->atomic_helper.free_work,
15035                   intel_atomic_helper_free_state_worker);
15036
15037         intel_init_quirks(dev);
15038
15039         intel_init_pm(dev_priv);
15040
15041         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15042                 return 0;
15043
15044         /*
15045          * There may be no VBT; and if the BIOS enabled SSC we can
15046          * just keep using it to avoid unnecessary flicker.  Whereas if the
15047          * BIOS isn't using it, don't assume it will work even if the VBT
15048          * indicates as much.
15049          */
15050         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15051                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15052                                             DREF_SSC1_ENABLE);
15053
15054                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15055                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15056                                      bios_lvds_use_ssc ? "en" : "dis",
15057                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15058                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15059                 }
15060         }
15061
15062         if (IS_GEN2(dev_priv)) {
15063                 dev->mode_config.max_width = 2048;
15064                 dev->mode_config.max_height = 2048;
15065         } else if (IS_GEN3(dev_priv)) {
15066                 dev->mode_config.max_width = 4096;
15067                 dev->mode_config.max_height = 4096;
15068         } else {
15069                 dev->mode_config.max_width = 8192;
15070                 dev->mode_config.max_height = 8192;
15071         }
15072
15073         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15074                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15075                 dev->mode_config.cursor_height = 1023;
15076         } else if (IS_GEN2(dev_priv)) {
15077                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15078                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15079         } else {
15080                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15081                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15082         }
15083
15084         dev->mode_config.fb_base = ggtt->mappable_base;
15085
15086         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15087                       INTEL_INFO(dev_priv)->num_pipes,
15088                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15089
15090         for_each_pipe(dev_priv, pipe) {
15091                 int ret;
15092
15093                 ret = intel_crtc_init(dev_priv, pipe);
15094                 if (ret) {
15095                         drm_mode_config_cleanup(dev);
15096                         return ret;
15097                 }
15098         }
15099
15100         intel_shared_dpll_init(dev);
15101
15102         intel_update_czclk(dev_priv);
15103         intel_modeset_init_hw(dev);
15104
15105         if (dev_priv->max_cdclk_freq == 0)
15106                 intel_update_max_cdclk(dev_priv);
15107
15108         /* Just disable it once at startup */
15109         i915_disable_vga(dev_priv);
15110         intel_setup_outputs(dev_priv);
15111
15112         drm_modeset_lock_all(dev);
15113         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15114         drm_modeset_unlock_all(dev);
15115
15116         for_each_intel_crtc(dev, crtc) {
15117                 struct intel_initial_plane_config plane_config = {};
15118
15119                 if (!crtc->active)
15120                         continue;
15121
15122                 /*
15123                  * Note that reserving the BIOS fb up front prevents us
15124                  * from stuffing other stolen allocations like the ring
15125                  * on top.  This prevents some ugliness at boot time, and
15126                  * can even allow for smooth boot transitions if the BIOS
15127                  * fb is large enough for the active pipe configuration.
15128                  */
15129                 dev_priv->display.get_initial_plane_config(crtc,
15130                                                            &plane_config);
15131
15132                 /*
15133                  * If the fb is shared between multiple heads, we'll
15134                  * just get the first one.
15135                  */
15136                 intel_find_initial_plane_obj(crtc, &plane_config);
15137         }
15138
15139         /*
15140          * Make sure hardware watermarks really match the state we read out.
15141          * Note that we need to do this after reconstructing the BIOS fb's
15142          * since the watermark calculation done here will use pstate->fb.
15143          */
15144         if (!HAS_GMCH_DISPLAY(dev_priv))
15145                 sanitize_watermarks(dev);
15146
15147         return 0;
15148 }
15149
15150 static void intel_enable_pipe_a(struct drm_device *dev,
15151                                 struct drm_modeset_acquire_ctx *ctx)
15152 {
15153         struct intel_connector *connector;
15154         struct drm_connector_list_iter conn_iter;
15155         struct drm_connector *crt = NULL;
15156         struct intel_load_detect_pipe load_detect_temp;
15157         int ret;
15158
15159         /* We can't just switch on the pipe A, we need to set things up with a
15160          * proper mode and output configuration. As a gross hack, enable pipe A
15161          * by enabling the load detect pipe once. */
15162         drm_connector_list_iter_begin(dev, &conn_iter);
15163         for_each_intel_connector_iter(connector, &conn_iter) {
15164                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15165                         crt = &connector->base;
15166                         break;
15167                 }
15168         }
15169         drm_connector_list_iter_end(&conn_iter);
15170
15171         if (!crt)
15172                 return;
15173
15174         ret = intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx);
15175         WARN(ret < 0, "All modeset mutexes are locked, but intel_get_load_detect_pipe failed\n");
15176
15177         if (ret > 0)
15178                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15179 }
15180
15181 static bool
15182 intel_check_plane_mapping(struct intel_crtc *crtc)
15183 {
15184         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15185         u32 val;
15186
15187         if (INTEL_INFO(dev_priv)->num_pipes == 1)
15188                 return true;
15189
15190         val = I915_READ(DSPCNTR(!crtc->plane));
15191
15192         if ((val & DISPLAY_PLANE_ENABLE) &&
15193             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15194                 return false;
15195
15196         return true;
15197 }
15198
15199 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15200 {
15201         struct drm_device *dev = crtc->base.dev;
15202         struct intel_encoder *encoder;
15203
15204         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15205                 return true;
15206
15207         return false;
15208 }
15209
15210 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15211 {
15212         struct drm_device *dev = encoder->base.dev;
15213         struct intel_connector *connector;
15214
15215         for_each_connector_on_encoder(dev, &encoder->base, connector)
15216                 return connector;
15217
15218         return NULL;
15219 }
15220
15221 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15222                               enum transcoder pch_transcoder)
15223 {
15224         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15225                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
15226 }
15227
15228 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15229                                 struct drm_modeset_acquire_ctx *ctx)
15230 {
15231         struct drm_device *dev = crtc->base.dev;
15232         struct drm_i915_private *dev_priv = to_i915(dev);
15233         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15234
15235         /* Clear any frame start delays used for debugging left by the BIOS */
15236         if (!transcoder_is_dsi(cpu_transcoder)) {
15237                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15238
15239                 I915_WRITE(reg,
15240                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15241         }
15242
15243         /* restore vblank interrupts to correct state */
15244         drm_crtc_vblank_reset(&crtc->base);
15245         if (crtc->active) {
15246                 struct intel_plane *plane;
15247
15248                 drm_crtc_vblank_on(&crtc->base);
15249
15250                 /* Disable everything but the primary plane */
15251                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15252                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15253                                 continue;
15254
15255                         trace_intel_disable_plane(&plane->base, crtc);
15256                         plane->disable_plane(plane, crtc);
15257                 }
15258         }
15259
15260         /* We need to sanitize the plane -> pipe mapping first because this will
15261          * disable the crtc (and hence change the state) if it is wrong. Note
15262          * that gen4+ has a fixed plane -> pipe mapping.  */
15263         if (INTEL_GEN(dev_priv) < 4 && !intel_check_plane_mapping(crtc)) {
15264                 bool plane;
15265
15266                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
15267                               crtc->base.base.id, crtc->base.name);
15268
15269                 /* Pipe has the wrong plane attached and the plane is active.
15270                  * Temporarily change the plane mapping and disable everything
15271                  * ...  */
15272                 plane = crtc->plane;
15273                 crtc->base.primary->state->visible = true;
15274                 crtc->plane = !plane;
15275                 intel_crtc_disable_noatomic(&crtc->base);
15276                 crtc->plane = plane;
15277         }
15278
15279         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15280             crtc->pipe == PIPE_A && !crtc->active) {
15281                 /* BIOS forgot to enable pipe A, this mostly happens after
15282                  * resume. Force-enable the pipe to fix this, the update_dpms
15283                  * call below we restore the pipe to the right state, but leave
15284                  * the required bits on. */
15285                 intel_enable_pipe_a(dev, ctx);
15286         }
15287
15288         /* Adjust the state of the output pipe according to whether we
15289          * have active connectors/encoders. */
15290         if (crtc->active && !intel_crtc_has_encoders(crtc))
15291                 intel_crtc_disable_noatomic(&crtc->base);
15292
15293         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15294                 /*
15295                  * We start out with underrun reporting disabled to avoid races.
15296                  * For correct bookkeeping mark this on active crtcs.
15297                  *
15298                  * Also on gmch platforms we dont have any hardware bits to
15299                  * disable the underrun reporting. Which means we need to start
15300                  * out with underrun reporting disabled also on inactive pipes,
15301                  * since otherwise we'll complain about the garbage we read when
15302                  * e.g. coming up after runtime pm.
15303                  *
15304                  * No protection against concurrent access is required - at
15305                  * worst a fifo underrun happens which also sets this to false.
15306                  */
15307                 crtc->cpu_fifo_underrun_disabled = true;
15308                 /*
15309                  * We track the PCH trancoder underrun reporting state
15310                  * within the crtc. With crtc for pipe A housing the underrun
15311                  * reporting state for PCH transcoder A, crtc for pipe B housing
15312                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15313                  * and marking underrun reporting as disabled for the non-existing
15314                  * PCH transcoders B and C would prevent enabling the south
15315                  * error interrupt (see cpt_can_enable_serr_int()).
15316                  */
15317                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
15318                         crtc->pch_fifo_underrun_disabled = true;
15319         }
15320 }
15321
15322 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15323 {
15324         struct intel_connector *connector;
15325
15326         /* We need to check both for a crtc link (meaning that the
15327          * encoder is active and trying to read from a pipe) and the
15328          * pipe itself being active. */
15329         bool has_active_crtc = encoder->base.crtc &&
15330                 to_intel_crtc(encoder->base.crtc)->active;
15331
15332         connector = intel_encoder_find_connector(encoder);
15333         if (connector && !has_active_crtc) {
15334                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15335                               encoder->base.base.id,
15336                               encoder->base.name);
15337
15338                 /* Connector is active, but has no active pipe. This is
15339                  * fallout from our resume register restoring. Disable
15340                  * the encoder manually again. */
15341                 if (encoder->base.crtc) {
15342                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15343
15344                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15345                                       encoder->base.base.id,
15346                                       encoder->base.name);
15347                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15348                         if (encoder->post_disable)
15349                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15350                 }
15351                 encoder->base.crtc = NULL;
15352
15353                 /* Inconsistent output/port/pipe state happens presumably due to
15354                  * a bug in one of the get_hw_state functions. Or someplace else
15355                  * in our code, like the register restore mess on resume. Clamp
15356                  * things to off as a safer default. */
15357
15358                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15359                 connector->base.encoder = NULL;
15360         }
15361         /* Enabled encoders without active connectors will be fixed in
15362          * the crtc fixup. */
15363 }
15364
15365 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15366 {
15367         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15368
15369         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15370                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15371                 i915_disable_vga(dev_priv);
15372         }
15373 }
15374
15375 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15376 {
15377         /* This function can be called both from intel_modeset_setup_hw_state or
15378          * at a very early point in our resume sequence, where the power well
15379          * structures are not yet restored. Since this function is at a very
15380          * paranoid "someone might have enabled VGA while we were not looking"
15381          * level, just check if the power well is enabled instead of trying to
15382          * follow the "don't touch the power well if we don't need it" policy
15383          * the rest of the driver uses. */
15384         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15385                 return;
15386
15387         i915_redisable_vga_power_on(dev_priv);
15388
15389         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15390 }
15391
15392 static bool primary_get_hw_state(struct intel_plane *plane)
15393 {
15394         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15395
15396         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15397 }
15398
15399 /* FIXME read out full plane state for all planes */
15400 static void readout_plane_state(struct intel_crtc *crtc)
15401 {
15402         struct intel_plane *primary = to_intel_plane(crtc->base.primary);
15403         bool visible;
15404
15405         visible = crtc->active && primary_get_hw_state(primary);
15406
15407         intel_set_plane_visible(to_intel_crtc_state(crtc->base.state),
15408                                 to_intel_plane_state(primary->base.state),
15409                                 visible);
15410 }
15411
15412 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15413 {
15414         struct drm_i915_private *dev_priv = to_i915(dev);
15415         enum pipe pipe;
15416         struct intel_crtc *crtc;
15417         struct intel_encoder *encoder;
15418         struct intel_connector *connector;
15419         struct drm_connector_list_iter conn_iter;
15420         int i;
15421
15422         dev_priv->active_crtcs = 0;
15423
15424         for_each_intel_crtc(dev, crtc) {
15425                 struct intel_crtc_state *crtc_state =
15426                         to_intel_crtc_state(crtc->base.state);
15427
15428                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15429                 memset(crtc_state, 0, sizeof(*crtc_state));
15430                 crtc_state->base.crtc = &crtc->base;
15431
15432                 crtc_state->base.active = crtc_state->base.enable =
15433                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15434
15435                 crtc->base.enabled = crtc_state->base.enable;
15436                 crtc->active = crtc_state->base.active;
15437
15438                 if (crtc_state->base.active)
15439                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15440
15441                 readout_plane_state(crtc);
15442
15443                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15444                               crtc->base.base.id, crtc->base.name,
15445                               enableddisabled(crtc_state->base.active));
15446         }
15447
15448         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15449                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15450
15451                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15452                                                   &pll->state.hw_state);
15453                 pll->state.crtc_mask = 0;
15454                 for_each_intel_crtc(dev, crtc) {
15455                         struct intel_crtc_state *crtc_state =
15456                                 to_intel_crtc_state(crtc->base.state);
15457
15458                         if (crtc_state->base.active &&
15459                             crtc_state->shared_dpll == pll)
15460                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15461                 }
15462                 pll->active_mask = pll->state.crtc_mask;
15463
15464                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15465                               pll->name, pll->state.crtc_mask, pll->on);
15466         }
15467
15468         for_each_intel_encoder(dev, encoder) {
15469                 pipe = 0;
15470
15471                 if (encoder->get_hw_state(encoder, &pipe)) {
15472                         struct intel_crtc_state *crtc_state;
15473
15474                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15475                         crtc_state = to_intel_crtc_state(crtc->base.state);
15476
15477                         encoder->base.crtc = &crtc->base;
15478                         crtc_state->output_types |= 1 << encoder->type;
15479                         encoder->get_config(encoder, crtc_state);
15480                 } else {
15481                         encoder->base.crtc = NULL;
15482                 }
15483
15484                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15485                               encoder->base.base.id, encoder->base.name,
15486                               enableddisabled(encoder->base.crtc),
15487                               pipe_name(pipe));
15488         }
15489
15490         drm_connector_list_iter_begin(dev, &conn_iter);
15491         for_each_intel_connector_iter(connector, &conn_iter) {
15492                 if (connector->get_hw_state(connector)) {
15493                         connector->base.dpms = DRM_MODE_DPMS_ON;
15494
15495                         encoder = connector->encoder;
15496                         connector->base.encoder = &encoder->base;
15497
15498                         if (encoder->base.crtc &&
15499                             encoder->base.crtc->state->active) {
15500                                 /*
15501                                  * This has to be done during hardware readout
15502                                  * because anything calling .crtc_disable may
15503                                  * rely on the connector_mask being accurate.
15504                                  */
15505                                 encoder->base.crtc->state->connector_mask |=
15506                                         1 << drm_connector_index(&connector->base);
15507                                 encoder->base.crtc->state->encoder_mask |=
15508                                         1 << drm_encoder_index(&encoder->base);
15509                         }
15510
15511                 } else {
15512                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15513                         connector->base.encoder = NULL;
15514                 }
15515                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15516                               connector->base.base.id, connector->base.name,
15517                               enableddisabled(connector->base.encoder));
15518         }
15519         drm_connector_list_iter_end(&conn_iter);
15520
15521         for_each_intel_crtc(dev, crtc) {
15522                 struct intel_crtc_state *crtc_state =
15523                         to_intel_crtc_state(crtc->base.state);
15524                 int pixclk = 0;
15525
15526                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15527                 if (crtc_state->base.active) {
15528                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15529                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15530                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15531
15532                         /*
15533                          * The initial mode needs to be set in order to keep
15534                          * the atomic core happy. It wants a valid mode if the
15535                          * crtc's enabled, so we do the above call.
15536                          *
15537                          * But we don't set all the derived state fully, hence
15538                          * set a flag to indicate that a full recalculation is
15539                          * needed on the next commit.
15540                          */
15541                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15542
15543                         intel_crtc_compute_pixel_rate(crtc_state);
15544
15545                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv) ||
15546                             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15547                                 pixclk = crtc_state->pixel_rate;
15548                         else
15549                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15550
15551                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15552                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
15553                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15554
15555                         drm_calc_timestamping_constants(&crtc->base,
15556                                                         &crtc_state->base.adjusted_mode);
15557                         update_scanline_offset(crtc);
15558                 }
15559
15560                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15561
15562                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15563         }
15564 }
15565
15566 static void
15567 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15568 {
15569         struct intel_encoder *encoder;
15570
15571         for_each_intel_encoder(&dev_priv->drm, encoder) {
15572                 u64 get_domains;
15573                 enum intel_display_power_domain domain;
15574
15575                 if (!encoder->get_power_domains)
15576                         continue;
15577
15578                 get_domains = encoder->get_power_domains(encoder);
15579                 for_each_power_domain(domain, get_domains)
15580                         intel_display_power_get(dev_priv, domain);
15581         }
15582 }
15583
15584 /* Scan out the current hw modeset state,
15585  * and sanitizes it to the current state
15586  */
15587 static void
15588 intel_modeset_setup_hw_state(struct drm_device *dev,
15589                              struct drm_modeset_acquire_ctx *ctx)
15590 {
15591         struct drm_i915_private *dev_priv = to_i915(dev);
15592         enum pipe pipe;
15593         struct intel_crtc *crtc;
15594         struct intel_encoder *encoder;
15595         int i;
15596
15597         intel_modeset_readout_hw_state(dev);
15598
15599         /* HW state is read out, now we need to sanitize this mess. */
15600         get_encoder_power_domains(dev_priv);
15601
15602         for_each_intel_encoder(dev, encoder) {
15603                 intel_sanitize_encoder(encoder);
15604         }
15605
15606         for_each_pipe(dev_priv, pipe) {
15607                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15608
15609                 intel_sanitize_crtc(crtc, ctx);
15610                 intel_dump_pipe_config(crtc, crtc->config,
15611                                        "[setup_hw_state]");
15612         }
15613
15614         intel_modeset_update_connector_atomic_state(dev);
15615
15616         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15617                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15618
15619                 if (!pll->on || pll->active_mask)
15620                         continue;
15621
15622                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15623
15624                 pll->funcs.disable(dev_priv, pll);
15625                 pll->on = false;
15626         }
15627
15628         if (IS_G4X(dev_priv)) {
15629                 g4x_wm_get_hw_state(dev);
15630                 g4x_wm_sanitize(dev_priv);
15631         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15632                 vlv_wm_get_hw_state(dev);
15633                 vlv_wm_sanitize(dev_priv);
15634         } else if (IS_GEN9(dev_priv)) {
15635                 skl_wm_get_hw_state(dev);
15636         } else if (HAS_PCH_SPLIT(dev_priv)) {
15637                 ilk_wm_get_hw_state(dev);
15638         }
15639
15640         for_each_intel_crtc(dev, crtc) {
15641                 u64 put_domains;
15642
15643                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15644                 if (WARN_ON(put_domains))
15645                         modeset_put_power_domains(dev_priv, put_domains);
15646         }
15647         intel_display_set_init_power(dev_priv, false);
15648
15649         intel_power_domains_verify_state(dev_priv);
15650
15651         intel_fbc_init_pipe_state(dev_priv);
15652 }
15653
15654 void intel_display_resume(struct drm_device *dev)
15655 {
15656         struct drm_i915_private *dev_priv = to_i915(dev);
15657         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15658         struct drm_modeset_acquire_ctx ctx;
15659         int ret;
15660
15661         dev_priv->modeset_restore_state = NULL;
15662         if (state)
15663                 state->acquire_ctx = &ctx;
15664
15665         drm_modeset_acquire_init(&ctx, 0);
15666
15667         while (1) {
15668                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15669                 if (ret != -EDEADLK)
15670                         break;
15671
15672                 drm_modeset_backoff(&ctx);
15673         }
15674
15675         if (!ret)
15676                 ret = __intel_display_resume(dev, state, &ctx);
15677
15678         drm_modeset_drop_locks(&ctx);
15679         drm_modeset_acquire_fini(&ctx);
15680
15681         if (ret)
15682                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15683         if (state)
15684                 drm_atomic_state_put(state);
15685 }
15686
15687 void intel_modeset_gem_init(struct drm_device *dev)
15688 {
15689         struct drm_i915_private *dev_priv = to_i915(dev);
15690
15691         intel_init_gt_powersave(dev_priv);
15692
15693         intel_setup_overlay(dev_priv);
15694 }
15695
15696 int intel_connector_register(struct drm_connector *connector)
15697 {
15698         struct intel_connector *intel_connector = to_intel_connector(connector);
15699         int ret;
15700
15701         ret = intel_backlight_device_register(intel_connector);
15702         if (ret)
15703                 goto err;
15704
15705         return 0;
15706
15707 err:
15708         return ret;
15709 }
15710
15711 void intel_connector_unregister(struct drm_connector *connector)
15712 {
15713         struct intel_connector *intel_connector = to_intel_connector(connector);
15714
15715         intel_backlight_device_unregister(intel_connector);
15716         intel_panel_destroy_backlight(connector);
15717 }
15718
15719 void intel_modeset_cleanup(struct drm_device *dev)
15720 {
15721         struct drm_i915_private *dev_priv = to_i915(dev);
15722
15723         flush_work(&dev_priv->atomic_helper.free_work);
15724         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15725
15726         intel_disable_gt_powersave(dev_priv);
15727
15728         /*
15729          * Interrupts and polling as the first thing to avoid creating havoc.
15730          * Too much stuff here (turning of connectors, ...) would
15731          * experience fancy races otherwise.
15732          */
15733         intel_irq_uninstall(dev_priv);
15734
15735         /*
15736          * Due to the hpd irq storm handling the hotplug work can re-arm the
15737          * poll handlers. Hence disable polling after hpd handling is shut down.
15738          */
15739         drm_kms_helper_poll_fini(dev);
15740
15741         intel_unregister_dsm_handler();
15742
15743         intel_fbc_global_disable(dev_priv);
15744
15745         /* flush any delayed tasks or pending work */
15746         flush_scheduled_work();
15747
15748         drm_mode_config_cleanup(dev);
15749
15750         intel_cleanup_overlay(dev_priv);
15751
15752         intel_cleanup_gt_powersave(dev_priv);
15753
15754         intel_teardown_gmbus(dev_priv);
15755 }
15756
15757 void intel_connector_attach_encoder(struct intel_connector *connector,
15758                                     struct intel_encoder *encoder)
15759 {
15760         connector->encoder = encoder;
15761         drm_mode_connector_attach_encoder(&connector->base,
15762                                           &encoder->base);
15763 }
15764
15765 /*
15766  * set vga decode state - true == enable VGA decode
15767  */
15768 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15769 {
15770         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15771         u16 gmch_ctrl;
15772
15773         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15774                 DRM_ERROR("failed to read control word\n");
15775                 return -EIO;
15776         }
15777
15778         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15779                 return 0;
15780
15781         if (state)
15782                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15783         else
15784                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15785
15786         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15787                 DRM_ERROR("failed to write control word\n");
15788                 return -EIO;
15789         }
15790
15791         return 0;
15792 }
15793
15794 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15795
15796 struct intel_display_error_state {
15797
15798         u32 power_well_driver;
15799
15800         int num_transcoders;
15801
15802         struct intel_cursor_error_state {
15803                 u32 control;
15804                 u32 position;
15805                 u32 base;
15806                 u32 size;
15807         } cursor[I915_MAX_PIPES];
15808
15809         struct intel_pipe_error_state {
15810                 bool power_domain_on;
15811                 u32 source;
15812                 u32 stat;
15813         } pipe[I915_MAX_PIPES];
15814
15815         struct intel_plane_error_state {
15816                 u32 control;
15817                 u32 stride;
15818                 u32 size;
15819                 u32 pos;
15820                 u32 addr;
15821                 u32 surface;
15822                 u32 tile_offset;
15823         } plane[I915_MAX_PIPES];
15824
15825         struct intel_transcoder_error_state {
15826                 bool power_domain_on;
15827                 enum transcoder cpu_transcoder;
15828
15829                 u32 conf;
15830
15831                 u32 htotal;
15832                 u32 hblank;
15833                 u32 hsync;
15834                 u32 vtotal;
15835                 u32 vblank;
15836                 u32 vsync;
15837         } transcoder[4];
15838 };
15839
15840 struct intel_display_error_state *
15841 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15842 {
15843         struct intel_display_error_state *error;
15844         int transcoders[] = {
15845                 TRANSCODER_A,
15846                 TRANSCODER_B,
15847                 TRANSCODER_C,
15848                 TRANSCODER_EDP,
15849         };
15850         int i;
15851
15852         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15853                 return NULL;
15854
15855         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15856         if (error == NULL)
15857                 return NULL;
15858
15859         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15860                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15861
15862         for_each_pipe(dev_priv, i) {
15863                 error->pipe[i].power_domain_on =
15864                         __intel_display_power_is_enabled(dev_priv,
15865                                                          POWER_DOMAIN_PIPE(i));
15866                 if (!error->pipe[i].power_domain_on)
15867                         continue;
15868
15869                 error->cursor[i].control = I915_READ(CURCNTR(i));
15870                 error->cursor[i].position = I915_READ(CURPOS(i));
15871                 error->cursor[i].base = I915_READ(CURBASE(i));
15872
15873                 error->plane[i].control = I915_READ(DSPCNTR(i));
15874                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15875                 if (INTEL_GEN(dev_priv) <= 3) {
15876                         error->plane[i].size = I915_READ(DSPSIZE(i));
15877                         error->plane[i].pos = I915_READ(DSPPOS(i));
15878                 }
15879                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15880                         error->plane[i].addr = I915_READ(DSPADDR(i));
15881                 if (INTEL_GEN(dev_priv) >= 4) {
15882                         error->plane[i].surface = I915_READ(DSPSURF(i));
15883                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15884                 }
15885
15886                 error->pipe[i].source = I915_READ(PIPESRC(i));
15887
15888                 if (HAS_GMCH_DISPLAY(dev_priv))
15889                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15890         }
15891
15892         /* Note: this does not include DSI transcoders. */
15893         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15894         if (HAS_DDI(dev_priv))
15895                 error->num_transcoders++; /* Account for eDP. */
15896
15897         for (i = 0; i < error->num_transcoders; i++) {
15898                 enum transcoder cpu_transcoder = transcoders[i];
15899
15900                 error->transcoder[i].power_domain_on =
15901                         __intel_display_power_is_enabled(dev_priv,
15902                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15903                 if (!error->transcoder[i].power_domain_on)
15904                         continue;
15905
15906                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15907
15908                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15909                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15910                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15911                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15912                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15913                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15914                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15915         }
15916
15917         return error;
15918 }
15919
15920 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15921
15922 void
15923 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15924                                 struct intel_display_error_state *error)
15925 {
15926         struct drm_i915_private *dev_priv = m->i915;
15927         int i;
15928
15929         if (!error)
15930                 return;
15931
15932         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15933         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15934                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15935                            error->power_well_driver);
15936         for_each_pipe(dev_priv, i) {
15937                 err_printf(m, "Pipe [%d]:\n", i);
15938                 err_printf(m, "  Power: %s\n",
15939                            onoff(error->pipe[i].power_domain_on));
15940                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15941                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15942
15943                 err_printf(m, "Plane [%d]:\n", i);
15944                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15945                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15946                 if (INTEL_GEN(dev_priv) <= 3) {
15947                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15948                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15949                 }
15950                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15951                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15952                 if (INTEL_GEN(dev_priv) >= 4) {
15953                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15954                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15955                 }
15956
15957                 err_printf(m, "Cursor [%d]:\n", i);
15958                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15959                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15960                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15961         }
15962
15963         for (i = 0; i < error->num_transcoders; i++) {
15964                 err_printf(m, "CPU transcoder: %s\n",
15965                            transcoder_name(error->transcoder[i].cpu_transcoder));
15966                 err_printf(m, "  Power: %s\n",
15967                            onoff(error->transcoder[i].power_domain_on));
15968                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15969                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15970                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15971                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15972                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15973                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15974                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15975         }
15976 }
15977
15978 #endif