]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/intel_display.c
Merge tag 'for-linus-20170812' of git://git.infradead.org/linux-mtd
[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         /* we keep both pipes enabled on 830 */
1197         if (IS_I830(dev_priv))
1198                 state = true;
1199
1200         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1201         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1202                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1203                 cur_state = !!(val & PIPECONF_ENABLE);
1204
1205                 intel_display_power_put(dev_priv, power_domain);
1206         } else {
1207                 cur_state = false;
1208         }
1209
1210         I915_STATE_WARN(cur_state != state,
1211              "pipe %c assertion failure (expected %s, current %s)\n",
1212                         pipe_name(pipe), onoff(state), onoff(cur_state));
1213 }
1214
1215 static void assert_plane(struct drm_i915_private *dev_priv,
1216                          enum plane plane, bool state)
1217 {
1218         u32 val;
1219         bool cur_state;
1220
1221         val = I915_READ(DSPCNTR(plane));
1222         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1223         I915_STATE_WARN(cur_state != state,
1224              "plane %c assertion failure (expected %s, current %s)\n",
1225                         plane_name(plane), onoff(state), onoff(cur_state));
1226 }
1227
1228 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1229 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1230
1231 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1232                                    enum pipe pipe)
1233 {
1234         int i;
1235
1236         /* Primary planes are fixed to pipes on gen4+ */
1237         if (INTEL_GEN(dev_priv) >= 4) {
1238                 u32 val = I915_READ(DSPCNTR(pipe));
1239                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1240                      "plane %c assertion failure, should be disabled but not\n",
1241                      plane_name(pipe));
1242                 return;
1243         }
1244
1245         /* Need to check both planes against the pipe */
1246         for_each_pipe(dev_priv, i) {
1247                 u32 val = I915_READ(DSPCNTR(i));
1248                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1249                         DISPPLANE_SEL_PIPE_SHIFT;
1250                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1251                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1252                      plane_name(i), pipe_name(pipe));
1253         }
1254 }
1255
1256 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1257                                     enum pipe pipe)
1258 {
1259         int sprite;
1260
1261         if (INTEL_GEN(dev_priv) >= 9) {
1262                 for_each_sprite(dev_priv, pipe, sprite) {
1263                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1264                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1265                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1266                              sprite, pipe_name(pipe));
1267                 }
1268         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1269                 for_each_sprite(dev_priv, pipe, sprite) {
1270                         u32 val = I915_READ(SPCNTR(pipe, PLANE_SPRITE0 + sprite));
1271                         I915_STATE_WARN(val & SP_ENABLE,
1272                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1273                              sprite_name(pipe, sprite), pipe_name(pipe));
1274                 }
1275         } else if (INTEL_GEN(dev_priv) >= 7) {
1276                 u32 val = I915_READ(SPRCTL(pipe));
1277                 I915_STATE_WARN(val & SPRITE_ENABLE,
1278                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1279                      plane_name(pipe), pipe_name(pipe));
1280         } else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv)) {
1281                 u32 val = I915_READ(DVSCNTR(pipe));
1282                 I915_STATE_WARN(val & DVS_ENABLE,
1283                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1284                      plane_name(pipe), pipe_name(pipe));
1285         }
1286 }
1287
1288 static void assert_vblank_disabled(struct drm_crtc *crtc)
1289 {
1290         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1291                 drm_crtc_vblank_put(crtc);
1292 }
1293
1294 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1295                                     enum pipe pipe)
1296 {
1297         u32 val;
1298         bool enabled;
1299
1300         val = I915_READ(PCH_TRANSCONF(pipe));
1301         enabled = !!(val & TRANS_ENABLE);
1302         I915_STATE_WARN(enabled,
1303              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1304              pipe_name(pipe));
1305 }
1306
1307 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1308                             enum pipe pipe, u32 port_sel, u32 val)
1309 {
1310         if ((val & DP_PORT_EN) == 0)
1311                 return false;
1312
1313         if (HAS_PCH_CPT(dev_priv)) {
1314                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1315                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1316                         return false;
1317         } else if (IS_CHERRYVIEW(dev_priv)) {
1318                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1319                         return false;
1320         } else {
1321                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1322                         return false;
1323         }
1324         return true;
1325 }
1326
1327 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1328                               enum pipe pipe, u32 val)
1329 {
1330         if ((val & SDVO_ENABLE) == 0)
1331                 return false;
1332
1333         if (HAS_PCH_CPT(dev_priv)) {
1334                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1335                         return false;
1336         } else if (IS_CHERRYVIEW(dev_priv)) {
1337                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1338                         return false;
1339         } else {
1340                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1341                         return false;
1342         }
1343         return true;
1344 }
1345
1346 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1347                               enum pipe pipe, u32 val)
1348 {
1349         if ((val & LVDS_PORT_EN) == 0)
1350                 return false;
1351
1352         if (HAS_PCH_CPT(dev_priv)) {
1353                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1354                         return false;
1355         } else {
1356                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1357                         return false;
1358         }
1359         return true;
1360 }
1361
1362 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1363                               enum pipe pipe, u32 val)
1364 {
1365         if ((val & ADPA_DAC_ENABLE) == 0)
1366                 return false;
1367         if (HAS_PCH_CPT(dev_priv)) {
1368                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1369                         return false;
1370         } else {
1371                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1372                         return false;
1373         }
1374         return true;
1375 }
1376
1377 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1378                                    enum pipe pipe, i915_reg_t reg,
1379                                    u32 port_sel)
1380 {
1381         u32 val = I915_READ(reg);
1382         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1383              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1384              i915_mmio_reg_offset(reg), pipe_name(pipe));
1385
1386         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1387              && (val & DP_PIPEB_SELECT),
1388              "IBX PCH dp port still using transcoder B\n");
1389 }
1390
1391 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1392                                      enum pipe pipe, i915_reg_t reg)
1393 {
1394         u32 val = I915_READ(reg);
1395         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1396              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1397              i915_mmio_reg_offset(reg), pipe_name(pipe));
1398
1399         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1400              && (val & SDVO_PIPE_B_SELECT),
1401              "IBX PCH hdmi port still using transcoder B\n");
1402 }
1403
1404 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1405                                       enum pipe pipe)
1406 {
1407         u32 val;
1408
1409         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1410         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1411         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1412
1413         val = I915_READ(PCH_ADPA);
1414         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1415              "PCH VGA enabled on transcoder %c, should be disabled\n",
1416              pipe_name(pipe));
1417
1418         val = I915_READ(PCH_LVDS);
1419         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1420              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1421              pipe_name(pipe));
1422
1423         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1424         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1425         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1426 }
1427
1428 static void _vlv_enable_pll(struct intel_crtc *crtc,
1429                             const struct intel_crtc_state *pipe_config)
1430 {
1431         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1432         enum pipe pipe = crtc->pipe;
1433
1434         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1435         POSTING_READ(DPLL(pipe));
1436         udelay(150);
1437
1438         if (intel_wait_for_register(dev_priv,
1439                                     DPLL(pipe),
1440                                     DPLL_LOCK_VLV,
1441                                     DPLL_LOCK_VLV,
1442                                     1))
1443                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1444 }
1445
1446 static void vlv_enable_pll(struct intel_crtc *crtc,
1447                            const struct intel_crtc_state *pipe_config)
1448 {
1449         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1450         enum pipe pipe = crtc->pipe;
1451
1452         assert_pipe_disabled(dev_priv, pipe);
1453
1454         /* PLL is protected by panel, make sure we can write it */
1455         assert_panel_unlocked(dev_priv, pipe);
1456
1457         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1458                 _vlv_enable_pll(crtc, pipe_config);
1459
1460         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1461         POSTING_READ(DPLL_MD(pipe));
1462 }
1463
1464
1465 static void _chv_enable_pll(struct intel_crtc *crtc,
1466                             const struct intel_crtc_state *pipe_config)
1467 {
1468         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1469         enum pipe pipe = crtc->pipe;
1470         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1471         u32 tmp;
1472
1473         mutex_lock(&dev_priv->sb_lock);
1474
1475         /* Enable back the 10bit clock to display controller */
1476         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1477         tmp |= DPIO_DCLKP_EN;
1478         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1479
1480         mutex_unlock(&dev_priv->sb_lock);
1481
1482         /*
1483          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1484          */
1485         udelay(1);
1486
1487         /* Enable PLL */
1488         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1489
1490         /* Check PLL is locked */
1491         if (intel_wait_for_register(dev_priv,
1492                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1493                                     1))
1494                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1495 }
1496
1497 static void chv_enable_pll(struct intel_crtc *crtc,
1498                            const struct intel_crtc_state *pipe_config)
1499 {
1500         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1501         enum pipe pipe = crtc->pipe;
1502
1503         assert_pipe_disabled(dev_priv, pipe);
1504
1505         /* PLL is protected by panel, make sure we can write it */
1506         assert_panel_unlocked(dev_priv, pipe);
1507
1508         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1509                 _chv_enable_pll(crtc, pipe_config);
1510
1511         if (pipe != PIPE_A) {
1512                 /*
1513                  * WaPixelRepeatModeFixForC0:chv
1514                  *
1515                  * DPLLCMD is AWOL. Use chicken bits to propagate
1516                  * the value from DPLLBMD to either pipe B or C.
1517                  */
1518                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1519                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1520                 I915_WRITE(CBR4_VLV, 0);
1521                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1522
1523                 /*
1524                  * DPLLB VGA mode also seems to cause problems.
1525                  * We should always have it disabled.
1526                  */
1527                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1528         } else {
1529                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1530                 POSTING_READ(DPLL_MD(pipe));
1531         }
1532 }
1533
1534 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1535 {
1536         struct intel_crtc *crtc;
1537         int count = 0;
1538
1539         for_each_intel_crtc(&dev_priv->drm, crtc) {
1540                 count += crtc->base.state->active &&
1541                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1542         }
1543
1544         return count;
1545 }
1546
1547 static void i9xx_enable_pll(struct intel_crtc *crtc)
1548 {
1549         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1550         i915_reg_t reg = DPLL(crtc->pipe);
1551         u32 dpll = crtc->config->dpll_hw_state.dpll;
1552         int i;
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         for (i = 0; i < 3; i++) {
1600                 I915_WRITE(reg, dpll);
1601                 POSTING_READ(reg);
1602                 udelay(150); /* wait for warmup */
1603         }
1604 }
1605
1606 /**
1607  * i9xx_disable_pll - disable a PLL
1608  * @dev_priv: i915 private structure
1609  * @pipe: pipe PLL to disable
1610  *
1611  * Disable the PLL for @pipe, making sure the pipe is off first.
1612  *
1613  * Note!  This is for pre-ILK only.
1614  */
1615 static void i9xx_disable_pll(struct intel_crtc *crtc)
1616 {
1617         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1618         enum pipe pipe = crtc->pipe;
1619
1620         /* Disable DVO 2x clock on both PLLs if necessary */
1621         if (IS_I830(dev_priv) &&
1622             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1623             !intel_num_dvo_pipes(dev_priv)) {
1624                 I915_WRITE(DPLL(PIPE_B),
1625                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1626                 I915_WRITE(DPLL(PIPE_A),
1627                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1628         }
1629
1630         /* Don't disable pipe or pipe PLLs if needed */
1631         if (IS_I830(dev_priv))
1632                 return;
1633
1634         /* Make sure the pipe isn't still relying on us */
1635         assert_pipe_disabled(dev_priv, pipe);
1636
1637         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1638         POSTING_READ(DPLL(pipe));
1639 }
1640
1641 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1642 {
1643         u32 val;
1644
1645         /* Make sure the pipe isn't still relying on us */
1646         assert_pipe_disabled(dev_priv, pipe);
1647
1648         val = DPLL_INTEGRATED_REF_CLK_VLV |
1649                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1650         if (pipe != PIPE_A)
1651                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1652
1653         I915_WRITE(DPLL(pipe), val);
1654         POSTING_READ(DPLL(pipe));
1655 }
1656
1657 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1658 {
1659         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1660         u32 val;
1661
1662         /* Make sure the pipe isn't still relying on us */
1663         assert_pipe_disabled(dev_priv, pipe);
1664
1665         val = DPLL_SSC_REF_CLK_CHV |
1666                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1667         if (pipe != PIPE_A)
1668                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1669
1670         I915_WRITE(DPLL(pipe), val);
1671         POSTING_READ(DPLL(pipe));
1672
1673         mutex_lock(&dev_priv->sb_lock);
1674
1675         /* Disable 10bit clock to display controller */
1676         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1677         val &= ~DPIO_DCLKP_EN;
1678         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1679
1680         mutex_unlock(&dev_priv->sb_lock);
1681 }
1682
1683 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1684                          struct intel_digital_port *dport,
1685                          unsigned int expected_mask)
1686 {
1687         u32 port_mask;
1688         i915_reg_t dpll_reg;
1689
1690         switch (dport->port) {
1691         case PORT_B:
1692                 port_mask = DPLL_PORTB_READY_MASK;
1693                 dpll_reg = DPLL(0);
1694                 break;
1695         case PORT_C:
1696                 port_mask = DPLL_PORTC_READY_MASK;
1697                 dpll_reg = DPLL(0);
1698                 expected_mask <<= 4;
1699                 break;
1700         case PORT_D:
1701                 port_mask = DPLL_PORTD_READY_MASK;
1702                 dpll_reg = DPIO_PHY_STATUS;
1703                 break;
1704         default:
1705                 BUG();
1706         }
1707
1708         if (intel_wait_for_register(dev_priv,
1709                                     dpll_reg, port_mask, expected_mask,
1710                                     1000))
1711                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1712                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1713 }
1714
1715 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1716                                            enum pipe pipe)
1717 {
1718         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1719                                                                 pipe);
1720         i915_reg_t reg;
1721         uint32_t val, pipeconf_val;
1722
1723         /* Make sure PCH DPLL is enabled */
1724         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1725
1726         /* FDI must be feeding us bits for PCH ports */
1727         assert_fdi_tx_enabled(dev_priv, pipe);
1728         assert_fdi_rx_enabled(dev_priv, pipe);
1729
1730         if (HAS_PCH_CPT(dev_priv)) {
1731                 /* Workaround: Set the timing override bit before enabling the
1732                  * pch transcoder. */
1733                 reg = TRANS_CHICKEN2(pipe);
1734                 val = I915_READ(reg);
1735                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1736                 I915_WRITE(reg, val);
1737         }
1738
1739         reg = PCH_TRANSCONF(pipe);
1740         val = I915_READ(reg);
1741         pipeconf_val = I915_READ(PIPECONF(pipe));
1742
1743         if (HAS_PCH_IBX(dev_priv)) {
1744                 /*
1745                  * Make the BPC in transcoder be consistent with
1746                  * that in pipeconf reg. For HDMI we must use 8bpc
1747                  * here for both 8bpc and 12bpc.
1748                  */
1749                 val &= ~PIPECONF_BPC_MASK;
1750                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1751                         val |= PIPECONF_8BPC;
1752                 else
1753                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1754         }
1755
1756         val &= ~TRANS_INTERLACE_MASK;
1757         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1758                 if (HAS_PCH_IBX(dev_priv) &&
1759                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1760                         val |= TRANS_LEGACY_INTERLACED_ILK;
1761                 else
1762                         val |= TRANS_INTERLACED;
1763         else
1764                 val |= TRANS_PROGRESSIVE;
1765
1766         I915_WRITE(reg, val | TRANS_ENABLE);
1767         if (intel_wait_for_register(dev_priv,
1768                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1769                                     100))
1770                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1771 }
1772
1773 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1774                                       enum transcoder cpu_transcoder)
1775 {
1776         u32 val, pipeconf_val;
1777
1778         /* FDI must be feeding us bits for PCH ports */
1779         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1780         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1781
1782         /* Workaround: set timing override bit. */
1783         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1784         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1785         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1786
1787         val = TRANS_ENABLE;
1788         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1789
1790         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1791             PIPECONF_INTERLACED_ILK)
1792                 val |= TRANS_INTERLACED;
1793         else
1794                 val |= TRANS_PROGRESSIVE;
1795
1796         I915_WRITE(LPT_TRANSCONF, val);
1797         if (intel_wait_for_register(dev_priv,
1798                                     LPT_TRANSCONF,
1799                                     TRANS_STATE_ENABLE,
1800                                     TRANS_STATE_ENABLE,
1801                                     100))
1802                 DRM_ERROR("Failed to enable PCH transcoder\n");
1803 }
1804
1805 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1806                                             enum pipe pipe)
1807 {
1808         i915_reg_t reg;
1809         uint32_t val;
1810
1811         /* FDI relies on the transcoder */
1812         assert_fdi_tx_disabled(dev_priv, pipe);
1813         assert_fdi_rx_disabled(dev_priv, pipe);
1814
1815         /* Ports must be off as well */
1816         assert_pch_ports_disabled(dev_priv, pipe);
1817
1818         reg = PCH_TRANSCONF(pipe);
1819         val = I915_READ(reg);
1820         val &= ~TRANS_ENABLE;
1821         I915_WRITE(reg, val);
1822         /* wait for PCH transcoder off, transcoder state */
1823         if (intel_wait_for_register(dev_priv,
1824                                     reg, TRANS_STATE_ENABLE, 0,
1825                                     50))
1826                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1827
1828         if (HAS_PCH_CPT(dev_priv)) {
1829                 /* Workaround: Clear the timing override chicken bit again. */
1830                 reg = TRANS_CHICKEN2(pipe);
1831                 val = I915_READ(reg);
1832                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1833                 I915_WRITE(reg, val);
1834         }
1835 }
1836
1837 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1838 {
1839         u32 val;
1840
1841         val = I915_READ(LPT_TRANSCONF);
1842         val &= ~TRANS_ENABLE;
1843         I915_WRITE(LPT_TRANSCONF, val);
1844         /* wait for PCH transcoder off, transcoder state */
1845         if (intel_wait_for_register(dev_priv,
1846                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1847                                     50))
1848                 DRM_ERROR("Failed to disable PCH transcoder\n");
1849
1850         /* Workaround: clear timing override bit. */
1851         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1852         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1853         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1854 }
1855
1856 enum transcoder intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1857 {
1858         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1859
1860         WARN_ON(!crtc->config->has_pch_encoder);
1861
1862         if (HAS_PCH_LPT(dev_priv))
1863                 return TRANSCODER_A;
1864         else
1865                 return (enum transcoder) crtc->pipe;
1866 }
1867
1868 /**
1869  * intel_enable_pipe - enable a pipe, asserting requirements
1870  * @crtc: crtc responsible for the pipe
1871  *
1872  * Enable @crtc's pipe, making sure that various hardware specific requirements
1873  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1874  */
1875 static void intel_enable_pipe(struct intel_crtc *crtc)
1876 {
1877         struct drm_device *dev = crtc->base.dev;
1878         struct drm_i915_private *dev_priv = to_i915(dev);
1879         enum pipe pipe = crtc->pipe;
1880         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1881         i915_reg_t reg;
1882         u32 val;
1883
1884         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1885
1886         assert_planes_disabled(dev_priv, pipe);
1887         assert_cursor_disabled(dev_priv, pipe);
1888         assert_sprites_disabled(dev_priv, pipe);
1889
1890         /*
1891          * A pipe without a PLL won't actually be able to drive bits from
1892          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1893          * need the check.
1894          */
1895         if (HAS_GMCH_DISPLAY(dev_priv)) {
1896                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1897                         assert_dsi_pll_enabled(dev_priv);
1898                 else
1899                         assert_pll_enabled(dev_priv, pipe);
1900         } else {
1901                 if (crtc->config->has_pch_encoder) {
1902                         /* if driving the PCH, we need FDI enabled */
1903                         assert_fdi_rx_pll_enabled(dev_priv,
1904                                                   (enum pipe) intel_crtc_pch_transcoder(crtc));
1905                         assert_fdi_tx_pll_enabled(dev_priv,
1906                                                   (enum pipe) cpu_transcoder);
1907                 }
1908                 /* FIXME: assert CPU port conditions for SNB+ */
1909         }
1910
1911         reg = PIPECONF(cpu_transcoder);
1912         val = I915_READ(reg);
1913         if (val & PIPECONF_ENABLE) {
1914                 /* we keep both pipes enabled on 830 */
1915                 WARN_ON(!IS_I830(dev_priv));
1916                 return;
1917         }
1918
1919         I915_WRITE(reg, val | PIPECONF_ENABLE);
1920         POSTING_READ(reg);
1921
1922         /*
1923          * Until the pipe starts DSL will read as 0, which would cause
1924          * an apparent vblank timestamp jump, which messes up also the
1925          * frame count when it's derived from the timestamps. So let's
1926          * wait for the pipe to start properly before we call
1927          * drm_crtc_vblank_on()
1928          */
1929         if (dev->max_vblank_count == 0 &&
1930             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1931                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1932 }
1933
1934 /**
1935  * intel_disable_pipe - disable a pipe, asserting requirements
1936  * @crtc: crtc whose pipes is to be disabled
1937  *
1938  * Disable the pipe of @crtc, making sure that various hardware
1939  * specific requirements are met, if applicable, e.g. plane
1940  * disabled, panel fitter off, etc.
1941  *
1942  * Will wait until the pipe has shut down before returning.
1943  */
1944 static void intel_disable_pipe(struct intel_crtc *crtc)
1945 {
1946         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1947         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1948         enum pipe pipe = crtc->pipe;
1949         i915_reg_t reg;
1950         u32 val;
1951
1952         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1953
1954         /*
1955          * Make sure planes won't keep trying to pump pixels to us,
1956          * or we might hang the display.
1957          */
1958         assert_planes_disabled(dev_priv, pipe);
1959         assert_cursor_disabled(dev_priv, pipe);
1960         assert_sprites_disabled(dev_priv, pipe);
1961
1962         reg = PIPECONF(cpu_transcoder);
1963         val = I915_READ(reg);
1964         if ((val & PIPECONF_ENABLE) == 0)
1965                 return;
1966
1967         /*
1968          * Double wide has implications for planes
1969          * so best keep it disabled when not needed.
1970          */
1971         if (crtc->config->double_wide)
1972                 val &= ~PIPECONF_DOUBLE_WIDE;
1973
1974         /* Don't disable pipe or pipe PLLs if needed */
1975         if (!IS_I830(dev_priv))
1976                 val &= ~PIPECONF_ENABLE;
1977
1978         I915_WRITE(reg, val);
1979         if ((val & PIPECONF_ENABLE) == 0)
1980                 intel_wait_for_pipe_off(crtc);
1981 }
1982
1983 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1984 {
1985         return IS_GEN2(dev_priv) ? 2048 : 4096;
1986 }
1987
1988 static unsigned int
1989 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1990 {
1991         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1992         unsigned int cpp = fb->format->cpp[plane];
1993
1994         switch (fb->modifier) {
1995         case DRM_FORMAT_MOD_LINEAR:
1996                 return cpp;
1997         case I915_FORMAT_MOD_X_TILED:
1998                 if (IS_GEN2(dev_priv))
1999                         return 128;
2000                 else
2001                         return 512;
2002         case I915_FORMAT_MOD_Y_TILED:
2003                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2004                         return 128;
2005                 else
2006                         return 512;
2007         case I915_FORMAT_MOD_Yf_TILED:
2008                 switch (cpp) {
2009                 case 1:
2010                         return 64;
2011                 case 2:
2012                 case 4:
2013                         return 128;
2014                 case 8:
2015                 case 16:
2016                         return 256;
2017                 default:
2018                         MISSING_CASE(cpp);
2019                         return cpp;
2020                 }
2021                 break;
2022         default:
2023                 MISSING_CASE(fb->modifier);
2024                 return cpp;
2025         }
2026 }
2027
2028 static unsigned int
2029 intel_tile_height(const struct drm_framebuffer *fb, int plane)
2030 {
2031         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
2032                 return 1;
2033         else
2034                 return intel_tile_size(to_i915(fb->dev)) /
2035                         intel_tile_width_bytes(fb, plane);
2036 }
2037
2038 /* Return the tile dimensions in pixel units */
2039 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
2040                             unsigned int *tile_width,
2041                             unsigned int *tile_height)
2042 {
2043         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
2044         unsigned int cpp = fb->format->cpp[plane];
2045
2046         *tile_width = tile_width_bytes / cpp;
2047         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
2048 }
2049
2050 unsigned int
2051 intel_fb_align_height(const struct drm_framebuffer *fb,
2052                       int plane, unsigned int height)
2053 {
2054         unsigned int tile_height = intel_tile_height(fb, plane);
2055
2056         return ALIGN(height, tile_height);
2057 }
2058
2059 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2060 {
2061         unsigned int size = 0;
2062         int i;
2063
2064         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2065                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2066
2067         return size;
2068 }
2069
2070 static void
2071 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2072                         const struct drm_framebuffer *fb,
2073                         unsigned int rotation)
2074 {
2075         view->type = I915_GGTT_VIEW_NORMAL;
2076         if (drm_rotation_90_or_270(rotation)) {
2077                 view->type = I915_GGTT_VIEW_ROTATED;
2078                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2079         }
2080 }
2081
2082 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2083 {
2084         if (IS_I830(dev_priv))
2085                 return 16 * 1024;
2086         else if (IS_I85X(dev_priv))
2087                 return 256;
2088         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2089                 return 32;
2090         else
2091                 return 4 * 1024;
2092 }
2093
2094 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2095 {
2096         if (INTEL_INFO(dev_priv)->gen >= 9)
2097                 return 256 * 1024;
2098         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2099                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2100                 return 128 * 1024;
2101         else if (INTEL_INFO(dev_priv)->gen >= 4)
2102                 return 4 * 1024;
2103         else
2104                 return 0;
2105 }
2106
2107 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2108                                          int plane)
2109 {
2110         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2111
2112         /* AUX_DIST needs only 4K alignment */
2113         if (fb->format->format == DRM_FORMAT_NV12 && plane == 1)
2114                 return 4096;
2115
2116         switch (fb->modifier) {
2117         case DRM_FORMAT_MOD_LINEAR:
2118                 return intel_linear_alignment(dev_priv);
2119         case I915_FORMAT_MOD_X_TILED:
2120                 if (INTEL_GEN(dev_priv) >= 9)
2121                         return 256 * 1024;
2122                 return 0;
2123         case I915_FORMAT_MOD_Y_TILED:
2124         case I915_FORMAT_MOD_Yf_TILED:
2125                 return 1 * 1024 * 1024;
2126         default:
2127                 MISSING_CASE(fb->modifier);
2128                 return 0;
2129         }
2130 }
2131
2132 struct i915_vma *
2133 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2134 {
2135         struct drm_device *dev = fb->dev;
2136         struct drm_i915_private *dev_priv = to_i915(dev);
2137         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2138         struct i915_ggtt_view view;
2139         struct i915_vma *vma;
2140         u32 alignment;
2141
2142         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2143
2144         alignment = intel_surf_alignment(fb, 0);
2145
2146         intel_fill_fb_ggtt_view(&view, fb, rotation);
2147
2148         /* Note that the w/a also requires 64 PTE of padding following the
2149          * bo. We currently fill all unused PTE with the shadow page and so
2150          * we should always have valid PTE following the scanout preventing
2151          * the VT-d warning.
2152          */
2153         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2154                 alignment = 256 * 1024;
2155
2156         /*
2157          * Global gtt pte registers are special registers which actually forward
2158          * writes to a chunk of system memory. Which means that there is no risk
2159          * that the register values disappear as soon as we call
2160          * intel_runtime_pm_put(), so it is correct to wrap only the
2161          * pin/unpin/fence and not more.
2162          */
2163         intel_runtime_pm_get(dev_priv);
2164
2165         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2166         if (IS_ERR(vma))
2167                 goto err;
2168
2169         if (i915_vma_is_map_and_fenceable(vma)) {
2170                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2171                  * fence, whereas 965+ only requires a fence if using
2172                  * framebuffer compression.  For simplicity, we always, when
2173                  * possible, install a fence as the cost is not that onerous.
2174                  *
2175                  * If we fail to fence the tiled scanout, then either the
2176                  * modeset will reject the change (which is highly unlikely as
2177                  * the affected systems, all but one, do not have unmappable
2178                  * space) or we will not be able to enable full powersaving
2179                  * techniques (also likely not to apply due to various limits
2180                  * FBC and the like impose on the size of the buffer, which
2181                  * presumably we violated anyway with this unmappable buffer).
2182                  * Anyway, it is presumably better to stumble onwards with
2183                  * something and try to run the system in a "less than optimal"
2184                  * mode that matches the user configuration.
2185                  */
2186                 if (i915_vma_get_fence(vma) == 0)
2187                         i915_vma_pin_fence(vma);
2188         }
2189
2190         i915_vma_get(vma);
2191 err:
2192         intel_runtime_pm_put(dev_priv);
2193         return vma;
2194 }
2195
2196 void intel_unpin_fb_vma(struct i915_vma *vma)
2197 {
2198         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2199
2200         i915_vma_unpin_fence(vma);
2201         i915_gem_object_unpin_from_display_plane(vma);
2202         i915_vma_put(vma);
2203 }
2204
2205 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2206                           unsigned int rotation)
2207 {
2208         if (drm_rotation_90_or_270(rotation))
2209                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2210         else
2211                 return fb->pitches[plane];
2212 }
2213
2214 /*
2215  * Convert the x/y offsets into a linear offset.
2216  * Only valid with 0/180 degree rotation, which is fine since linear
2217  * offset is only used with linear buffers on pre-hsw and tiled buffers
2218  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2219  */
2220 u32 intel_fb_xy_to_linear(int x, int y,
2221                           const struct intel_plane_state *state,
2222                           int plane)
2223 {
2224         const struct drm_framebuffer *fb = state->base.fb;
2225         unsigned int cpp = fb->format->cpp[plane];
2226         unsigned int pitch = fb->pitches[plane];
2227
2228         return y * pitch + x * cpp;
2229 }
2230
2231 /*
2232  * Add the x/y offsets derived from fb->offsets[] to the user
2233  * specified plane src x/y offsets. The resulting x/y offsets
2234  * specify the start of scanout from the beginning of the gtt mapping.
2235  */
2236 void intel_add_fb_offsets(int *x, int *y,
2237                           const struct intel_plane_state *state,
2238                           int plane)
2239
2240 {
2241         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2242         unsigned int rotation = state->base.rotation;
2243
2244         if (drm_rotation_90_or_270(rotation)) {
2245                 *x += intel_fb->rotated[plane].x;
2246                 *y += intel_fb->rotated[plane].y;
2247         } else {
2248                 *x += intel_fb->normal[plane].x;
2249                 *y += intel_fb->normal[plane].y;
2250         }
2251 }
2252
2253 /*
2254  * Input tile dimensions and pitch must already be
2255  * rotated to match x and y, and in pixel units.
2256  */
2257 static u32 _intel_adjust_tile_offset(int *x, int *y,
2258                                      unsigned int tile_width,
2259                                      unsigned int tile_height,
2260                                      unsigned int tile_size,
2261                                      unsigned int pitch_tiles,
2262                                      u32 old_offset,
2263                                      u32 new_offset)
2264 {
2265         unsigned int pitch_pixels = pitch_tiles * tile_width;
2266         unsigned int tiles;
2267
2268         WARN_ON(old_offset & (tile_size - 1));
2269         WARN_ON(new_offset & (tile_size - 1));
2270         WARN_ON(new_offset > old_offset);
2271
2272         tiles = (old_offset - new_offset) / tile_size;
2273
2274         *y += tiles / pitch_tiles * tile_height;
2275         *x += tiles % pitch_tiles * tile_width;
2276
2277         /* minimize x in case it got needlessly big */
2278         *y += *x / pitch_pixels * tile_height;
2279         *x %= pitch_pixels;
2280
2281         return new_offset;
2282 }
2283
2284 /*
2285  * Adjust the tile offset by moving the difference into
2286  * the x/y offsets.
2287  */
2288 static u32 intel_adjust_tile_offset(int *x, int *y,
2289                                     const struct intel_plane_state *state, int plane,
2290                                     u32 old_offset, u32 new_offset)
2291 {
2292         const struct drm_i915_private *dev_priv = to_i915(state->base.plane->dev);
2293         const struct drm_framebuffer *fb = state->base.fb;
2294         unsigned int cpp = fb->format->cpp[plane];
2295         unsigned int rotation = state->base.rotation;
2296         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2297
2298         WARN_ON(new_offset > old_offset);
2299
2300         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2301                 unsigned int tile_size, tile_width, tile_height;
2302                 unsigned int pitch_tiles;
2303
2304                 tile_size = intel_tile_size(dev_priv);
2305                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2306
2307                 if (drm_rotation_90_or_270(rotation)) {
2308                         pitch_tiles = pitch / tile_height;
2309                         swap(tile_width, tile_height);
2310                 } else {
2311                         pitch_tiles = pitch / (tile_width * cpp);
2312                 }
2313
2314                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2315                                           tile_size, pitch_tiles,
2316                                           old_offset, new_offset);
2317         } else {
2318                 old_offset += *y * pitch + *x * cpp;
2319
2320                 *y = (old_offset - new_offset) / pitch;
2321                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2322         }
2323
2324         return new_offset;
2325 }
2326
2327 /*
2328  * Computes the linear offset to the base tile and adjusts
2329  * x, y. bytes per pixel is assumed to be a power-of-two.
2330  *
2331  * In the 90/270 rotated case, x and y are assumed
2332  * to be already rotated to match the rotated GTT view, and
2333  * pitch is the tile_height aligned framebuffer height.
2334  *
2335  * This function is used when computing the derived information
2336  * under intel_framebuffer, so using any of that information
2337  * here is not allowed. Anything under drm_framebuffer can be
2338  * used. This is why the user has to pass in the pitch since it
2339  * is specified in the rotated orientation.
2340  */
2341 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2342                                       int *x, int *y,
2343                                       const struct drm_framebuffer *fb, int plane,
2344                                       unsigned int pitch,
2345                                       unsigned int rotation,
2346                                       u32 alignment)
2347 {
2348         uint64_t fb_modifier = fb->modifier;
2349         unsigned int cpp = fb->format->cpp[plane];
2350         u32 offset, offset_aligned;
2351
2352         if (alignment)
2353                 alignment--;
2354
2355         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2356                 unsigned int tile_size, tile_width, tile_height;
2357                 unsigned int tile_rows, tiles, pitch_tiles;
2358
2359                 tile_size = intel_tile_size(dev_priv);
2360                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2361
2362                 if (drm_rotation_90_or_270(rotation)) {
2363                         pitch_tiles = pitch / tile_height;
2364                         swap(tile_width, tile_height);
2365                 } else {
2366                         pitch_tiles = pitch / (tile_width * cpp);
2367                 }
2368
2369                 tile_rows = *y / tile_height;
2370                 *y %= tile_height;
2371
2372                 tiles = *x / tile_width;
2373                 *x %= tile_width;
2374
2375                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2376                 offset_aligned = offset & ~alignment;
2377
2378                 _intel_adjust_tile_offset(x, y, tile_width, tile_height,
2379                                           tile_size, pitch_tiles,
2380                                           offset, offset_aligned);
2381         } else {
2382                 offset = *y * pitch + *x * cpp;
2383                 offset_aligned = offset & ~alignment;
2384
2385                 *y = (offset & alignment) / pitch;
2386                 *x = ((offset & alignment) - *y * pitch) / cpp;
2387         }
2388
2389         return offset_aligned;
2390 }
2391
2392 u32 intel_compute_tile_offset(int *x, int *y,
2393                               const struct intel_plane_state *state,
2394                               int plane)
2395 {
2396         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2397         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2398         const struct drm_framebuffer *fb = state->base.fb;
2399         unsigned int rotation = state->base.rotation;
2400         int pitch = intel_fb_pitch(fb, plane, rotation);
2401         u32 alignment;
2402
2403         if (intel_plane->id == PLANE_CURSOR)
2404                 alignment = intel_cursor_alignment(dev_priv);
2405         else
2406                 alignment = intel_surf_alignment(fb, plane);
2407
2408         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2409                                           rotation, alignment);
2410 }
2411
2412 /* Convert the fb->offset[] linear offset into x/y offsets */
2413 static void intel_fb_offset_to_xy(int *x, int *y,
2414                                   const struct drm_framebuffer *fb, int plane)
2415 {
2416         unsigned int cpp = fb->format->cpp[plane];
2417         unsigned int pitch = fb->pitches[plane];
2418         u32 linear_offset = fb->offsets[plane];
2419
2420         *y = linear_offset / pitch;
2421         *x = linear_offset % pitch / cpp;
2422 }
2423
2424 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2425 {
2426         switch (fb_modifier) {
2427         case I915_FORMAT_MOD_X_TILED:
2428                 return I915_TILING_X;
2429         case I915_FORMAT_MOD_Y_TILED:
2430                 return I915_TILING_Y;
2431         default:
2432                 return I915_TILING_NONE;
2433         }
2434 }
2435
2436 static int
2437 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2438                    struct drm_framebuffer *fb)
2439 {
2440         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2441         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2442         u32 gtt_offset_rotated = 0;
2443         unsigned int max_size = 0;
2444         int i, num_planes = fb->format->num_planes;
2445         unsigned int tile_size = intel_tile_size(dev_priv);
2446
2447         for (i = 0; i < num_planes; i++) {
2448                 unsigned int width, height;
2449                 unsigned int cpp, size;
2450                 u32 offset;
2451                 int x, y;
2452
2453                 cpp = fb->format->cpp[i];
2454                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2455                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2456
2457                 intel_fb_offset_to_xy(&x, &y, fb, i);
2458
2459                 /*
2460                  * The fence (if used) is aligned to the start of the object
2461                  * so having the framebuffer wrap around across the edge of the
2462                  * fenced region doesn't really work. We have no API to configure
2463                  * the fence start offset within the object (nor could we probably
2464                  * on gen2/3). So it's just easier if we just require that the
2465                  * fb layout agrees with the fence layout. We already check that the
2466                  * fb stride matches the fence stride elsewhere.
2467                  */
2468                 if (i915_gem_object_is_tiled(intel_fb->obj) &&
2469                     (x + width) * cpp > fb->pitches[i]) {
2470                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2471                                       i, fb->offsets[i]);
2472                         return -EINVAL;
2473                 }
2474
2475                 /*
2476                  * First pixel of the framebuffer from
2477                  * the start of the normal gtt mapping.
2478                  */
2479                 intel_fb->normal[i].x = x;
2480                 intel_fb->normal[i].y = y;
2481
2482                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2483                                                     fb, i, fb->pitches[i],
2484                                                     DRM_MODE_ROTATE_0, tile_size);
2485                 offset /= tile_size;
2486
2487                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2488                         unsigned int tile_width, tile_height;
2489                         unsigned int pitch_tiles;
2490                         struct drm_rect r;
2491
2492                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2493
2494                         rot_info->plane[i].offset = offset;
2495                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2496                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2497                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2498
2499                         intel_fb->rotated[i].pitch =
2500                                 rot_info->plane[i].height * tile_height;
2501
2502                         /* how many tiles does this plane need */
2503                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2504                         /*
2505                          * If the plane isn't horizontally tile aligned,
2506                          * we need one more tile.
2507                          */
2508                         if (x != 0)
2509                                 size++;
2510
2511                         /* rotate the x/y offsets to match the GTT view */
2512                         r.x1 = x;
2513                         r.y1 = y;
2514                         r.x2 = x + width;
2515                         r.y2 = y + height;
2516                         drm_rect_rotate(&r,
2517                                         rot_info->plane[i].width * tile_width,
2518                                         rot_info->plane[i].height * tile_height,
2519                                         DRM_MODE_ROTATE_270);
2520                         x = r.x1;
2521                         y = r.y1;
2522
2523                         /* rotate the tile dimensions to match the GTT view */
2524                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2525                         swap(tile_width, tile_height);
2526
2527                         /*
2528                          * We only keep the x/y offsets, so push all of the
2529                          * gtt offset into the x/y offsets.
2530                          */
2531                         _intel_adjust_tile_offset(&x, &y,
2532                                                   tile_width, tile_height,
2533                                                   tile_size, pitch_tiles,
2534                                                   gtt_offset_rotated * tile_size, 0);
2535
2536                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2537
2538                         /*
2539                          * First pixel of the framebuffer from
2540                          * the start of the rotated gtt mapping.
2541                          */
2542                         intel_fb->rotated[i].x = x;
2543                         intel_fb->rotated[i].y = y;
2544                 } else {
2545                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2546                                             x * cpp, tile_size);
2547                 }
2548
2549                 /* how many tiles in total needed in the bo */
2550                 max_size = max(max_size, offset + size);
2551         }
2552
2553         if (max_size * tile_size > intel_fb->obj->base.size) {
2554                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2555                               max_size * tile_size, intel_fb->obj->base.size);
2556                 return -EINVAL;
2557         }
2558
2559         return 0;
2560 }
2561
2562 static int i9xx_format_to_fourcc(int format)
2563 {
2564         switch (format) {
2565         case DISPPLANE_8BPP:
2566                 return DRM_FORMAT_C8;
2567         case DISPPLANE_BGRX555:
2568                 return DRM_FORMAT_XRGB1555;
2569         case DISPPLANE_BGRX565:
2570                 return DRM_FORMAT_RGB565;
2571         default:
2572         case DISPPLANE_BGRX888:
2573                 return DRM_FORMAT_XRGB8888;
2574         case DISPPLANE_RGBX888:
2575                 return DRM_FORMAT_XBGR8888;
2576         case DISPPLANE_BGRX101010:
2577                 return DRM_FORMAT_XRGB2101010;
2578         case DISPPLANE_RGBX101010:
2579                 return DRM_FORMAT_XBGR2101010;
2580         }
2581 }
2582
2583 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2584 {
2585         switch (format) {
2586         case PLANE_CTL_FORMAT_RGB_565:
2587                 return DRM_FORMAT_RGB565;
2588         default:
2589         case PLANE_CTL_FORMAT_XRGB_8888:
2590                 if (rgb_order) {
2591                         if (alpha)
2592                                 return DRM_FORMAT_ABGR8888;
2593                         else
2594                                 return DRM_FORMAT_XBGR8888;
2595                 } else {
2596                         if (alpha)
2597                                 return DRM_FORMAT_ARGB8888;
2598                         else
2599                                 return DRM_FORMAT_XRGB8888;
2600                 }
2601         case PLANE_CTL_FORMAT_XRGB_2101010:
2602                 if (rgb_order)
2603                         return DRM_FORMAT_XBGR2101010;
2604                 else
2605                         return DRM_FORMAT_XRGB2101010;
2606         }
2607 }
2608
2609 static bool
2610 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2611                               struct intel_initial_plane_config *plane_config)
2612 {
2613         struct drm_device *dev = crtc->base.dev;
2614         struct drm_i915_private *dev_priv = to_i915(dev);
2615         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2616         struct drm_i915_gem_object *obj = NULL;
2617         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2618         struct drm_framebuffer *fb = &plane_config->fb->base;
2619         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2620         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2621                                     PAGE_SIZE);
2622
2623         size_aligned -= base_aligned;
2624
2625         if (plane_config->size == 0)
2626                 return false;
2627
2628         /* If the FB is too big, just don't use it since fbdev is not very
2629          * important and we should probably use that space with FBC or other
2630          * features. */
2631         if (size_aligned * 2 > ggtt->stolen_usable_size)
2632                 return false;
2633
2634         mutex_lock(&dev->struct_mutex);
2635         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2636                                                              base_aligned,
2637                                                              base_aligned,
2638                                                              size_aligned);
2639         mutex_unlock(&dev->struct_mutex);
2640         if (!obj)
2641                 return false;
2642
2643         if (plane_config->tiling == I915_TILING_X)
2644                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2645
2646         mode_cmd.pixel_format = fb->format->format;
2647         mode_cmd.width = fb->width;
2648         mode_cmd.height = fb->height;
2649         mode_cmd.pitches[0] = fb->pitches[0];
2650         mode_cmd.modifier[0] = fb->modifier;
2651         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2652
2653         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2654                 DRM_DEBUG_KMS("intel fb init failed\n");
2655                 goto out_unref_obj;
2656         }
2657
2658
2659         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2660         return true;
2661
2662 out_unref_obj:
2663         i915_gem_object_put(obj);
2664         return false;
2665 }
2666
2667 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2668 static void
2669 update_state_fb(struct drm_plane *plane)
2670 {
2671         if (plane->fb == plane->state->fb)
2672                 return;
2673
2674         if (plane->state->fb)
2675                 drm_framebuffer_unreference(plane->state->fb);
2676         plane->state->fb = plane->fb;
2677         if (plane->state->fb)
2678                 drm_framebuffer_reference(plane->state->fb);
2679 }
2680
2681 static void
2682 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2683                         struct intel_plane_state *plane_state,
2684                         bool visible)
2685 {
2686         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2687
2688         plane_state->base.visible = visible;
2689
2690         /* FIXME pre-g4x don't work like this */
2691         if (visible) {
2692                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2693                 crtc_state->active_planes |= BIT(plane->id);
2694         } else {
2695                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2696                 crtc_state->active_planes &= ~BIT(plane->id);
2697         }
2698
2699         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2700                       crtc_state->base.crtc->name,
2701                       crtc_state->active_planes);
2702 }
2703
2704 static void
2705 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2706                              struct intel_initial_plane_config *plane_config)
2707 {
2708         struct drm_device *dev = intel_crtc->base.dev;
2709         struct drm_i915_private *dev_priv = to_i915(dev);
2710         struct drm_crtc *c;
2711         struct drm_i915_gem_object *obj;
2712         struct drm_plane *primary = intel_crtc->base.primary;
2713         struct drm_plane_state *plane_state = primary->state;
2714         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2715         struct intel_plane *intel_plane = to_intel_plane(primary);
2716         struct intel_plane_state *intel_state =
2717                 to_intel_plane_state(plane_state);
2718         struct drm_framebuffer *fb;
2719
2720         if (!plane_config->fb)
2721                 return;
2722
2723         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2724                 fb = &plane_config->fb->base;
2725                 goto valid_fb;
2726         }
2727
2728         kfree(plane_config->fb);
2729
2730         /*
2731          * Failed to alloc the obj, check to see if we should share
2732          * an fb with another CRTC instead
2733          */
2734         for_each_crtc(dev, c) {
2735                 struct intel_plane_state *state;
2736
2737                 if (c == &intel_crtc->base)
2738                         continue;
2739
2740                 if (!to_intel_crtc(c)->active)
2741                         continue;
2742
2743                 state = to_intel_plane_state(c->primary->state);
2744                 if (!state->vma)
2745                         continue;
2746
2747                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2748                         fb = c->primary->fb;
2749                         drm_framebuffer_reference(fb);
2750                         goto valid_fb;
2751                 }
2752         }
2753
2754         /*
2755          * We've failed to reconstruct the BIOS FB.  Current display state
2756          * indicates that the primary plane is visible, but has a NULL FB,
2757          * which will lead to problems later if we don't fix it up.  The
2758          * simplest solution is to just disable the primary plane now and
2759          * pretend the BIOS never had it enabled.
2760          */
2761         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2762                                 to_intel_plane_state(plane_state),
2763                                 false);
2764         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2765         trace_intel_disable_plane(primary, intel_crtc);
2766         intel_plane->disable_plane(intel_plane, intel_crtc);
2767
2768         return;
2769
2770 valid_fb:
2771         mutex_lock(&dev->struct_mutex);
2772         intel_state->vma =
2773                 intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
2774         mutex_unlock(&dev->struct_mutex);
2775         if (IS_ERR(intel_state->vma)) {
2776                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2777                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2778
2779                 intel_state->vma = NULL;
2780                 drm_framebuffer_unreference(fb);
2781                 return;
2782         }
2783
2784         plane_state->src_x = 0;
2785         plane_state->src_y = 0;
2786         plane_state->src_w = fb->width << 16;
2787         plane_state->src_h = fb->height << 16;
2788
2789         plane_state->crtc_x = 0;
2790         plane_state->crtc_y = 0;
2791         plane_state->crtc_w = fb->width;
2792         plane_state->crtc_h = fb->height;
2793
2794         intel_state->base.src = drm_plane_state_src(plane_state);
2795         intel_state->base.dst = drm_plane_state_dest(plane_state);
2796
2797         obj = intel_fb_obj(fb);
2798         if (i915_gem_object_is_tiled(obj))
2799                 dev_priv->preserve_bios_swizzle = true;
2800
2801         drm_framebuffer_reference(fb);
2802         primary->fb = primary->state->fb = fb;
2803         primary->crtc = primary->state->crtc = &intel_crtc->base;
2804
2805         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2806                                 to_intel_plane_state(plane_state),
2807                                 true);
2808
2809         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2810                   &obj->frontbuffer_bits);
2811 }
2812
2813 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2814                                unsigned int rotation)
2815 {
2816         int cpp = fb->format->cpp[plane];
2817
2818         switch (fb->modifier) {
2819         case DRM_FORMAT_MOD_LINEAR:
2820         case I915_FORMAT_MOD_X_TILED:
2821                 switch (cpp) {
2822                 case 8:
2823                         return 4096;
2824                 case 4:
2825                 case 2:
2826                 case 1:
2827                         return 8192;
2828                 default:
2829                         MISSING_CASE(cpp);
2830                         break;
2831                 }
2832                 break;
2833         case I915_FORMAT_MOD_Y_TILED:
2834         case I915_FORMAT_MOD_Yf_TILED:
2835                 switch (cpp) {
2836                 case 8:
2837                         return 2048;
2838                 case 4:
2839                         return 4096;
2840                 case 2:
2841                 case 1:
2842                         return 8192;
2843                 default:
2844                         MISSING_CASE(cpp);
2845                         break;
2846                 }
2847                 break;
2848         default:
2849                 MISSING_CASE(fb->modifier);
2850         }
2851
2852         return 2048;
2853 }
2854
2855 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2856 {
2857         const struct drm_framebuffer *fb = plane_state->base.fb;
2858         unsigned int rotation = plane_state->base.rotation;
2859         int x = plane_state->base.src.x1 >> 16;
2860         int y = plane_state->base.src.y1 >> 16;
2861         int w = drm_rect_width(&plane_state->base.src) >> 16;
2862         int h = drm_rect_height(&plane_state->base.src) >> 16;
2863         int max_width = skl_max_plane_width(fb, 0, rotation);
2864         int max_height = 4096;
2865         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2866
2867         if (w > max_width || h > max_height) {
2868                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2869                               w, h, max_width, max_height);
2870                 return -EINVAL;
2871         }
2872
2873         intel_add_fb_offsets(&x, &y, plane_state, 0);
2874         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2875         alignment = intel_surf_alignment(fb, 0);
2876
2877         /*
2878          * AUX surface offset is specified as the distance from the
2879          * main surface offset, and it must be non-negative. Make
2880          * sure that is what we will get.
2881          */
2882         if (offset > aux_offset)
2883                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2884                                                   offset, aux_offset & ~(alignment - 1));
2885
2886         /*
2887          * When using an X-tiled surface, the plane blows up
2888          * if the x offset + width exceed the stride.
2889          *
2890          * TODO: linear and Y-tiled seem fine, Yf untested,
2891          */
2892         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
2893                 int cpp = fb->format->cpp[0];
2894
2895                 while ((x + w) * cpp > fb->pitches[0]) {
2896                         if (offset == 0) {
2897                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset\n");
2898                                 return -EINVAL;
2899                         }
2900
2901                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2902                                                           offset, offset - alignment);
2903                 }
2904         }
2905
2906         plane_state->main.offset = offset;
2907         plane_state->main.x = x;
2908         plane_state->main.y = y;
2909
2910         return 0;
2911 }
2912
2913 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2914 {
2915         const struct drm_framebuffer *fb = plane_state->base.fb;
2916         unsigned int rotation = plane_state->base.rotation;
2917         int max_width = skl_max_plane_width(fb, 1, rotation);
2918         int max_height = 4096;
2919         int x = plane_state->base.src.x1 >> 17;
2920         int y = plane_state->base.src.y1 >> 17;
2921         int w = drm_rect_width(&plane_state->base.src) >> 17;
2922         int h = drm_rect_height(&plane_state->base.src) >> 17;
2923         u32 offset;
2924
2925         intel_add_fb_offsets(&x, &y, plane_state, 1);
2926         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
2927
2928         /* FIXME not quite sure how/if these apply to the chroma plane */
2929         if (w > max_width || h > max_height) {
2930                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
2931                               w, h, max_width, max_height);
2932                 return -EINVAL;
2933         }
2934
2935         plane_state->aux.offset = offset;
2936         plane_state->aux.x = x;
2937         plane_state->aux.y = y;
2938
2939         return 0;
2940 }
2941
2942 int skl_check_plane_surface(struct intel_plane_state *plane_state)
2943 {
2944         const struct drm_framebuffer *fb = plane_state->base.fb;
2945         unsigned int rotation = plane_state->base.rotation;
2946         int ret;
2947
2948         if (!plane_state->base.visible)
2949                 return 0;
2950
2951         /* Rotate src coordinates to match rotated GTT view */
2952         if (drm_rotation_90_or_270(rotation))
2953                 drm_rect_rotate(&plane_state->base.src,
2954                                 fb->width << 16, fb->height << 16,
2955                                 DRM_MODE_ROTATE_270);
2956
2957         /*
2958          * Handle the AUX surface first since
2959          * the main surface setup depends on it.
2960          */
2961         if (fb->format->format == DRM_FORMAT_NV12) {
2962                 ret = skl_check_nv12_aux_surface(plane_state);
2963                 if (ret)
2964                         return ret;
2965         } else {
2966                 plane_state->aux.offset = ~0xfff;
2967                 plane_state->aux.x = 0;
2968                 plane_state->aux.y = 0;
2969         }
2970
2971         ret = skl_check_main_surface(plane_state);
2972         if (ret)
2973                 return ret;
2974
2975         return 0;
2976 }
2977
2978 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
2979                           const struct intel_plane_state *plane_state)
2980 {
2981         struct drm_i915_private *dev_priv =
2982                 to_i915(plane_state->base.plane->dev);
2983         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
2984         const struct drm_framebuffer *fb = plane_state->base.fb;
2985         unsigned int rotation = plane_state->base.rotation;
2986         u32 dspcntr;
2987
2988         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
2989
2990         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
2991             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
2992                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2993
2994         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
2995                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2996
2997         if (INTEL_GEN(dev_priv) < 4)
2998                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
2999
3000         switch (fb->format->format) {
3001         case DRM_FORMAT_C8:
3002                 dspcntr |= DISPPLANE_8BPP;
3003                 break;
3004         case DRM_FORMAT_XRGB1555:
3005                 dspcntr |= DISPPLANE_BGRX555;
3006                 break;
3007         case DRM_FORMAT_RGB565:
3008                 dspcntr |= DISPPLANE_BGRX565;
3009                 break;
3010         case DRM_FORMAT_XRGB8888:
3011                 dspcntr |= DISPPLANE_BGRX888;
3012                 break;
3013         case DRM_FORMAT_XBGR8888:
3014                 dspcntr |= DISPPLANE_RGBX888;
3015                 break;
3016         case DRM_FORMAT_XRGB2101010:
3017                 dspcntr |= DISPPLANE_BGRX101010;
3018                 break;
3019         case DRM_FORMAT_XBGR2101010:
3020                 dspcntr |= DISPPLANE_RGBX101010;
3021                 break;
3022         default:
3023                 MISSING_CASE(fb->format->format);
3024                 return 0;
3025         }
3026
3027         if (INTEL_GEN(dev_priv) >= 4 &&
3028             fb->modifier == I915_FORMAT_MOD_X_TILED)
3029                 dspcntr |= DISPPLANE_TILED;
3030
3031         if (rotation & DRM_MODE_ROTATE_180)
3032                 dspcntr |= DISPPLANE_ROTATE_180;
3033
3034         if (rotation & DRM_MODE_REFLECT_X)
3035                 dspcntr |= DISPPLANE_MIRROR;
3036
3037         return dspcntr;
3038 }
3039
3040 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3041 {
3042         struct drm_i915_private *dev_priv =
3043                 to_i915(plane_state->base.plane->dev);
3044         int src_x = plane_state->base.src.x1 >> 16;
3045         int src_y = plane_state->base.src.y1 >> 16;
3046         u32 offset;
3047
3048         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3049
3050         if (INTEL_GEN(dev_priv) >= 4)
3051                 offset = intel_compute_tile_offset(&src_x, &src_y,
3052                                                    plane_state, 0);
3053         else
3054                 offset = 0;
3055
3056         /* HSW/BDW do this automagically in hardware */
3057         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3058                 unsigned int rotation = plane_state->base.rotation;
3059                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3060                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3061
3062                 if (rotation & DRM_MODE_ROTATE_180) {
3063                         src_x += src_w - 1;
3064                         src_y += src_h - 1;
3065                 } else if (rotation & DRM_MODE_REFLECT_X) {
3066                         src_x += src_w - 1;
3067                 }
3068         }
3069
3070         plane_state->main.offset = offset;
3071         plane_state->main.x = src_x;
3072         plane_state->main.y = src_y;
3073
3074         return 0;
3075 }
3076
3077 static void i9xx_update_primary_plane(struct intel_plane *primary,
3078                                       const struct intel_crtc_state *crtc_state,
3079                                       const struct intel_plane_state *plane_state)
3080 {
3081         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3082         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3083         const struct drm_framebuffer *fb = plane_state->base.fb;
3084         enum plane plane = primary->plane;
3085         u32 linear_offset;
3086         u32 dspcntr = plane_state->ctl;
3087         i915_reg_t reg = DSPCNTR(plane);
3088         int x = plane_state->main.x;
3089         int y = plane_state->main.y;
3090         unsigned long irqflags;
3091
3092         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3093
3094         if (INTEL_GEN(dev_priv) >= 4)
3095                 crtc->dspaddr_offset = plane_state->main.offset;
3096         else
3097                 crtc->dspaddr_offset = linear_offset;
3098
3099         crtc->adjusted_x = x;
3100         crtc->adjusted_y = y;
3101
3102         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3103
3104         if (INTEL_GEN(dev_priv) < 4) {
3105                 /* pipesrc and dspsize control the size that is scaled from,
3106                  * which should always be the user's requested size.
3107                  */
3108                 I915_WRITE_FW(DSPSIZE(plane),
3109                               ((crtc_state->pipe_src_h - 1) << 16) |
3110                               (crtc_state->pipe_src_w - 1));
3111                 I915_WRITE_FW(DSPPOS(plane), 0);
3112         } else if (IS_CHERRYVIEW(dev_priv) && plane == PLANE_B) {
3113                 I915_WRITE_FW(PRIMSIZE(plane),
3114                               ((crtc_state->pipe_src_h - 1) << 16) |
3115                               (crtc_state->pipe_src_w - 1));
3116                 I915_WRITE_FW(PRIMPOS(plane), 0);
3117                 I915_WRITE_FW(PRIMCNSTALPHA(plane), 0);
3118         }
3119
3120         I915_WRITE_FW(reg, dspcntr);
3121
3122         I915_WRITE_FW(DSPSTRIDE(plane), fb->pitches[0]);
3123         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3124                 I915_WRITE_FW(DSPSURF(plane),
3125                               intel_plane_ggtt_offset(plane_state) +
3126                               crtc->dspaddr_offset);
3127                 I915_WRITE_FW(DSPOFFSET(plane), (y << 16) | x);
3128         } else if (INTEL_GEN(dev_priv) >= 4) {
3129                 I915_WRITE_FW(DSPSURF(plane),
3130                               intel_plane_ggtt_offset(plane_state) +
3131                               crtc->dspaddr_offset);
3132                 I915_WRITE_FW(DSPTILEOFF(plane), (y << 16) | x);
3133                 I915_WRITE_FW(DSPLINOFF(plane), linear_offset);
3134         } else {
3135                 I915_WRITE_FW(DSPADDR(plane),
3136                               intel_plane_ggtt_offset(plane_state) +
3137                               crtc->dspaddr_offset);
3138         }
3139         POSTING_READ_FW(reg);
3140
3141         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3142 }
3143
3144 static void i9xx_disable_primary_plane(struct intel_plane *primary,
3145                                        struct intel_crtc *crtc)
3146 {
3147         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3148         enum plane plane = primary->plane;
3149         unsigned long irqflags;
3150
3151         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3152
3153         I915_WRITE_FW(DSPCNTR(plane), 0);
3154         if (INTEL_INFO(dev_priv)->gen >= 4)
3155                 I915_WRITE_FW(DSPSURF(plane), 0);
3156         else
3157                 I915_WRITE_FW(DSPADDR(plane), 0);
3158         POSTING_READ_FW(DSPCNTR(plane));
3159
3160         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3161 }
3162
3163 static u32
3164 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3165 {
3166         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3167                 return 64;
3168         else
3169                 return intel_tile_width_bytes(fb, plane);
3170 }
3171
3172 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3173 {
3174         struct drm_device *dev = intel_crtc->base.dev;
3175         struct drm_i915_private *dev_priv = to_i915(dev);
3176
3177         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3178         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3179         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3180 }
3181
3182 /*
3183  * This function detaches (aka. unbinds) unused scalers in hardware
3184  */
3185 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3186 {
3187         struct intel_crtc_scaler_state *scaler_state;
3188         int i;
3189
3190         scaler_state = &intel_crtc->config->scaler_state;
3191
3192         /* loop through and disable scalers that aren't in use */
3193         for (i = 0; i < intel_crtc->num_scalers; i++) {
3194                 if (!scaler_state->scalers[i].in_use)
3195                         skl_detach_scaler(intel_crtc, i);
3196         }
3197 }
3198
3199 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3200                      unsigned int rotation)
3201 {
3202         u32 stride;
3203
3204         if (plane >= fb->format->num_planes)
3205                 return 0;
3206
3207         stride = intel_fb_pitch(fb, plane, rotation);
3208
3209         /*
3210          * The stride is either expressed as a multiple of 64 bytes chunks for
3211          * linear buffers or in number of tiles for tiled buffers.
3212          */
3213         if (drm_rotation_90_or_270(rotation))
3214                 stride /= intel_tile_height(fb, plane);
3215         else
3216                 stride /= intel_fb_stride_alignment(fb, plane);
3217
3218         return stride;
3219 }
3220
3221 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3222 {
3223         switch (pixel_format) {
3224         case DRM_FORMAT_C8:
3225                 return PLANE_CTL_FORMAT_INDEXED;
3226         case DRM_FORMAT_RGB565:
3227                 return PLANE_CTL_FORMAT_RGB_565;
3228         case DRM_FORMAT_XBGR8888:
3229                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3230         case DRM_FORMAT_XRGB8888:
3231                 return PLANE_CTL_FORMAT_XRGB_8888;
3232         /*
3233          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3234          * to be already pre-multiplied. We need to add a knob (or a different
3235          * DRM_FORMAT) for user-space to configure that.
3236          */
3237         case DRM_FORMAT_ABGR8888:
3238                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3239                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3240         case DRM_FORMAT_ARGB8888:
3241                 return PLANE_CTL_FORMAT_XRGB_8888 |
3242                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3243         case DRM_FORMAT_XRGB2101010:
3244                 return PLANE_CTL_FORMAT_XRGB_2101010;
3245         case DRM_FORMAT_XBGR2101010:
3246                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3247         case DRM_FORMAT_YUYV:
3248                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3249         case DRM_FORMAT_YVYU:
3250                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3251         case DRM_FORMAT_UYVY:
3252                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3253         case DRM_FORMAT_VYUY:
3254                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3255         default:
3256                 MISSING_CASE(pixel_format);
3257         }
3258
3259         return 0;
3260 }
3261
3262 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3263 {
3264         switch (fb_modifier) {
3265         case DRM_FORMAT_MOD_LINEAR:
3266                 break;
3267         case I915_FORMAT_MOD_X_TILED:
3268                 return PLANE_CTL_TILED_X;
3269         case I915_FORMAT_MOD_Y_TILED:
3270                 return PLANE_CTL_TILED_Y;
3271         case I915_FORMAT_MOD_Yf_TILED:
3272                 return PLANE_CTL_TILED_YF;
3273         default:
3274                 MISSING_CASE(fb_modifier);
3275         }
3276
3277         return 0;
3278 }
3279
3280 static u32 skl_plane_ctl_rotation(unsigned int rotation)
3281 {
3282         switch (rotation) {
3283         case DRM_MODE_ROTATE_0:
3284                 break;
3285         /*
3286          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3287          * while i915 HW rotation is clockwise, thats why this swapping.
3288          */
3289         case DRM_MODE_ROTATE_90:
3290                 return PLANE_CTL_ROTATE_270;
3291         case DRM_MODE_ROTATE_180:
3292                 return PLANE_CTL_ROTATE_180;
3293         case DRM_MODE_ROTATE_270:
3294                 return PLANE_CTL_ROTATE_90;
3295         default:
3296                 MISSING_CASE(rotation);
3297         }
3298
3299         return 0;
3300 }
3301
3302 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3303                   const struct intel_plane_state *plane_state)
3304 {
3305         struct drm_i915_private *dev_priv =
3306                 to_i915(plane_state->base.plane->dev);
3307         const struct drm_framebuffer *fb = plane_state->base.fb;
3308         unsigned int rotation = plane_state->base.rotation;
3309         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3310         u32 plane_ctl;
3311
3312         plane_ctl = PLANE_CTL_ENABLE;
3313
3314         if (!IS_GEMINILAKE(dev_priv)) {
3315                 plane_ctl |=
3316                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3317                         PLANE_CTL_PIPE_CSC_ENABLE |
3318                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3319         }
3320
3321         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3322         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3323         plane_ctl |= skl_plane_ctl_rotation(rotation);
3324
3325         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3326                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3327         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3328                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3329
3330         return plane_ctl;
3331 }
3332
3333 static void skylake_update_primary_plane(struct intel_plane *plane,
3334                                          const struct intel_crtc_state *crtc_state,
3335                                          const struct intel_plane_state *plane_state)
3336 {
3337         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3338         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3339         const struct drm_framebuffer *fb = plane_state->base.fb;
3340         enum plane_id plane_id = plane->id;
3341         enum pipe pipe = plane->pipe;
3342         u32 plane_ctl = plane_state->ctl;
3343         unsigned int rotation = plane_state->base.rotation;
3344         u32 stride = skl_plane_stride(fb, 0, rotation);
3345         u32 surf_addr = plane_state->main.offset;
3346         int scaler_id = plane_state->scaler_id;
3347         int src_x = plane_state->main.x;
3348         int src_y = plane_state->main.y;
3349         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3350         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3351         int dst_x = plane_state->base.dst.x1;
3352         int dst_y = plane_state->base.dst.y1;
3353         int dst_w = drm_rect_width(&plane_state->base.dst);
3354         int dst_h = drm_rect_height(&plane_state->base.dst);
3355         unsigned long irqflags;
3356
3357         /* Sizes are 0 based */
3358         src_w--;
3359         src_h--;
3360         dst_w--;
3361         dst_h--;
3362
3363         crtc->dspaddr_offset = surf_addr;
3364
3365         crtc->adjusted_x = src_x;
3366         crtc->adjusted_y = src_y;
3367
3368         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3369
3370         if (IS_GEMINILAKE(dev_priv)) {
3371                 I915_WRITE_FW(PLANE_COLOR_CTL(pipe, plane_id),
3372                               PLANE_COLOR_PIPE_GAMMA_ENABLE |
3373                               PLANE_COLOR_PIPE_CSC_ENABLE |
3374                               PLANE_COLOR_PLANE_GAMMA_DISABLE);
3375         }
3376
3377         I915_WRITE_FW(PLANE_CTL(pipe, plane_id), plane_ctl);
3378         I915_WRITE_FW(PLANE_OFFSET(pipe, plane_id), (src_y << 16) | src_x);
3379         I915_WRITE_FW(PLANE_STRIDE(pipe, plane_id), stride);
3380         I915_WRITE_FW(PLANE_SIZE(pipe, plane_id), (src_h << 16) | src_w);
3381
3382         if (scaler_id >= 0) {
3383                 uint32_t ps_ctrl = 0;
3384
3385                 WARN_ON(!dst_w || !dst_h);
3386                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(plane_id) |
3387                         crtc_state->scaler_state.scalers[scaler_id].mode;
3388                 I915_WRITE_FW(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3389                 I915_WRITE_FW(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3390                 I915_WRITE_FW(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3391                 I915_WRITE_FW(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3392                 I915_WRITE_FW(PLANE_POS(pipe, plane_id), 0);
3393         } else {
3394                 I915_WRITE_FW(PLANE_POS(pipe, plane_id), (dst_y << 16) | dst_x);
3395         }
3396
3397         I915_WRITE_FW(PLANE_SURF(pipe, plane_id),
3398                       intel_plane_ggtt_offset(plane_state) + surf_addr);
3399
3400         POSTING_READ_FW(PLANE_SURF(pipe, plane_id));
3401
3402         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3403 }
3404
3405 static void skylake_disable_primary_plane(struct intel_plane *primary,
3406                                           struct intel_crtc *crtc)
3407 {
3408         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3409         enum plane_id plane_id = primary->id;
3410         enum pipe pipe = primary->pipe;
3411         unsigned long irqflags;
3412
3413         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3414
3415         I915_WRITE_FW(PLANE_CTL(pipe, plane_id), 0);
3416         I915_WRITE_FW(PLANE_SURF(pipe, plane_id), 0);
3417         POSTING_READ_FW(PLANE_SURF(pipe, plane_id));
3418
3419         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3420 }
3421
3422 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3423 {
3424         struct intel_crtc *crtc;
3425
3426         for_each_intel_crtc(&dev_priv->drm, crtc)
3427                 intel_finish_page_flip_cs(dev_priv, crtc->pipe);
3428 }
3429
3430 static int
3431 __intel_display_resume(struct drm_device *dev,
3432                        struct drm_atomic_state *state,
3433                        struct drm_modeset_acquire_ctx *ctx)
3434 {
3435         struct drm_crtc_state *crtc_state;
3436         struct drm_crtc *crtc;
3437         int i, ret;
3438
3439         intel_modeset_setup_hw_state(dev, ctx);
3440         i915_redisable_vga(to_i915(dev));
3441
3442         if (!state)
3443                 return 0;
3444
3445         /*
3446          * We've duplicated the state, pointers to the old state are invalid.
3447          *
3448          * Don't attempt to use the old state until we commit the duplicated state.
3449          */
3450         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3451                 /*
3452                  * Force recalculation even if we restore
3453                  * current state. With fast modeset this may not result
3454                  * in a modeset when the state is compatible.
3455                  */
3456                 crtc_state->mode_changed = true;
3457         }
3458
3459         /* ignore any reset values/BIOS leftovers in the WM registers */
3460         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3461                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3462
3463         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3464
3465         WARN_ON(ret == -EDEADLK);
3466         return ret;
3467 }
3468
3469 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3470 {
3471         return intel_has_gpu_reset(dev_priv) &&
3472                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3473 }
3474
3475 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3476 {
3477         struct drm_device *dev = &dev_priv->drm;
3478         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3479         struct drm_atomic_state *state;
3480         int ret;
3481
3482
3483         /* reset doesn't touch the display */
3484         if (!i915.force_reset_modeset_test &&
3485             !gpu_reset_clobbers_display(dev_priv))
3486                 return;
3487
3488         /*
3489          * Need mode_config.mutex so that we don't
3490          * trample ongoing ->detect() and whatnot.
3491          */
3492         mutex_lock(&dev->mode_config.mutex);
3493         drm_modeset_acquire_init(ctx, 0);
3494         while (1) {
3495                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3496                 if (ret != -EDEADLK)
3497                         break;
3498
3499                 drm_modeset_backoff(ctx);
3500         }
3501         /*
3502          * Disabling the crtcs gracefully seems nicer. Also the
3503          * g33 docs say we should at least disable all the planes.
3504          */
3505         state = drm_atomic_helper_duplicate_state(dev, ctx);
3506         if (IS_ERR(state)) {
3507                 ret = PTR_ERR(state);
3508                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3509                 return;
3510         }
3511
3512         ret = drm_atomic_helper_disable_all(dev, ctx);
3513         if (ret) {
3514                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3515                 drm_atomic_state_put(state);
3516                 return;
3517         }
3518
3519         dev_priv->modeset_restore_state = state;
3520         state->acquire_ctx = ctx;
3521 }
3522
3523 void intel_finish_reset(struct drm_i915_private *dev_priv)
3524 {
3525         struct drm_device *dev = &dev_priv->drm;
3526         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3527         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3528         int ret;
3529
3530         /* reset doesn't touch the display */
3531         if (!i915.force_reset_modeset_test &&
3532             !gpu_reset_clobbers_display(dev_priv))
3533                 return;
3534
3535         if (!state)
3536                 goto unlock;
3537
3538         /*
3539          * Flips in the rings will be nuked by the reset,
3540          * so complete all pending flips so that user space
3541          * will get its events and not get stuck.
3542          */
3543         intel_complete_page_flips(dev_priv);
3544
3545         dev_priv->modeset_restore_state = NULL;
3546
3547         /* reset doesn't touch the display */
3548         if (!gpu_reset_clobbers_display(dev_priv)) {
3549                 /* for testing only restore the display */
3550                 ret = __intel_display_resume(dev, state, ctx);
3551                         if (ret)
3552                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3553         } else {
3554                 /*
3555                  * The display has been reset as well,
3556                  * so need a full re-initialization.
3557                  */
3558                 intel_runtime_pm_disable_interrupts(dev_priv);
3559                 intel_runtime_pm_enable_interrupts(dev_priv);
3560
3561                 intel_pps_unlock_regs_wa(dev_priv);
3562                 intel_modeset_init_hw(dev);
3563
3564                 spin_lock_irq(&dev_priv->irq_lock);
3565                 if (dev_priv->display.hpd_irq_setup)
3566                         dev_priv->display.hpd_irq_setup(dev_priv);
3567                 spin_unlock_irq(&dev_priv->irq_lock);
3568
3569                 ret = __intel_display_resume(dev, state, ctx);
3570                 if (ret)
3571                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3572
3573                 intel_hpd_init(dev_priv);
3574         }
3575
3576         drm_atomic_state_put(state);
3577 unlock:
3578         drm_modeset_drop_locks(ctx);
3579         drm_modeset_acquire_fini(ctx);
3580         mutex_unlock(&dev->mode_config.mutex);
3581 }
3582
3583 static bool abort_flip_on_reset(struct intel_crtc *crtc)
3584 {
3585         struct i915_gpu_error *error = &to_i915(crtc->base.dev)->gpu_error;
3586
3587         if (i915_reset_backoff(error))
3588                 return true;
3589
3590         if (crtc->reset_count != i915_reset_count(error))
3591                 return true;
3592
3593         return false;
3594 }
3595
3596 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3597 {
3598         struct drm_device *dev = crtc->dev;
3599         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3600         bool pending;
3601
3602         if (abort_flip_on_reset(intel_crtc))
3603                 return false;
3604
3605         spin_lock_irq(&dev->event_lock);
3606         pending = to_intel_crtc(crtc)->flip_work != NULL;
3607         spin_unlock_irq(&dev->event_lock);
3608
3609         return pending;
3610 }
3611
3612 static void intel_update_pipe_config(struct intel_crtc *crtc,
3613                                      struct intel_crtc_state *old_crtc_state)
3614 {
3615         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3616         struct intel_crtc_state *pipe_config =
3617                 to_intel_crtc_state(crtc->base.state);
3618
3619         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3620         crtc->base.mode = crtc->base.state->mode;
3621
3622         /*
3623          * Update pipe size and adjust fitter if needed: the reason for this is
3624          * that in compute_mode_changes we check the native mode (not the pfit
3625          * mode) to see if we can flip rather than do a full mode set. In the
3626          * fastboot case, we'll flip, but if we don't update the pipesrc and
3627          * pfit state, we'll end up with a big fb scanned out into the wrong
3628          * sized surface.
3629          */
3630
3631         I915_WRITE(PIPESRC(crtc->pipe),
3632                    ((pipe_config->pipe_src_w - 1) << 16) |
3633                    (pipe_config->pipe_src_h - 1));
3634
3635         /* on skylake this is done by detaching scalers */
3636         if (INTEL_GEN(dev_priv) >= 9) {
3637                 skl_detach_scalers(crtc);
3638
3639                 if (pipe_config->pch_pfit.enabled)
3640                         skylake_pfit_enable(crtc);
3641         } else if (HAS_PCH_SPLIT(dev_priv)) {
3642                 if (pipe_config->pch_pfit.enabled)
3643                         ironlake_pfit_enable(crtc);
3644                 else if (old_crtc_state->pch_pfit.enabled)
3645                         ironlake_pfit_disable(crtc, true);
3646         }
3647 }
3648
3649 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3650 {
3651         struct drm_device *dev = crtc->base.dev;
3652         struct drm_i915_private *dev_priv = to_i915(dev);
3653         int pipe = crtc->pipe;
3654         i915_reg_t reg;
3655         u32 temp;
3656
3657         /* enable normal train */
3658         reg = FDI_TX_CTL(pipe);
3659         temp = I915_READ(reg);
3660         if (IS_IVYBRIDGE(dev_priv)) {
3661                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3662                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3663         } else {
3664                 temp &= ~FDI_LINK_TRAIN_NONE;
3665                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3666         }
3667         I915_WRITE(reg, temp);
3668
3669         reg = FDI_RX_CTL(pipe);
3670         temp = I915_READ(reg);
3671         if (HAS_PCH_CPT(dev_priv)) {
3672                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3673                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3674         } else {
3675                 temp &= ~FDI_LINK_TRAIN_NONE;
3676                 temp |= FDI_LINK_TRAIN_NONE;
3677         }
3678         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3679
3680         /* wait one idle pattern time */
3681         POSTING_READ(reg);
3682         udelay(1000);
3683
3684         /* IVB wants error correction enabled */
3685         if (IS_IVYBRIDGE(dev_priv))
3686                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3687                            FDI_FE_ERRC_ENABLE);
3688 }
3689
3690 /* The FDI link training functions for ILK/Ibexpeak. */
3691 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3692                                     const struct intel_crtc_state *crtc_state)
3693 {
3694         struct drm_device *dev = crtc->base.dev;
3695         struct drm_i915_private *dev_priv = to_i915(dev);
3696         int pipe = crtc->pipe;
3697         i915_reg_t reg;
3698         u32 temp, tries;
3699
3700         /* FDI needs bits from pipe first */
3701         assert_pipe_enabled(dev_priv, pipe);
3702
3703         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3704            for train result */
3705         reg = FDI_RX_IMR(pipe);
3706         temp = I915_READ(reg);
3707         temp &= ~FDI_RX_SYMBOL_LOCK;
3708         temp &= ~FDI_RX_BIT_LOCK;
3709         I915_WRITE(reg, temp);
3710         I915_READ(reg);
3711         udelay(150);
3712
3713         /* enable CPU FDI TX and PCH FDI RX */
3714         reg = FDI_TX_CTL(pipe);
3715         temp = I915_READ(reg);
3716         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3717         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3718         temp &= ~FDI_LINK_TRAIN_NONE;
3719         temp |= FDI_LINK_TRAIN_PATTERN_1;
3720         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3721
3722         reg = FDI_RX_CTL(pipe);
3723         temp = I915_READ(reg);
3724         temp &= ~FDI_LINK_TRAIN_NONE;
3725         temp |= FDI_LINK_TRAIN_PATTERN_1;
3726         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3727
3728         POSTING_READ(reg);
3729         udelay(150);
3730
3731         /* Ironlake workaround, enable clock pointer after FDI enable*/
3732         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3733         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3734                    FDI_RX_PHASE_SYNC_POINTER_EN);
3735
3736         reg = FDI_RX_IIR(pipe);
3737         for (tries = 0; tries < 5; tries++) {
3738                 temp = I915_READ(reg);
3739                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3740
3741                 if ((temp & FDI_RX_BIT_LOCK)) {
3742                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3743                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3744                         break;
3745                 }
3746         }
3747         if (tries == 5)
3748                 DRM_ERROR("FDI train 1 fail!\n");
3749
3750         /* Train 2 */
3751         reg = FDI_TX_CTL(pipe);
3752         temp = I915_READ(reg);
3753         temp &= ~FDI_LINK_TRAIN_NONE;
3754         temp |= FDI_LINK_TRAIN_PATTERN_2;
3755         I915_WRITE(reg, temp);
3756
3757         reg = FDI_RX_CTL(pipe);
3758         temp = I915_READ(reg);
3759         temp &= ~FDI_LINK_TRAIN_NONE;
3760         temp |= FDI_LINK_TRAIN_PATTERN_2;
3761         I915_WRITE(reg, temp);
3762
3763         POSTING_READ(reg);
3764         udelay(150);
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_SYMBOL_LOCK) {
3772                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3773                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3774                         break;
3775                 }
3776         }
3777         if (tries == 5)
3778                 DRM_ERROR("FDI train 2 fail!\n");
3779
3780         DRM_DEBUG_KMS("FDI train done\n");
3781
3782 }
3783
3784 static const int snb_b_fdi_train_param[] = {
3785         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3786         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3787         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3788         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3789 };
3790
3791 /* The FDI link training functions for SNB/Cougarpoint. */
3792 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3793                                 const struct intel_crtc_state *crtc_state)
3794 {
3795         struct drm_device *dev = crtc->base.dev;
3796         struct drm_i915_private *dev_priv = to_i915(dev);
3797         int pipe = crtc->pipe;
3798         i915_reg_t reg;
3799         u32 temp, i, retry;
3800
3801         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3802            for train result */
3803         reg = FDI_RX_IMR(pipe);
3804         temp = I915_READ(reg);
3805         temp &= ~FDI_RX_SYMBOL_LOCK;
3806         temp &= ~FDI_RX_BIT_LOCK;
3807         I915_WRITE(reg, temp);
3808
3809         POSTING_READ(reg);
3810         udelay(150);
3811
3812         /* enable CPU FDI TX and PCH FDI RX */
3813         reg = FDI_TX_CTL(pipe);
3814         temp = I915_READ(reg);
3815         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3816         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3817         temp &= ~FDI_LINK_TRAIN_NONE;
3818         temp |= FDI_LINK_TRAIN_PATTERN_1;
3819         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3820         /* SNB-B */
3821         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3822         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3823
3824         I915_WRITE(FDI_RX_MISC(pipe),
3825                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3826
3827         reg = FDI_RX_CTL(pipe);
3828         temp = I915_READ(reg);
3829         if (HAS_PCH_CPT(dev_priv)) {
3830                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3831                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3832         } else {
3833                 temp &= ~FDI_LINK_TRAIN_NONE;
3834                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3835         }
3836         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3837
3838         POSTING_READ(reg);
3839         udelay(150);
3840
3841         for (i = 0; i < 4; i++) {
3842                 reg = FDI_TX_CTL(pipe);
3843                 temp = I915_READ(reg);
3844                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3845                 temp |= snb_b_fdi_train_param[i];
3846                 I915_WRITE(reg, temp);
3847
3848                 POSTING_READ(reg);
3849                 udelay(500);
3850
3851                 for (retry = 0; retry < 5; retry++) {
3852                         reg = FDI_RX_IIR(pipe);
3853                         temp = I915_READ(reg);
3854                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3855                         if (temp & FDI_RX_BIT_LOCK) {
3856                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3857                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3858                                 break;
3859                         }
3860                         udelay(50);
3861                 }
3862                 if (retry < 5)
3863                         break;
3864         }
3865         if (i == 4)
3866                 DRM_ERROR("FDI train 1 fail!\n");
3867
3868         /* Train 2 */
3869         reg = FDI_TX_CTL(pipe);
3870         temp = I915_READ(reg);
3871         temp &= ~FDI_LINK_TRAIN_NONE;
3872         temp |= FDI_LINK_TRAIN_PATTERN_2;
3873         if (IS_GEN6(dev_priv)) {
3874                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3875                 /* SNB-B */
3876                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3877         }
3878         I915_WRITE(reg, temp);
3879
3880         reg = FDI_RX_CTL(pipe);
3881         temp = I915_READ(reg);
3882         if (HAS_PCH_CPT(dev_priv)) {
3883                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3884                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3885         } else {
3886                 temp &= ~FDI_LINK_TRAIN_NONE;
3887                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3888         }
3889         I915_WRITE(reg, temp);
3890
3891         POSTING_READ(reg);
3892         udelay(150);
3893
3894         for (i = 0; i < 4; i++) {
3895                 reg = FDI_TX_CTL(pipe);
3896                 temp = I915_READ(reg);
3897                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3898                 temp |= snb_b_fdi_train_param[i];
3899                 I915_WRITE(reg, temp);
3900
3901                 POSTING_READ(reg);
3902                 udelay(500);
3903
3904                 for (retry = 0; retry < 5; retry++) {
3905                         reg = FDI_RX_IIR(pipe);
3906                         temp = I915_READ(reg);
3907                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3908                         if (temp & FDI_RX_SYMBOL_LOCK) {
3909                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3910                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3911                                 break;
3912                         }
3913                         udelay(50);
3914                 }
3915                 if (retry < 5)
3916                         break;
3917         }
3918         if (i == 4)
3919                 DRM_ERROR("FDI train 2 fail!\n");
3920
3921         DRM_DEBUG_KMS("FDI train done.\n");
3922 }
3923
3924 /* Manual link training for Ivy Bridge A0 parts */
3925 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
3926                                       const struct intel_crtc_state *crtc_state)
3927 {
3928         struct drm_device *dev = crtc->base.dev;
3929         struct drm_i915_private *dev_priv = to_i915(dev);
3930         int pipe = crtc->pipe;
3931         i915_reg_t reg;
3932         u32 temp, i, j;
3933
3934         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3935            for train result */
3936         reg = FDI_RX_IMR(pipe);
3937         temp = I915_READ(reg);
3938         temp &= ~FDI_RX_SYMBOL_LOCK;
3939         temp &= ~FDI_RX_BIT_LOCK;
3940         I915_WRITE(reg, temp);
3941
3942         POSTING_READ(reg);
3943         udelay(150);
3944
3945         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3946                       I915_READ(FDI_RX_IIR(pipe)));
3947
3948         /* Try each vswing and preemphasis setting twice before moving on */
3949         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3950                 /* disable first in case we need to retry */
3951                 reg = FDI_TX_CTL(pipe);
3952                 temp = I915_READ(reg);
3953                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3954                 temp &= ~FDI_TX_ENABLE;
3955                 I915_WRITE(reg, temp);
3956
3957                 reg = FDI_RX_CTL(pipe);
3958                 temp = I915_READ(reg);
3959                 temp &= ~FDI_LINK_TRAIN_AUTO;
3960                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3961                 temp &= ~FDI_RX_ENABLE;
3962                 I915_WRITE(reg, temp);
3963
3964                 /* enable CPU FDI TX and PCH FDI RX */
3965                 reg = FDI_TX_CTL(pipe);
3966                 temp = I915_READ(reg);
3967                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3968                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3969                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3970                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3971                 temp |= snb_b_fdi_train_param[j/2];
3972                 temp |= FDI_COMPOSITE_SYNC;
3973                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3974
3975                 I915_WRITE(FDI_RX_MISC(pipe),
3976                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3977
3978                 reg = FDI_RX_CTL(pipe);
3979                 temp = I915_READ(reg);
3980                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3981                 temp |= FDI_COMPOSITE_SYNC;
3982                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3983
3984                 POSTING_READ(reg);
3985                 udelay(1); /* should be 0.5us */
3986
3987                 for (i = 0; i < 4; i++) {
3988                         reg = FDI_RX_IIR(pipe);
3989                         temp = I915_READ(reg);
3990                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3991
3992                         if (temp & FDI_RX_BIT_LOCK ||
3993                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3994                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3995                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3996                                               i);
3997                                 break;
3998                         }
3999                         udelay(1); /* should be 0.5us */
4000                 }
4001                 if (i == 4) {
4002                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4003                         continue;
4004                 }
4005
4006                 /* Train 2 */
4007                 reg = FDI_TX_CTL(pipe);
4008                 temp = I915_READ(reg);
4009                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4010                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4011                 I915_WRITE(reg, temp);
4012
4013                 reg = FDI_RX_CTL(pipe);
4014                 temp = I915_READ(reg);
4015                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4016                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4017                 I915_WRITE(reg, temp);
4018
4019                 POSTING_READ(reg);
4020                 udelay(2); /* should be 1.5us */
4021
4022                 for (i = 0; i < 4; i++) {
4023                         reg = FDI_RX_IIR(pipe);
4024                         temp = I915_READ(reg);
4025                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4026
4027                         if (temp & FDI_RX_SYMBOL_LOCK ||
4028                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4029                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4030                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4031                                               i);
4032                                 goto train_done;
4033                         }
4034                         udelay(2); /* should be 1.5us */
4035                 }
4036                 if (i == 4)
4037                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4038         }
4039
4040 train_done:
4041         DRM_DEBUG_KMS("FDI train done.\n");
4042 }
4043
4044 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4045 {
4046         struct drm_device *dev = intel_crtc->base.dev;
4047         struct drm_i915_private *dev_priv = to_i915(dev);
4048         int pipe = intel_crtc->pipe;
4049         i915_reg_t reg;
4050         u32 temp;
4051
4052         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4053         reg = FDI_RX_CTL(pipe);
4054         temp = I915_READ(reg);
4055         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4056         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4057         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4058         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4059
4060         POSTING_READ(reg);
4061         udelay(200);
4062
4063         /* Switch from Rawclk to PCDclk */
4064         temp = I915_READ(reg);
4065         I915_WRITE(reg, temp | FDI_PCDCLK);
4066
4067         POSTING_READ(reg);
4068         udelay(200);
4069
4070         /* Enable CPU FDI TX PLL, always on for Ironlake */
4071         reg = FDI_TX_CTL(pipe);
4072         temp = I915_READ(reg);
4073         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4074                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4075
4076                 POSTING_READ(reg);
4077                 udelay(100);
4078         }
4079 }
4080
4081 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4082 {
4083         struct drm_device *dev = intel_crtc->base.dev;
4084         struct drm_i915_private *dev_priv = to_i915(dev);
4085         int pipe = intel_crtc->pipe;
4086         i915_reg_t reg;
4087         u32 temp;
4088
4089         /* Switch from PCDclk to Rawclk */
4090         reg = FDI_RX_CTL(pipe);
4091         temp = I915_READ(reg);
4092         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4093
4094         /* Disable CPU FDI TX PLL */
4095         reg = FDI_TX_CTL(pipe);
4096         temp = I915_READ(reg);
4097         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4098
4099         POSTING_READ(reg);
4100         udelay(100);
4101
4102         reg = FDI_RX_CTL(pipe);
4103         temp = I915_READ(reg);
4104         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4105
4106         /* Wait for the clocks to turn off. */
4107         POSTING_READ(reg);
4108         udelay(100);
4109 }
4110
4111 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4112 {
4113         struct drm_device *dev = crtc->dev;
4114         struct drm_i915_private *dev_priv = to_i915(dev);
4115         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4116         int pipe = intel_crtc->pipe;
4117         i915_reg_t reg;
4118         u32 temp;
4119
4120         /* disable CPU FDI tx and PCH FDI rx */
4121         reg = FDI_TX_CTL(pipe);
4122         temp = I915_READ(reg);
4123         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4124         POSTING_READ(reg);
4125
4126         reg = FDI_RX_CTL(pipe);
4127         temp = I915_READ(reg);
4128         temp &= ~(0x7 << 16);
4129         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4130         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4131
4132         POSTING_READ(reg);
4133         udelay(100);
4134
4135         /* Ironlake workaround, disable clock pointer after downing FDI */
4136         if (HAS_PCH_IBX(dev_priv))
4137                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4138
4139         /* still set train pattern 1 */
4140         reg = FDI_TX_CTL(pipe);
4141         temp = I915_READ(reg);
4142         temp &= ~FDI_LINK_TRAIN_NONE;
4143         temp |= FDI_LINK_TRAIN_PATTERN_1;
4144         I915_WRITE(reg, temp);
4145
4146         reg = FDI_RX_CTL(pipe);
4147         temp = I915_READ(reg);
4148         if (HAS_PCH_CPT(dev_priv)) {
4149                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4150                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4151         } else {
4152                 temp &= ~FDI_LINK_TRAIN_NONE;
4153                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4154         }
4155         /* BPC in FDI rx is consistent with that in PIPECONF */
4156         temp &= ~(0x07 << 16);
4157         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4158         I915_WRITE(reg, temp);
4159
4160         POSTING_READ(reg);
4161         udelay(100);
4162 }
4163
4164 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4165 {
4166         struct intel_crtc *crtc;
4167
4168         /* Note that we don't need to be called with mode_config.lock here
4169          * as our list of CRTC objects is static for the lifetime of the
4170          * device and so cannot disappear as we iterate. Similarly, we can
4171          * happily treat the predicates as racy, atomic checks as userspace
4172          * cannot claim and pin a new fb without at least acquring the
4173          * struct_mutex and so serialising with us.
4174          */
4175         for_each_intel_crtc(&dev_priv->drm, crtc) {
4176                 if (atomic_read(&crtc->unpin_work_count) == 0)
4177                         continue;
4178
4179                 if (crtc->flip_work)
4180                         intel_wait_for_vblank(dev_priv, crtc->pipe);
4181
4182                 return true;
4183         }
4184
4185         return false;
4186 }
4187
4188 static void page_flip_completed(struct intel_crtc *intel_crtc)
4189 {
4190         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4191         struct intel_flip_work *work = intel_crtc->flip_work;
4192
4193         intel_crtc->flip_work = NULL;
4194
4195         if (work->event)
4196                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
4197
4198         drm_crtc_vblank_put(&intel_crtc->base);
4199
4200         wake_up_all(&dev_priv->pending_flip_queue);
4201         trace_i915_flip_complete(intel_crtc->plane,
4202                                  work->pending_flip_obj);
4203
4204         queue_work(dev_priv->wq, &work->unpin_work);
4205 }
4206
4207 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
4208 {
4209         struct drm_device *dev = crtc->dev;
4210         struct drm_i915_private *dev_priv = to_i915(dev);
4211         long ret;
4212
4213         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
4214
4215         ret = wait_event_interruptible_timeout(
4216                                         dev_priv->pending_flip_queue,
4217                                         !intel_crtc_has_pending_flip(crtc),
4218                                         60*HZ);
4219
4220         if (ret < 0)
4221                 return ret;
4222
4223         if (ret == 0) {
4224                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4225                 struct intel_flip_work *work;
4226
4227                 spin_lock_irq(&dev->event_lock);
4228                 work = intel_crtc->flip_work;
4229                 if (work && !is_mmio_work(work)) {
4230                         WARN_ONCE(1, "Removing stuck page flip\n");
4231                         page_flip_completed(intel_crtc);
4232                 }
4233                 spin_unlock_irq(&dev->event_lock);
4234         }
4235
4236         return 0;
4237 }
4238
4239 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4240 {
4241         u32 temp;
4242
4243         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4244
4245         mutex_lock(&dev_priv->sb_lock);
4246
4247         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4248         temp |= SBI_SSCCTL_DISABLE;
4249         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4250
4251         mutex_unlock(&dev_priv->sb_lock);
4252 }
4253
4254 /* Program iCLKIP clock to the desired frequency */
4255 static void lpt_program_iclkip(struct intel_crtc *crtc)
4256 {
4257         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4258         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4259         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4260         u32 temp;
4261
4262         lpt_disable_iclkip(dev_priv);
4263
4264         /* The iCLK virtual clock root frequency is in MHz,
4265          * but the adjusted_mode->crtc_clock in in KHz. To get the
4266          * divisors, it is necessary to divide one by another, so we
4267          * convert the virtual clock precision to KHz here for higher
4268          * precision.
4269          */
4270         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4271                 u32 iclk_virtual_root_freq = 172800 * 1000;
4272                 u32 iclk_pi_range = 64;
4273                 u32 desired_divisor;
4274
4275                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4276                                                     clock << auxdiv);
4277                 divsel = (desired_divisor / iclk_pi_range) - 2;
4278                 phaseinc = desired_divisor % iclk_pi_range;
4279
4280                 /*
4281                  * Near 20MHz is a corner case which is
4282                  * out of range for the 7-bit divisor
4283                  */
4284                 if (divsel <= 0x7f)
4285                         break;
4286         }
4287
4288         /* This should not happen with any sane values */
4289         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4290                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4291         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4292                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4293
4294         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4295                         clock,
4296                         auxdiv,
4297                         divsel,
4298                         phasedir,
4299                         phaseinc);
4300
4301         mutex_lock(&dev_priv->sb_lock);
4302
4303         /* Program SSCDIVINTPHASE6 */
4304         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4305         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4306         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4307         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4308         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4309         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4310         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4311         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4312
4313         /* Program SSCAUXDIV */
4314         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4315         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4316         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4317         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4318
4319         /* Enable modulator and associated divider */
4320         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4321         temp &= ~SBI_SSCCTL_DISABLE;
4322         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4323
4324         mutex_unlock(&dev_priv->sb_lock);
4325
4326         /* Wait for initialization time */
4327         udelay(24);
4328
4329         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4330 }
4331
4332 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4333 {
4334         u32 divsel, phaseinc, auxdiv;
4335         u32 iclk_virtual_root_freq = 172800 * 1000;
4336         u32 iclk_pi_range = 64;
4337         u32 desired_divisor;
4338         u32 temp;
4339
4340         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4341                 return 0;
4342
4343         mutex_lock(&dev_priv->sb_lock);
4344
4345         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4346         if (temp & SBI_SSCCTL_DISABLE) {
4347                 mutex_unlock(&dev_priv->sb_lock);
4348                 return 0;
4349         }
4350
4351         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4352         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4353                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4354         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4355                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4356
4357         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4358         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4359                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4360
4361         mutex_unlock(&dev_priv->sb_lock);
4362
4363         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4364
4365         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4366                                  desired_divisor << auxdiv);
4367 }
4368
4369 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4370                                                 enum pipe pch_transcoder)
4371 {
4372         struct drm_device *dev = crtc->base.dev;
4373         struct drm_i915_private *dev_priv = to_i915(dev);
4374         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4375
4376         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4377                    I915_READ(HTOTAL(cpu_transcoder)));
4378         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4379                    I915_READ(HBLANK(cpu_transcoder)));
4380         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4381                    I915_READ(HSYNC(cpu_transcoder)));
4382
4383         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4384                    I915_READ(VTOTAL(cpu_transcoder)));
4385         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4386                    I915_READ(VBLANK(cpu_transcoder)));
4387         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4388                    I915_READ(VSYNC(cpu_transcoder)));
4389         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4390                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4391 }
4392
4393 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4394 {
4395         struct drm_i915_private *dev_priv = to_i915(dev);
4396         uint32_t temp;
4397
4398         temp = I915_READ(SOUTH_CHICKEN1);
4399         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4400                 return;
4401
4402         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4403         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4404
4405         temp &= ~FDI_BC_BIFURCATION_SELECT;
4406         if (enable)
4407                 temp |= FDI_BC_BIFURCATION_SELECT;
4408
4409         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4410         I915_WRITE(SOUTH_CHICKEN1, temp);
4411         POSTING_READ(SOUTH_CHICKEN1);
4412 }
4413
4414 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4415 {
4416         struct drm_device *dev = intel_crtc->base.dev;
4417
4418         switch (intel_crtc->pipe) {
4419         case PIPE_A:
4420                 break;
4421         case PIPE_B:
4422                 if (intel_crtc->config->fdi_lanes > 2)
4423                         cpt_set_fdi_bc_bifurcation(dev, false);
4424                 else
4425                         cpt_set_fdi_bc_bifurcation(dev, true);
4426
4427                 break;
4428         case PIPE_C:
4429                 cpt_set_fdi_bc_bifurcation(dev, true);
4430
4431                 break;
4432         default:
4433                 BUG();
4434         }
4435 }
4436
4437 /* Return which DP Port should be selected for Transcoder DP control */
4438 static enum port
4439 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4440 {
4441         struct drm_device *dev = crtc->base.dev;
4442         struct intel_encoder *encoder;
4443
4444         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4445                 if (encoder->type == INTEL_OUTPUT_DP ||
4446                     encoder->type == INTEL_OUTPUT_EDP)
4447                         return enc_to_dig_port(&encoder->base)->port;
4448         }
4449
4450         return -1;
4451 }
4452
4453 /*
4454  * Enable PCH resources required for PCH ports:
4455  *   - PCH PLLs
4456  *   - FDI training & RX/TX
4457  *   - update transcoder timings
4458  *   - DP transcoding bits
4459  *   - transcoder
4460  */
4461 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4462 {
4463         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4464         struct drm_device *dev = crtc->base.dev;
4465         struct drm_i915_private *dev_priv = to_i915(dev);
4466         int pipe = crtc->pipe;
4467         u32 temp;
4468
4469         assert_pch_transcoder_disabled(dev_priv, pipe);
4470
4471         if (IS_IVYBRIDGE(dev_priv))
4472                 ivybridge_update_fdi_bc_bifurcation(crtc);
4473
4474         /* Write the TU size bits before fdi link training, so that error
4475          * detection works. */
4476         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4477                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4478
4479         /* For PCH output, training FDI link */
4480         dev_priv->display.fdi_link_train(crtc, crtc_state);
4481
4482         /* We need to program the right clock selection before writing the pixel
4483          * mutliplier into the DPLL. */
4484         if (HAS_PCH_CPT(dev_priv)) {
4485                 u32 sel;
4486
4487                 temp = I915_READ(PCH_DPLL_SEL);
4488                 temp |= TRANS_DPLL_ENABLE(pipe);
4489                 sel = TRANS_DPLLB_SEL(pipe);
4490                 if (crtc_state->shared_dpll ==
4491                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4492                         temp |= sel;
4493                 else
4494                         temp &= ~sel;
4495                 I915_WRITE(PCH_DPLL_SEL, temp);
4496         }
4497
4498         /* XXX: pch pll's can be enabled any time before we enable the PCH
4499          * transcoder, and we actually should do this to not upset any PCH
4500          * transcoder that already use the clock when we share it.
4501          *
4502          * Note that enable_shared_dpll tries to do the right thing, but
4503          * get_shared_dpll unconditionally resets the pll - we need that to have
4504          * the right LVDS enable sequence. */
4505         intel_enable_shared_dpll(crtc);
4506
4507         /* set transcoder timing, panel must allow it */
4508         assert_panel_unlocked(dev_priv, pipe);
4509         ironlake_pch_transcoder_set_timings(crtc, pipe);
4510
4511         intel_fdi_normal_train(crtc);
4512
4513         /* For PCH DP, enable TRANS_DP_CTL */
4514         if (HAS_PCH_CPT(dev_priv) &&
4515             intel_crtc_has_dp_encoder(crtc_state)) {
4516                 const struct drm_display_mode *adjusted_mode =
4517                         &crtc_state->base.adjusted_mode;
4518                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4519                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4520                 temp = I915_READ(reg);
4521                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4522                           TRANS_DP_SYNC_MASK |
4523                           TRANS_DP_BPC_MASK);
4524                 temp |= TRANS_DP_OUTPUT_ENABLE;
4525                 temp |= bpc << 9; /* same format but at 11:9 */
4526
4527                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4528                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4529                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4530                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4531
4532                 switch (intel_trans_dp_port_sel(crtc)) {
4533                 case PORT_B:
4534                         temp |= TRANS_DP_PORT_SEL_B;
4535                         break;
4536                 case PORT_C:
4537                         temp |= TRANS_DP_PORT_SEL_C;
4538                         break;
4539                 case PORT_D:
4540                         temp |= TRANS_DP_PORT_SEL_D;
4541                         break;
4542                 default:
4543                         BUG();
4544                 }
4545
4546                 I915_WRITE(reg, temp);
4547         }
4548
4549         ironlake_enable_pch_transcoder(dev_priv, pipe);
4550 }
4551
4552 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4553 {
4554         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4555         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4556         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4557
4558         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4559
4560         lpt_program_iclkip(crtc);
4561
4562         /* Set transcoder timing. */
4563         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4564
4565         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4566 }
4567
4568 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4569 {
4570         struct drm_i915_private *dev_priv = to_i915(dev);
4571         i915_reg_t dslreg = PIPEDSL(pipe);
4572         u32 temp;
4573
4574         temp = I915_READ(dslreg);
4575         udelay(500);
4576         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4577                 if (wait_for(I915_READ(dslreg) != temp, 5))
4578                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4579         }
4580 }
4581
4582 static int
4583 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4584                   unsigned int scaler_user, int *scaler_id,
4585                   int src_w, int src_h, int dst_w, int dst_h)
4586 {
4587         struct intel_crtc_scaler_state *scaler_state =
4588                 &crtc_state->scaler_state;
4589         struct intel_crtc *intel_crtc =
4590                 to_intel_crtc(crtc_state->base.crtc);
4591         int need_scaling;
4592
4593         /*
4594          * Src coordinates are already rotated by 270 degrees for
4595          * the 90/270 degree plane rotation cases (to match the
4596          * GTT mapping), hence no need to account for rotation here.
4597          */
4598         need_scaling = src_w != dst_w || src_h != dst_h;
4599
4600         /*
4601          * if plane is being disabled or scaler is no more required or force detach
4602          *  - free scaler binded to this plane/crtc
4603          *  - in order to do this, update crtc->scaler_usage
4604          *
4605          * Here scaler state in crtc_state is set free so that
4606          * scaler can be assigned to other user. Actual register
4607          * update to free the scaler is done in plane/panel-fit programming.
4608          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4609          */
4610         if (force_detach || !need_scaling) {
4611                 if (*scaler_id >= 0) {
4612                         scaler_state->scaler_users &= ~(1 << scaler_user);
4613                         scaler_state->scalers[*scaler_id].in_use = 0;
4614
4615                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4616                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4617                                 intel_crtc->pipe, scaler_user, *scaler_id,
4618                                 scaler_state->scaler_users);
4619                         *scaler_id = -1;
4620                 }
4621                 return 0;
4622         }
4623
4624         /* range checks */
4625         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4626                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4627
4628                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4629                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4630                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4631                         "size is out of scaler range\n",
4632                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4633                 return -EINVAL;
4634         }
4635
4636         /* mark this plane as a scaler user in crtc_state */
4637         scaler_state->scaler_users |= (1 << scaler_user);
4638         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4639                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4640                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4641                 scaler_state->scaler_users);
4642
4643         return 0;
4644 }
4645
4646 /**
4647  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4648  *
4649  * @state: crtc's scaler state
4650  *
4651  * Return
4652  *     0 - scaler_usage updated successfully
4653  *    error - requested scaling cannot be supported or other error condition
4654  */
4655 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4656 {
4657         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4658
4659         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4660                 &state->scaler_state.scaler_id,
4661                 state->pipe_src_w, state->pipe_src_h,
4662                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4663 }
4664
4665 /**
4666  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4667  *
4668  * @state: crtc's scaler state
4669  * @plane_state: atomic plane state to update
4670  *
4671  * Return
4672  *     0 - scaler_usage updated successfully
4673  *    error - requested scaling cannot be supported or other error condition
4674  */
4675 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4676                                    struct intel_plane_state *plane_state)
4677 {
4678
4679         struct intel_plane *intel_plane =
4680                 to_intel_plane(plane_state->base.plane);
4681         struct drm_framebuffer *fb = plane_state->base.fb;
4682         int ret;
4683
4684         bool force_detach = !fb || !plane_state->base.visible;
4685
4686         ret = skl_update_scaler(crtc_state, force_detach,
4687                                 drm_plane_index(&intel_plane->base),
4688                                 &plane_state->scaler_id,
4689                                 drm_rect_width(&plane_state->base.src) >> 16,
4690                                 drm_rect_height(&plane_state->base.src) >> 16,
4691                                 drm_rect_width(&plane_state->base.dst),
4692                                 drm_rect_height(&plane_state->base.dst));
4693
4694         if (ret || plane_state->scaler_id < 0)
4695                 return ret;
4696
4697         /* check colorkey */
4698         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4699                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4700                               intel_plane->base.base.id,
4701                               intel_plane->base.name);
4702                 return -EINVAL;
4703         }
4704
4705         /* Check src format */
4706         switch (fb->format->format) {
4707         case DRM_FORMAT_RGB565:
4708         case DRM_FORMAT_XBGR8888:
4709         case DRM_FORMAT_XRGB8888:
4710         case DRM_FORMAT_ABGR8888:
4711         case DRM_FORMAT_ARGB8888:
4712         case DRM_FORMAT_XRGB2101010:
4713         case DRM_FORMAT_XBGR2101010:
4714         case DRM_FORMAT_YUYV:
4715         case DRM_FORMAT_YVYU:
4716         case DRM_FORMAT_UYVY:
4717         case DRM_FORMAT_VYUY:
4718                 break;
4719         default:
4720                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4721                               intel_plane->base.base.id, intel_plane->base.name,
4722                               fb->base.id, fb->format->format);
4723                 return -EINVAL;
4724         }
4725
4726         return 0;
4727 }
4728
4729 static void skylake_scaler_disable(struct intel_crtc *crtc)
4730 {
4731         int i;
4732
4733         for (i = 0; i < crtc->num_scalers; i++)
4734                 skl_detach_scaler(crtc, i);
4735 }
4736
4737 static void skylake_pfit_enable(struct intel_crtc *crtc)
4738 {
4739         struct drm_device *dev = crtc->base.dev;
4740         struct drm_i915_private *dev_priv = to_i915(dev);
4741         int pipe = crtc->pipe;
4742         struct intel_crtc_scaler_state *scaler_state =
4743                 &crtc->config->scaler_state;
4744
4745         if (crtc->config->pch_pfit.enabled) {
4746                 int id;
4747
4748                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4749                         return;
4750
4751                 id = scaler_state->scaler_id;
4752                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4753                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4754                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4755                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4756         }
4757 }
4758
4759 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4760 {
4761         struct drm_device *dev = crtc->base.dev;
4762         struct drm_i915_private *dev_priv = to_i915(dev);
4763         int pipe = crtc->pipe;
4764
4765         if (crtc->config->pch_pfit.enabled) {
4766                 /* Force use of hard-coded filter coefficients
4767                  * as some pre-programmed values are broken,
4768                  * e.g. x201.
4769                  */
4770                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4771                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4772                                                  PF_PIPE_SEL_IVB(pipe));
4773                 else
4774                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4775                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4776                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4777         }
4778 }
4779
4780 void hsw_enable_ips(struct intel_crtc *crtc)
4781 {
4782         struct drm_device *dev = crtc->base.dev;
4783         struct drm_i915_private *dev_priv = to_i915(dev);
4784
4785         if (!crtc->config->ips_enabled)
4786                 return;
4787
4788         /*
4789          * We can only enable IPS after we enable a plane and wait for a vblank
4790          * This function is called from post_plane_update, which is run after
4791          * a vblank wait.
4792          */
4793
4794         assert_plane_enabled(dev_priv, crtc->plane);
4795         if (IS_BROADWELL(dev_priv)) {
4796                 mutex_lock(&dev_priv->rps.hw_lock);
4797                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4798                 mutex_unlock(&dev_priv->rps.hw_lock);
4799                 /* Quoting Art Runyan: "its not safe to expect any particular
4800                  * value in IPS_CTL bit 31 after enabling IPS through the
4801                  * mailbox." Moreover, the mailbox may return a bogus state,
4802                  * so we need to just enable it and continue on.
4803                  */
4804         } else {
4805                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4806                 /* The bit only becomes 1 in the next vblank, so this wait here
4807                  * is essentially intel_wait_for_vblank. If we don't have this
4808                  * and don't wait for vblanks until the end of crtc_enable, then
4809                  * the HW state readout code will complain that the expected
4810                  * IPS_CTL value is not the one we read. */
4811                 if (intel_wait_for_register(dev_priv,
4812                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4813                                             50))
4814                         DRM_ERROR("Timed out waiting for IPS enable\n");
4815         }
4816 }
4817
4818 void hsw_disable_ips(struct intel_crtc *crtc)
4819 {
4820         struct drm_device *dev = crtc->base.dev;
4821         struct drm_i915_private *dev_priv = to_i915(dev);
4822
4823         if (!crtc->config->ips_enabled)
4824                 return;
4825
4826         assert_plane_enabled(dev_priv, crtc->plane);
4827         if (IS_BROADWELL(dev_priv)) {
4828                 mutex_lock(&dev_priv->rps.hw_lock);
4829                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4830                 mutex_unlock(&dev_priv->rps.hw_lock);
4831                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4832                 if (intel_wait_for_register(dev_priv,
4833                                             IPS_CTL, IPS_ENABLE, 0,
4834                                             42))
4835                         DRM_ERROR("Timed out waiting for IPS disable\n");
4836         } else {
4837                 I915_WRITE(IPS_CTL, 0);
4838                 POSTING_READ(IPS_CTL);
4839         }
4840
4841         /* We need to wait for a vblank before we can disable the plane. */
4842         intel_wait_for_vblank(dev_priv, crtc->pipe);
4843 }
4844
4845 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4846 {
4847         if (intel_crtc->overlay) {
4848                 struct drm_device *dev = intel_crtc->base.dev;
4849
4850                 mutex_lock(&dev->struct_mutex);
4851                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4852                 mutex_unlock(&dev->struct_mutex);
4853         }
4854
4855         /* Let userspace switch the overlay on again. In most cases userspace
4856          * has to recompute where to put it anyway.
4857          */
4858 }
4859
4860 /**
4861  * intel_post_enable_primary - Perform operations after enabling primary plane
4862  * @crtc: the CRTC whose primary plane was just enabled
4863  *
4864  * Performs potentially sleeping operations that must be done after the primary
4865  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4866  * called due to an explicit primary plane update, or due to an implicit
4867  * re-enable that is caused when a sprite plane is updated to no longer
4868  * completely hide the primary plane.
4869  */
4870 static void
4871 intel_post_enable_primary(struct drm_crtc *crtc)
4872 {
4873         struct drm_device *dev = crtc->dev;
4874         struct drm_i915_private *dev_priv = to_i915(dev);
4875         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4876         int pipe = intel_crtc->pipe;
4877
4878         /*
4879          * FIXME IPS should be fine as long as one plane is
4880          * enabled, but in practice it seems to have problems
4881          * when going from primary only to sprite only and vice
4882          * versa.
4883          */
4884         hsw_enable_ips(intel_crtc);
4885
4886         /*
4887          * Gen2 reports pipe underruns whenever all planes are disabled.
4888          * So don't enable underrun reporting before at least some planes
4889          * are enabled.
4890          * FIXME: Need to fix the logic to work when we turn off all planes
4891          * but leave the pipe running.
4892          */
4893         if (IS_GEN2(dev_priv))
4894                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4895
4896         /* Underruns don't always raise interrupts, so check manually. */
4897         intel_check_cpu_fifo_underruns(dev_priv);
4898         intel_check_pch_fifo_underruns(dev_priv);
4899 }
4900
4901 /* FIXME move all this to pre_plane_update() with proper state tracking */
4902 static void
4903 intel_pre_disable_primary(struct drm_crtc *crtc)
4904 {
4905         struct drm_device *dev = crtc->dev;
4906         struct drm_i915_private *dev_priv = to_i915(dev);
4907         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4908         int pipe = intel_crtc->pipe;
4909
4910         /*
4911          * Gen2 reports pipe underruns whenever all planes are disabled.
4912          * So diasble underrun reporting before all the planes get disabled.
4913          * FIXME: Need to fix the logic to work when we turn off all planes
4914          * but leave the pipe running.
4915          */
4916         if (IS_GEN2(dev_priv))
4917                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4918
4919         /*
4920          * FIXME IPS should be fine as long as one plane is
4921          * enabled, but in practice it seems to have problems
4922          * when going from primary only to sprite only and vice
4923          * versa.
4924          */
4925         hsw_disable_ips(intel_crtc);
4926 }
4927
4928 /* FIXME get rid of this and use pre_plane_update */
4929 static void
4930 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4931 {
4932         struct drm_device *dev = crtc->dev;
4933         struct drm_i915_private *dev_priv = to_i915(dev);
4934         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4935         int pipe = intel_crtc->pipe;
4936
4937         intel_pre_disable_primary(crtc);
4938
4939         /*
4940          * Vblank time updates from the shadow to live plane control register
4941          * are blocked if the memory self-refresh mode is active at that
4942          * moment. So to make sure the plane gets truly disabled, disable
4943          * first the self-refresh mode. The self-refresh enable bit in turn
4944          * will be checked/applied by the HW only at the next frame start
4945          * event which is after the vblank start event, so we need to have a
4946          * wait-for-vblank between disabling the plane and the pipe.
4947          */
4948         if (HAS_GMCH_DISPLAY(dev_priv) &&
4949             intel_set_memory_cxsr(dev_priv, false))
4950                 intel_wait_for_vblank(dev_priv, pipe);
4951 }
4952
4953 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4954 {
4955         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4956         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4957         struct intel_crtc_state *pipe_config =
4958                 to_intel_crtc_state(crtc->base.state);
4959         struct drm_plane *primary = crtc->base.primary;
4960         struct drm_plane_state *old_pri_state =
4961                 drm_atomic_get_existing_plane_state(old_state, primary);
4962
4963         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
4964
4965         if (pipe_config->update_wm_post && pipe_config->base.active)
4966                 intel_update_watermarks(crtc);
4967
4968         if (old_pri_state) {
4969                 struct intel_plane_state *primary_state =
4970                         to_intel_plane_state(primary->state);
4971                 struct intel_plane_state *old_primary_state =
4972                         to_intel_plane_state(old_pri_state);
4973
4974                 intel_fbc_post_update(crtc);
4975
4976                 if (primary_state->base.visible &&
4977                     (needs_modeset(&pipe_config->base) ||
4978                      !old_primary_state->base.visible))
4979                         intel_post_enable_primary(&crtc->base);
4980         }
4981 }
4982
4983 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
4984                                    struct intel_crtc_state *pipe_config)
4985 {
4986         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4987         struct drm_device *dev = crtc->base.dev;
4988         struct drm_i915_private *dev_priv = to_i915(dev);
4989         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4990         struct drm_plane *primary = crtc->base.primary;
4991         struct drm_plane_state *old_pri_state =
4992                 drm_atomic_get_existing_plane_state(old_state, primary);
4993         bool modeset = needs_modeset(&pipe_config->base);
4994         struct intel_atomic_state *old_intel_state =
4995                 to_intel_atomic_state(old_state);
4996
4997         if (old_pri_state) {
4998                 struct intel_plane_state *primary_state =
4999                         to_intel_plane_state(primary->state);
5000                 struct intel_plane_state *old_primary_state =
5001                         to_intel_plane_state(old_pri_state);
5002
5003                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5004
5005                 if (old_primary_state->base.visible &&
5006                     (modeset || !primary_state->base.visible))
5007                         intel_pre_disable_primary(&crtc->base);
5008         }
5009
5010         /*
5011          * Vblank time updates from the shadow to live plane control register
5012          * are blocked if the memory self-refresh mode is active at that
5013          * moment. So to make sure the plane gets truly disabled, disable
5014          * first the self-refresh mode. The self-refresh enable bit in turn
5015          * will be checked/applied by the HW only at the next frame start
5016          * event which is after the vblank start event, so we need to have a
5017          * wait-for-vblank between disabling the plane and the pipe.
5018          */
5019         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5020             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5021                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5022
5023         /*
5024          * IVB workaround: must disable low power watermarks for at least
5025          * one frame before enabling scaling.  LP watermarks can be re-enabled
5026          * when scaling is disabled.
5027          *
5028          * WaCxSRDisabledForSpriteScaling:ivb
5029          */
5030         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5031                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5032
5033         /*
5034          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5035          * watermark programming here.
5036          */
5037         if (needs_modeset(&pipe_config->base))
5038                 return;
5039
5040         /*
5041          * For platforms that support atomic watermarks, program the
5042          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5043          * will be the intermediate values that are safe for both pre- and
5044          * post- vblank; when vblank happens, the 'active' values will be set
5045          * to the final 'target' values and we'll do this again to get the
5046          * optimal watermarks.  For gen9+ platforms, the values we program here
5047          * will be the final target values which will get automatically latched
5048          * at vblank time; no further programming will be necessary.
5049          *
5050          * If a platform hasn't been transitioned to atomic watermarks yet,
5051          * we'll continue to update watermarks the old way, if flags tell
5052          * us to.
5053          */
5054         if (dev_priv->display.initial_watermarks != NULL)
5055                 dev_priv->display.initial_watermarks(old_intel_state,
5056                                                      pipe_config);
5057         else if (pipe_config->update_wm_pre)
5058                 intel_update_watermarks(crtc);
5059 }
5060
5061 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5062 {
5063         struct drm_device *dev = crtc->dev;
5064         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5065         struct drm_plane *p;
5066         int pipe = intel_crtc->pipe;
5067
5068         intel_crtc_dpms_overlay_disable(intel_crtc);
5069
5070         drm_for_each_plane_mask(p, dev, plane_mask)
5071                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5072
5073         /*
5074          * FIXME: Once we grow proper nuclear flip support out of this we need
5075          * to compute the mask of flip planes precisely. For the time being
5076          * consider this a flip to a NULL plane.
5077          */
5078         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5079 }
5080
5081 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5082                                           struct intel_crtc_state *crtc_state,
5083                                           struct drm_atomic_state *old_state)
5084 {
5085         struct drm_connector_state *conn_state;
5086         struct drm_connector *conn;
5087         int i;
5088
5089         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5090                 struct intel_encoder *encoder =
5091                         to_intel_encoder(conn_state->best_encoder);
5092
5093                 if (conn_state->crtc != crtc)
5094                         continue;
5095
5096                 if (encoder->pre_pll_enable)
5097                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5098         }
5099 }
5100
5101 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5102                                       struct intel_crtc_state *crtc_state,
5103                                       struct drm_atomic_state *old_state)
5104 {
5105         struct drm_connector_state *conn_state;
5106         struct drm_connector *conn;
5107         int i;
5108
5109         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5110                 struct intel_encoder *encoder =
5111                         to_intel_encoder(conn_state->best_encoder);
5112
5113                 if (conn_state->crtc != crtc)
5114                         continue;
5115
5116                 if (encoder->pre_enable)
5117                         encoder->pre_enable(encoder, crtc_state, conn_state);
5118         }
5119 }
5120
5121 static void intel_encoders_enable(struct drm_crtc *crtc,
5122                                   struct intel_crtc_state *crtc_state,
5123                                   struct drm_atomic_state *old_state)
5124 {
5125         struct drm_connector_state *conn_state;
5126         struct drm_connector *conn;
5127         int i;
5128
5129         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5130                 struct intel_encoder *encoder =
5131                         to_intel_encoder(conn_state->best_encoder);
5132
5133                 if (conn_state->crtc != crtc)
5134                         continue;
5135
5136                 encoder->enable(encoder, crtc_state, conn_state);
5137                 intel_opregion_notify_encoder(encoder, true);
5138         }
5139 }
5140
5141 static void intel_encoders_disable(struct drm_crtc *crtc,
5142                                    struct intel_crtc_state *old_crtc_state,
5143                                    struct drm_atomic_state *old_state)
5144 {
5145         struct drm_connector_state *old_conn_state;
5146         struct drm_connector *conn;
5147         int i;
5148
5149         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5150                 struct intel_encoder *encoder =
5151                         to_intel_encoder(old_conn_state->best_encoder);
5152
5153                 if (old_conn_state->crtc != crtc)
5154                         continue;
5155
5156                 intel_opregion_notify_encoder(encoder, false);
5157                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5158         }
5159 }
5160
5161 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5162                                         struct intel_crtc_state *old_crtc_state,
5163                                         struct drm_atomic_state *old_state)
5164 {
5165         struct drm_connector_state *old_conn_state;
5166         struct drm_connector *conn;
5167         int i;
5168
5169         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5170                 struct intel_encoder *encoder =
5171                         to_intel_encoder(old_conn_state->best_encoder);
5172
5173                 if (old_conn_state->crtc != crtc)
5174                         continue;
5175
5176                 if (encoder->post_disable)
5177                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5178         }
5179 }
5180
5181 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5182                                             struct intel_crtc_state *old_crtc_state,
5183                                             struct drm_atomic_state *old_state)
5184 {
5185         struct drm_connector_state *old_conn_state;
5186         struct drm_connector *conn;
5187         int i;
5188
5189         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5190                 struct intel_encoder *encoder =
5191                         to_intel_encoder(old_conn_state->best_encoder);
5192
5193                 if (old_conn_state->crtc != crtc)
5194                         continue;
5195
5196                 if (encoder->post_pll_disable)
5197                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5198         }
5199 }
5200
5201 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5202                                  struct drm_atomic_state *old_state)
5203 {
5204         struct drm_crtc *crtc = pipe_config->base.crtc;
5205         struct drm_device *dev = crtc->dev;
5206         struct drm_i915_private *dev_priv = to_i915(dev);
5207         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5208         int pipe = intel_crtc->pipe;
5209         struct intel_atomic_state *old_intel_state =
5210                 to_intel_atomic_state(old_state);
5211
5212         if (WARN_ON(intel_crtc->active))
5213                 return;
5214
5215         /*
5216          * Sometimes spurious CPU pipe underruns happen during FDI
5217          * training, at least with VGA+HDMI cloning. Suppress them.
5218          *
5219          * On ILK we get an occasional spurious CPU pipe underruns
5220          * between eDP port A enable and vdd enable. Also PCH port
5221          * enable seems to result in the occasional CPU pipe underrun.
5222          *
5223          * Spurious PCH underruns also occur during PCH enabling.
5224          */
5225         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5226                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5227         if (intel_crtc->config->has_pch_encoder)
5228                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5229
5230         if (intel_crtc->config->has_pch_encoder)
5231                 intel_prepare_shared_dpll(intel_crtc);
5232
5233         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5234                 intel_dp_set_m_n(intel_crtc, M1_N1);
5235
5236         intel_set_pipe_timings(intel_crtc);
5237         intel_set_pipe_src_size(intel_crtc);
5238
5239         if (intel_crtc->config->has_pch_encoder) {
5240                 intel_cpu_transcoder_set_m_n(intel_crtc,
5241                                      &intel_crtc->config->fdi_m_n, NULL);
5242         }
5243
5244         ironlake_set_pipeconf(crtc);
5245
5246         intel_crtc->active = true;
5247
5248         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5249
5250         if (intel_crtc->config->has_pch_encoder) {
5251                 /* Note: FDI PLL enabling _must_ be done before we enable the
5252                  * cpu pipes, hence this is separate from all the other fdi/pch
5253                  * enabling. */
5254                 ironlake_fdi_pll_enable(intel_crtc);
5255         } else {
5256                 assert_fdi_tx_disabled(dev_priv, pipe);
5257                 assert_fdi_rx_disabled(dev_priv, pipe);
5258         }
5259
5260         ironlake_pfit_enable(intel_crtc);
5261
5262         /*
5263          * On ILK+ LUT must be loaded before the pipe is running but with
5264          * clocks enabled
5265          */
5266         intel_color_load_luts(&pipe_config->base);
5267
5268         if (dev_priv->display.initial_watermarks != NULL)
5269                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5270         intel_enable_pipe(intel_crtc);
5271
5272         if (intel_crtc->config->has_pch_encoder)
5273                 ironlake_pch_enable(pipe_config);
5274
5275         assert_vblank_disabled(crtc);
5276         drm_crtc_vblank_on(crtc);
5277
5278         intel_encoders_enable(crtc, pipe_config, old_state);
5279
5280         if (HAS_PCH_CPT(dev_priv))
5281                 cpt_verify_modeset(dev, intel_crtc->pipe);
5282
5283         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5284         if (intel_crtc->config->has_pch_encoder)
5285                 intel_wait_for_vblank(dev_priv, pipe);
5286         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5287         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5288 }
5289
5290 /* IPS only exists on ULT machines and is tied to pipe A. */
5291 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5292 {
5293         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5294 }
5295
5296 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5297                                 struct drm_atomic_state *old_state)
5298 {
5299         struct drm_crtc *crtc = pipe_config->base.crtc;
5300         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5301         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5302         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5303         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5304         struct intel_atomic_state *old_intel_state =
5305                 to_intel_atomic_state(old_state);
5306
5307         if (WARN_ON(intel_crtc->active))
5308                 return;
5309
5310         if (intel_crtc->config->has_pch_encoder)
5311                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5312                                                       false);
5313
5314         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5315
5316         if (intel_crtc->config->shared_dpll)
5317                 intel_enable_shared_dpll(intel_crtc);
5318
5319         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5320                 intel_dp_set_m_n(intel_crtc, M1_N1);
5321
5322         if (!transcoder_is_dsi(cpu_transcoder))
5323                 intel_set_pipe_timings(intel_crtc);
5324
5325         intel_set_pipe_src_size(intel_crtc);
5326
5327         if (cpu_transcoder != TRANSCODER_EDP &&
5328             !transcoder_is_dsi(cpu_transcoder)) {
5329                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5330                            intel_crtc->config->pixel_multiplier - 1);
5331         }
5332
5333         if (intel_crtc->config->has_pch_encoder) {
5334                 intel_cpu_transcoder_set_m_n(intel_crtc,
5335                                      &intel_crtc->config->fdi_m_n, NULL);
5336         }
5337
5338         if (!transcoder_is_dsi(cpu_transcoder))
5339                 haswell_set_pipeconf(crtc);
5340
5341         haswell_set_pipemisc(crtc);
5342
5343         intel_color_set_csc(&pipe_config->base);
5344
5345         intel_crtc->active = true;
5346
5347         if (intel_crtc->config->has_pch_encoder)
5348                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5349         else
5350                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5351
5352         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5353
5354         if (intel_crtc->config->has_pch_encoder)
5355                 dev_priv->display.fdi_link_train(intel_crtc, pipe_config);
5356
5357         if (!transcoder_is_dsi(cpu_transcoder))
5358                 intel_ddi_enable_pipe_clock(pipe_config);
5359
5360         if (INTEL_GEN(dev_priv) >= 9)
5361                 skylake_pfit_enable(intel_crtc);
5362         else
5363                 ironlake_pfit_enable(intel_crtc);
5364
5365         /*
5366          * On ILK+ LUT must be loaded before the pipe is running but with
5367          * clocks enabled
5368          */
5369         intel_color_load_luts(&pipe_config->base);
5370
5371         intel_ddi_set_pipe_settings(pipe_config);
5372         if (!transcoder_is_dsi(cpu_transcoder))
5373                 intel_ddi_enable_transcoder_func(pipe_config);
5374
5375         if (dev_priv->display.initial_watermarks != NULL)
5376                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5377
5378         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5379         if (!transcoder_is_dsi(cpu_transcoder))
5380                 intel_enable_pipe(intel_crtc);
5381
5382         if (intel_crtc->config->has_pch_encoder)
5383                 lpt_pch_enable(pipe_config);
5384
5385         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5386                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5387
5388         assert_vblank_disabled(crtc);
5389         drm_crtc_vblank_on(crtc);
5390
5391         intel_encoders_enable(crtc, pipe_config, old_state);
5392
5393         if (intel_crtc->config->has_pch_encoder) {
5394                 intel_wait_for_vblank(dev_priv, pipe);
5395                 intel_wait_for_vblank(dev_priv, pipe);
5396                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5397                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5398                                                       true);
5399         }
5400
5401         /* If we change the relative order between pipe/planes enabling, we need
5402          * to change the workaround. */
5403         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5404         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5405                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5406                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5407         }
5408 }
5409
5410 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5411 {
5412         struct drm_device *dev = crtc->base.dev;
5413         struct drm_i915_private *dev_priv = to_i915(dev);
5414         int pipe = crtc->pipe;
5415
5416         /* To avoid upsetting the power well on haswell only disable the pfit if
5417          * it's in use. The hw state code will make sure we get this right. */
5418         if (force || crtc->config->pch_pfit.enabled) {
5419                 I915_WRITE(PF_CTL(pipe), 0);
5420                 I915_WRITE(PF_WIN_POS(pipe), 0);
5421                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5422         }
5423 }
5424
5425 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5426                                   struct drm_atomic_state *old_state)
5427 {
5428         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5429         struct drm_device *dev = crtc->dev;
5430         struct drm_i915_private *dev_priv = to_i915(dev);
5431         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5432         int pipe = intel_crtc->pipe;
5433
5434         /*
5435          * Sometimes spurious CPU pipe underruns happen when the
5436          * pipe is already disabled, but FDI RX/TX is still enabled.
5437          * Happens at least with VGA+HDMI cloning. Suppress them.
5438          */
5439         if (intel_crtc->config->has_pch_encoder) {
5440                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5441                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5442         }
5443
5444         intel_encoders_disable(crtc, old_crtc_state, old_state);
5445
5446         drm_crtc_vblank_off(crtc);
5447         assert_vblank_disabled(crtc);
5448
5449         intel_disable_pipe(intel_crtc);
5450
5451         ironlake_pfit_disable(intel_crtc, false);
5452
5453         if (intel_crtc->config->has_pch_encoder)
5454                 ironlake_fdi_disable(crtc);
5455
5456         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5457
5458         if (intel_crtc->config->has_pch_encoder) {
5459                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5460
5461                 if (HAS_PCH_CPT(dev_priv)) {
5462                         i915_reg_t reg;
5463                         u32 temp;
5464
5465                         /* disable TRANS_DP_CTL */
5466                         reg = TRANS_DP_CTL(pipe);
5467                         temp = I915_READ(reg);
5468                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5469                                   TRANS_DP_PORT_SEL_MASK);
5470                         temp |= TRANS_DP_PORT_SEL_NONE;
5471                         I915_WRITE(reg, temp);
5472
5473                         /* disable DPLL_SEL */
5474                         temp = I915_READ(PCH_DPLL_SEL);
5475                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5476                         I915_WRITE(PCH_DPLL_SEL, temp);
5477                 }
5478
5479                 ironlake_fdi_pll_disable(intel_crtc);
5480         }
5481
5482         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5483         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5484 }
5485
5486 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5487                                  struct drm_atomic_state *old_state)
5488 {
5489         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5490         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5491         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5492         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5493
5494         if (intel_crtc->config->has_pch_encoder)
5495                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5496                                                       false);
5497
5498         intel_encoders_disable(crtc, old_crtc_state, old_state);
5499
5500         drm_crtc_vblank_off(crtc);
5501         assert_vblank_disabled(crtc);
5502
5503         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5504         if (!transcoder_is_dsi(cpu_transcoder))
5505                 intel_disable_pipe(intel_crtc);
5506
5507         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5508                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5509
5510         if (!transcoder_is_dsi(cpu_transcoder))
5511                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5512
5513         if (INTEL_GEN(dev_priv) >= 9)
5514                 skylake_scaler_disable(intel_crtc);
5515         else
5516                 ironlake_pfit_disable(intel_crtc, false);
5517
5518         if (!transcoder_is_dsi(cpu_transcoder))
5519                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5520
5521         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5522
5523         if (old_crtc_state->has_pch_encoder)
5524                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5525                                                       true);
5526 }
5527
5528 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5529 {
5530         struct drm_device *dev = crtc->base.dev;
5531         struct drm_i915_private *dev_priv = to_i915(dev);
5532         struct intel_crtc_state *pipe_config = crtc->config;
5533
5534         if (!pipe_config->gmch_pfit.control)
5535                 return;
5536
5537         /*
5538          * The panel fitter should only be adjusted whilst the pipe is disabled,
5539          * according to register description and PRM.
5540          */
5541         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5542         assert_pipe_disabled(dev_priv, crtc->pipe);
5543
5544         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5545         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5546
5547         /* Border color in case we don't scale up to the full screen. Black by
5548          * default, change to something else for debugging. */
5549         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5550 }
5551
5552 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5553 {
5554         switch (port) {
5555         case PORT_A:
5556                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5557         case PORT_B:
5558                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5559         case PORT_C:
5560                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5561         case PORT_D:
5562                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5563         case PORT_E:
5564                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5565         default:
5566                 MISSING_CASE(port);
5567                 return POWER_DOMAIN_PORT_OTHER;
5568         }
5569 }
5570
5571 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5572                                   struct intel_crtc_state *crtc_state)
5573 {
5574         struct drm_device *dev = crtc->dev;
5575         struct drm_i915_private *dev_priv = to_i915(dev);
5576         struct drm_encoder *encoder;
5577         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5578         enum pipe pipe = intel_crtc->pipe;
5579         u64 mask;
5580         enum transcoder transcoder = crtc_state->cpu_transcoder;
5581
5582         if (!crtc_state->base.active)
5583                 return 0;
5584
5585         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5586         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5587         if (crtc_state->pch_pfit.enabled ||
5588             crtc_state->pch_pfit.force_thru)
5589                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5590
5591         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5592                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5593
5594                 mask |= BIT_ULL(intel_encoder->power_domain);
5595         }
5596
5597         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5598                 mask |= BIT(POWER_DOMAIN_AUDIO);
5599
5600         if (crtc_state->shared_dpll)
5601                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5602
5603         return mask;
5604 }
5605
5606 static u64
5607 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5608                                struct intel_crtc_state *crtc_state)
5609 {
5610         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5611         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5612         enum intel_display_power_domain domain;
5613         u64 domains, new_domains, old_domains;
5614
5615         old_domains = intel_crtc->enabled_power_domains;
5616         intel_crtc->enabled_power_domains = new_domains =
5617                 get_crtc_power_domains(crtc, crtc_state);
5618
5619         domains = new_domains & ~old_domains;
5620
5621         for_each_power_domain(domain, domains)
5622                 intel_display_power_get(dev_priv, domain);
5623
5624         return old_domains & ~new_domains;
5625 }
5626
5627 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5628                                       u64 domains)
5629 {
5630         enum intel_display_power_domain domain;
5631
5632         for_each_power_domain(domain, domains)
5633                 intel_display_power_put(dev_priv, domain);
5634 }
5635
5636 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5637                                    struct drm_atomic_state *old_state)
5638 {
5639         struct intel_atomic_state *old_intel_state =
5640                 to_intel_atomic_state(old_state);
5641         struct drm_crtc *crtc = pipe_config->base.crtc;
5642         struct drm_device *dev = crtc->dev;
5643         struct drm_i915_private *dev_priv = to_i915(dev);
5644         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5645         int pipe = intel_crtc->pipe;
5646
5647         if (WARN_ON(intel_crtc->active))
5648                 return;
5649
5650         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5651                 intel_dp_set_m_n(intel_crtc, M1_N1);
5652
5653         intel_set_pipe_timings(intel_crtc);
5654         intel_set_pipe_src_size(intel_crtc);
5655
5656         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5657                 struct drm_i915_private *dev_priv = to_i915(dev);
5658
5659                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5660                 I915_WRITE(CHV_CANVAS(pipe), 0);
5661         }
5662
5663         i9xx_set_pipeconf(intel_crtc);
5664
5665         intel_crtc->active = true;
5666
5667         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5668
5669         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5670
5671         if (IS_CHERRYVIEW(dev_priv)) {
5672                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5673                 chv_enable_pll(intel_crtc, intel_crtc->config);
5674         } else {
5675                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5676                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5677         }
5678
5679         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5680
5681         i9xx_pfit_enable(intel_crtc);
5682
5683         intel_color_load_luts(&pipe_config->base);
5684
5685         dev_priv->display.initial_watermarks(old_intel_state,
5686                                              pipe_config);
5687         intel_enable_pipe(intel_crtc);
5688
5689         assert_vblank_disabled(crtc);
5690         drm_crtc_vblank_on(crtc);
5691
5692         intel_encoders_enable(crtc, pipe_config, old_state);
5693 }
5694
5695 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5696 {
5697         struct drm_device *dev = crtc->base.dev;
5698         struct drm_i915_private *dev_priv = to_i915(dev);
5699
5700         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5701         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5702 }
5703
5704 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5705                              struct drm_atomic_state *old_state)
5706 {
5707         struct intel_atomic_state *old_intel_state =
5708                 to_intel_atomic_state(old_state);
5709         struct drm_crtc *crtc = pipe_config->base.crtc;
5710         struct drm_device *dev = crtc->dev;
5711         struct drm_i915_private *dev_priv = to_i915(dev);
5712         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5713         enum pipe pipe = intel_crtc->pipe;
5714
5715         if (WARN_ON(intel_crtc->active))
5716                 return;
5717
5718         i9xx_set_pll_dividers(intel_crtc);
5719
5720         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5721                 intel_dp_set_m_n(intel_crtc, M1_N1);
5722
5723         intel_set_pipe_timings(intel_crtc);
5724         intel_set_pipe_src_size(intel_crtc);
5725
5726         i9xx_set_pipeconf(intel_crtc);
5727
5728         intel_crtc->active = true;
5729
5730         if (!IS_GEN2(dev_priv))
5731                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5732
5733         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5734
5735         i9xx_enable_pll(intel_crtc);
5736
5737         i9xx_pfit_enable(intel_crtc);
5738
5739         intel_color_load_luts(&pipe_config->base);
5740
5741         if (dev_priv->display.initial_watermarks != NULL)
5742                 dev_priv->display.initial_watermarks(old_intel_state,
5743                                                      intel_crtc->config);
5744         else
5745                 intel_update_watermarks(intel_crtc);
5746         intel_enable_pipe(intel_crtc);
5747
5748         assert_vblank_disabled(crtc);
5749         drm_crtc_vblank_on(crtc);
5750
5751         intel_encoders_enable(crtc, pipe_config, old_state);
5752 }
5753
5754 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5755 {
5756         struct drm_device *dev = crtc->base.dev;
5757         struct drm_i915_private *dev_priv = to_i915(dev);
5758
5759         if (!crtc->config->gmch_pfit.control)
5760                 return;
5761
5762         assert_pipe_disabled(dev_priv, crtc->pipe);
5763
5764         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5765                          I915_READ(PFIT_CONTROL));
5766         I915_WRITE(PFIT_CONTROL, 0);
5767 }
5768
5769 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5770                               struct drm_atomic_state *old_state)
5771 {
5772         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5773         struct drm_device *dev = crtc->dev;
5774         struct drm_i915_private *dev_priv = to_i915(dev);
5775         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5776         int pipe = intel_crtc->pipe;
5777
5778         /*
5779          * On gen2 planes are double buffered but the pipe isn't, so we must
5780          * wait for planes to fully turn off before disabling the pipe.
5781          */
5782         if (IS_GEN2(dev_priv))
5783                 intel_wait_for_vblank(dev_priv, pipe);
5784
5785         intel_encoders_disable(crtc, old_crtc_state, old_state);
5786
5787         drm_crtc_vblank_off(crtc);
5788         assert_vblank_disabled(crtc);
5789
5790         intel_disable_pipe(intel_crtc);
5791
5792         i9xx_pfit_disable(intel_crtc);
5793
5794         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5795
5796         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
5797                 if (IS_CHERRYVIEW(dev_priv))
5798                         chv_disable_pll(dev_priv, pipe);
5799                 else if (IS_VALLEYVIEW(dev_priv))
5800                         vlv_disable_pll(dev_priv, pipe);
5801                 else
5802                         i9xx_disable_pll(intel_crtc);
5803         }
5804
5805         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5806
5807         if (!IS_GEN2(dev_priv))
5808                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5809
5810         if (!dev_priv->display.initial_watermarks)
5811                 intel_update_watermarks(intel_crtc);
5812
5813         /* clock the pipe down to 640x480@60 to potentially save power */
5814         if (IS_I830(dev_priv))
5815                 i830_enable_pipe(dev_priv, pipe);
5816 }
5817
5818 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
5819                                         struct drm_modeset_acquire_ctx *ctx)
5820 {
5821         struct intel_encoder *encoder;
5822         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5823         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5824         enum intel_display_power_domain domain;
5825         u64 domains;
5826         struct drm_atomic_state *state;
5827         struct intel_crtc_state *crtc_state;
5828         int ret;
5829
5830         if (!intel_crtc->active)
5831                 return;
5832
5833         if (crtc->primary->state->visible) {
5834                 WARN_ON(intel_crtc->flip_work);
5835
5836                 intel_pre_disable_primary_noatomic(crtc);
5837
5838                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
5839                 crtc->primary->state->visible = false;
5840         }
5841
5842         state = drm_atomic_state_alloc(crtc->dev);
5843         if (!state) {
5844                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
5845                               crtc->base.id, crtc->name);
5846                 return;
5847         }
5848
5849         state->acquire_ctx = ctx;
5850
5851         /* Everything's already locked, -EDEADLK can't happen. */
5852         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5853         ret = drm_atomic_add_affected_connectors(state, crtc);
5854
5855         WARN_ON(IS_ERR(crtc_state) || ret);
5856
5857         dev_priv->display.crtc_disable(crtc_state, state);
5858
5859         drm_atomic_state_put(state);
5860
5861         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
5862                       crtc->base.id, crtc->name);
5863
5864         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
5865         crtc->state->active = false;
5866         intel_crtc->active = false;
5867         crtc->enabled = false;
5868         crtc->state->connector_mask = 0;
5869         crtc->state->encoder_mask = 0;
5870
5871         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
5872                 encoder->base.crtc = NULL;
5873
5874         intel_fbc_disable(intel_crtc);
5875         intel_update_watermarks(intel_crtc);
5876         intel_disable_shared_dpll(intel_crtc);
5877
5878         domains = intel_crtc->enabled_power_domains;
5879         for_each_power_domain(domain, domains)
5880                 intel_display_power_put(dev_priv, domain);
5881         intel_crtc->enabled_power_domains = 0;
5882
5883         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
5884         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
5885 }
5886
5887 /*
5888  * turn all crtc's off, but do not adjust state
5889  * This has to be paired with a call to intel_modeset_setup_hw_state.
5890  */
5891 int intel_display_suspend(struct drm_device *dev)
5892 {
5893         struct drm_i915_private *dev_priv = to_i915(dev);
5894         struct drm_atomic_state *state;
5895         int ret;
5896
5897         state = drm_atomic_helper_suspend(dev);
5898         ret = PTR_ERR_OR_ZERO(state);
5899         if (ret)
5900                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
5901         else
5902                 dev_priv->modeset_restore_state = state;
5903         return ret;
5904 }
5905
5906 void intel_encoder_destroy(struct drm_encoder *encoder)
5907 {
5908         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5909
5910         drm_encoder_cleanup(encoder);
5911         kfree(intel_encoder);
5912 }
5913
5914 /* Cross check the actual hw state with our own modeset state tracking (and it's
5915  * internal consistency). */
5916 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
5917                                          struct drm_connector_state *conn_state)
5918 {
5919         struct intel_connector *connector = to_intel_connector(conn_state->connector);
5920
5921         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
5922                       connector->base.base.id,
5923                       connector->base.name);
5924
5925         if (connector->get_hw_state(connector)) {
5926                 struct intel_encoder *encoder = connector->encoder;
5927
5928                 I915_STATE_WARN(!crtc_state,
5929                          "connector enabled without attached crtc\n");
5930
5931                 if (!crtc_state)
5932                         return;
5933
5934                 I915_STATE_WARN(!crtc_state->active,
5935                       "connector is active, but attached crtc isn't\n");
5936
5937                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
5938                         return;
5939
5940                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
5941                         "atomic encoder doesn't match attached encoder\n");
5942
5943                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
5944                         "attached encoder crtc differs from connector crtc\n");
5945         } else {
5946                 I915_STATE_WARN(crtc_state && crtc_state->active,
5947                         "attached crtc is active, but connector isn't\n");
5948                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
5949                         "best encoder set without crtc!\n");
5950         }
5951 }
5952
5953 int intel_connector_init(struct intel_connector *connector)
5954 {
5955         struct intel_digital_connector_state *conn_state;
5956
5957         /*
5958          * Allocate enough memory to hold intel_digital_connector_state,
5959          * This might be a few bytes too many, but for connectors that don't
5960          * need it we'll free the state and allocate a smaller one on the first
5961          * succesful commit anyway.
5962          */
5963         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
5964         if (!conn_state)
5965                 return -ENOMEM;
5966
5967         __drm_atomic_helper_connector_reset(&connector->base,
5968                                             &conn_state->base);
5969
5970         return 0;
5971 }
5972
5973 struct intel_connector *intel_connector_alloc(void)
5974 {
5975         struct intel_connector *connector;
5976
5977         connector = kzalloc(sizeof *connector, GFP_KERNEL);
5978         if (!connector)
5979                 return NULL;
5980
5981         if (intel_connector_init(connector) < 0) {
5982                 kfree(connector);
5983                 return NULL;
5984         }
5985
5986         return connector;
5987 }
5988
5989 /* Simple connector->get_hw_state implementation for encoders that support only
5990  * one connector and no cloning and hence the encoder state determines the state
5991  * of the connector. */
5992 bool intel_connector_get_hw_state(struct intel_connector *connector)
5993 {
5994         enum pipe pipe = 0;
5995         struct intel_encoder *encoder = connector->encoder;
5996
5997         return encoder->get_hw_state(encoder, &pipe);
5998 }
5999
6000 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6001 {
6002         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6003                 return crtc_state->fdi_lanes;
6004
6005         return 0;
6006 }
6007
6008 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6009                                      struct intel_crtc_state *pipe_config)
6010 {
6011         struct drm_i915_private *dev_priv = to_i915(dev);
6012         struct drm_atomic_state *state = pipe_config->base.state;
6013         struct intel_crtc *other_crtc;
6014         struct intel_crtc_state *other_crtc_state;
6015
6016         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6017                       pipe_name(pipe), pipe_config->fdi_lanes);
6018         if (pipe_config->fdi_lanes > 4) {
6019                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6020                               pipe_name(pipe), pipe_config->fdi_lanes);
6021                 return -EINVAL;
6022         }
6023
6024         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6025                 if (pipe_config->fdi_lanes > 2) {
6026                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6027                                       pipe_config->fdi_lanes);
6028                         return -EINVAL;
6029                 } else {
6030                         return 0;
6031                 }
6032         }
6033
6034         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6035                 return 0;
6036
6037         /* Ivybridge 3 pipe is really complicated */
6038         switch (pipe) {
6039         case PIPE_A:
6040                 return 0;
6041         case PIPE_B:
6042                 if (pipe_config->fdi_lanes <= 2)
6043                         return 0;
6044
6045                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6046                 other_crtc_state =
6047                         intel_atomic_get_crtc_state(state, other_crtc);
6048                 if (IS_ERR(other_crtc_state))
6049                         return PTR_ERR(other_crtc_state);
6050
6051                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6052                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6053                                       pipe_name(pipe), pipe_config->fdi_lanes);
6054                         return -EINVAL;
6055                 }
6056                 return 0;
6057         case PIPE_C:
6058                 if (pipe_config->fdi_lanes > 2) {
6059                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6060                                       pipe_name(pipe), pipe_config->fdi_lanes);
6061                         return -EINVAL;
6062                 }
6063
6064                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6065                 other_crtc_state =
6066                         intel_atomic_get_crtc_state(state, other_crtc);
6067                 if (IS_ERR(other_crtc_state))
6068                         return PTR_ERR(other_crtc_state);
6069
6070                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6071                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6072                         return -EINVAL;
6073                 }
6074                 return 0;
6075         default:
6076                 BUG();
6077         }
6078 }
6079
6080 #define RETRY 1
6081 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6082                                        struct intel_crtc_state *pipe_config)
6083 {
6084         struct drm_device *dev = intel_crtc->base.dev;
6085         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6086         int lane, link_bw, fdi_dotclock, ret;
6087         bool needs_recompute = false;
6088
6089 retry:
6090         /* FDI is a binary signal running at ~2.7GHz, encoding
6091          * each output octet as 10 bits. The actual frequency
6092          * is stored as a divider into a 100MHz clock, and the
6093          * mode pixel clock is stored in units of 1KHz.
6094          * Hence the bw of each lane in terms of the mode signal
6095          * is:
6096          */
6097         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6098
6099         fdi_dotclock = adjusted_mode->crtc_clock;
6100
6101         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6102                                            pipe_config->pipe_bpp);
6103
6104         pipe_config->fdi_lanes = lane;
6105
6106         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6107                                link_bw, &pipe_config->fdi_m_n, false);
6108
6109         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6110         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6111                 pipe_config->pipe_bpp -= 2*3;
6112                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6113                               pipe_config->pipe_bpp);
6114                 needs_recompute = true;
6115                 pipe_config->bw_constrained = true;
6116
6117                 goto retry;
6118         }
6119
6120         if (needs_recompute)
6121                 return RETRY;
6122
6123         return ret;
6124 }
6125
6126 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6127                                      struct intel_crtc_state *pipe_config)
6128 {
6129         if (pipe_config->pipe_bpp > 24)
6130                 return false;
6131
6132         /* HSW can handle pixel rate up to cdclk? */
6133         if (IS_HASWELL(dev_priv))
6134                 return true;
6135
6136         /*
6137          * We compare against max which means we must take
6138          * the increased cdclk requirement into account when
6139          * calculating the new cdclk.
6140          *
6141          * Should measure whether using a lower cdclk w/o IPS
6142          */
6143         return pipe_config->pixel_rate <=
6144                 dev_priv->max_cdclk_freq * 95 / 100;
6145 }
6146
6147 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6148                                    struct intel_crtc_state *pipe_config)
6149 {
6150         struct drm_device *dev = crtc->base.dev;
6151         struct drm_i915_private *dev_priv = to_i915(dev);
6152
6153         pipe_config->ips_enabled = i915.enable_ips &&
6154                 hsw_crtc_supports_ips(crtc) &&
6155                 pipe_config_supports_ips(dev_priv, pipe_config);
6156 }
6157
6158 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6159 {
6160         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6161
6162         /* GDG double wide on either pipe, otherwise pipe A only */
6163         return INTEL_INFO(dev_priv)->gen < 4 &&
6164                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6165 }
6166
6167 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6168 {
6169         uint32_t pixel_rate;
6170
6171         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6172
6173         /*
6174          * We only use IF-ID interlacing. If we ever use
6175          * PF-ID we'll need to adjust the pixel_rate here.
6176          */
6177
6178         if (pipe_config->pch_pfit.enabled) {
6179                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6180                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6181
6182                 pipe_w = pipe_config->pipe_src_w;
6183                 pipe_h = pipe_config->pipe_src_h;
6184
6185                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6186                 pfit_h = pfit_size & 0xFFFF;
6187                 if (pipe_w < pfit_w)
6188                         pipe_w = pfit_w;
6189                 if (pipe_h < pfit_h)
6190                         pipe_h = pfit_h;
6191
6192                 if (WARN_ON(!pfit_w || !pfit_h))
6193                         return pixel_rate;
6194
6195                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6196                                      pfit_w * pfit_h);
6197         }
6198
6199         return pixel_rate;
6200 }
6201
6202 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6203 {
6204         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6205
6206         if (HAS_GMCH_DISPLAY(dev_priv))
6207                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6208                 crtc_state->pixel_rate =
6209                         crtc_state->base.adjusted_mode.crtc_clock;
6210         else
6211                 crtc_state->pixel_rate =
6212                         ilk_pipe_pixel_rate(crtc_state);
6213 }
6214
6215 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6216                                      struct intel_crtc_state *pipe_config)
6217 {
6218         struct drm_device *dev = crtc->base.dev;
6219         struct drm_i915_private *dev_priv = to_i915(dev);
6220         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6221         int clock_limit = dev_priv->max_dotclk_freq;
6222
6223         if (INTEL_GEN(dev_priv) < 4) {
6224                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6225
6226                 /*
6227                  * Enable double wide mode when the dot clock
6228                  * is > 90% of the (display) core speed.
6229                  */
6230                 if (intel_crtc_supports_double_wide(crtc) &&
6231                     adjusted_mode->crtc_clock > clock_limit) {
6232                         clock_limit = dev_priv->max_dotclk_freq;
6233                         pipe_config->double_wide = true;
6234                 }
6235         }
6236
6237         if (adjusted_mode->crtc_clock > clock_limit) {
6238                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6239                               adjusted_mode->crtc_clock, clock_limit,
6240                               yesno(pipe_config->double_wide));
6241                 return -EINVAL;
6242         }
6243
6244         /*
6245          * Pipe horizontal size must be even in:
6246          * - DVO ganged mode
6247          * - LVDS dual channel mode
6248          * - Double wide pipe
6249          */
6250         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6251              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6252                 pipe_config->pipe_src_w &= ~1;
6253
6254         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6255          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6256          */
6257         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6258                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6259                 return -EINVAL;
6260
6261         intel_crtc_compute_pixel_rate(pipe_config);
6262
6263         if (HAS_IPS(dev_priv))
6264                 hsw_compute_ips_config(crtc, pipe_config);
6265
6266         if (pipe_config->has_pch_encoder)
6267                 return ironlake_fdi_compute_config(crtc, pipe_config);
6268
6269         return 0;
6270 }
6271
6272 static void
6273 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6274 {
6275         while (*num > DATA_LINK_M_N_MASK ||
6276                *den > DATA_LINK_M_N_MASK) {
6277                 *num >>= 1;
6278                 *den >>= 1;
6279         }
6280 }
6281
6282 static void compute_m_n(unsigned int m, unsigned int n,
6283                         uint32_t *ret_m, uint32_t *ret_n,
6284                         bool reduce_m_n)
6285 {
6286         /*
6287          * Reduce M/N as much as possible without loss in precision. Several DP
6288          * dongles in particular seem to be fussy about too large *link* M/N
6289          * values. The passed in values are more likely to have the least
6290          * significant bits zero than M after rounding below, so do this first.
6291          */
6292         if (reduce_m_n) {
6293                 while ((m & 1) == 0 && (n & 1) == 0) {
6294                         m >>= 1;
6295                         n >>= 1;
6296                 }
6297         }
6298
6299         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6300         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6301         intel_reduce_m_n_ratio(ret_m, ret_n);
6302 }
6303
6304 void
6305 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6306                        int pixel_clock, int link_clock,
6307                        struct intel_link_m_n *m_n,
6308                        bool reduce_m_n)
6309 {
6310         m_n->tu = 64;
6311
6312         compute_m_n(bits_per_pixel * pixel_clock,
6313                     link_clock * nlanes * 8,
6314                     &m_n->gmch_m, &m_n->gmch_n,
6315                     reduce_m_n);
6316
6317         compute_m_n(pixel_clock, link_clock,
6318                     &m_n->link_m, &m_n->link_n,
6319                     reduce_m_n);
6320 }
6321
6322 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6323 {
6324         if (i915.panel_use_ssc >= 0)
6325                 return i915.panel_use_ssc != 0;
6326         return dev_priv->vbt.lvds_use_ssc
6327                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6328 }
6329
6330 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6331 {
6332         return (1 << dpll->n) << 16 | dpll->m2;
6333 }
6334
6335 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6336 {
6337         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6338 }
6339
6340 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6341                                      struct intel_crtc_state *crtc_state,
6342                                      struct dpll *reduced_clock)
6343 {
6344         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6345         u32 fp, fp2 = 0;
6346
6347         if (IS_PINEVIEW(dev_priv)) {
6348                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6349                 if (reduced_clock)
6350                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6351         } else {
6352                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6353                 if (reduced_clock)
6354                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6355         }
6356
6357         crtc_state->dpll_hw_state.fp0 = fp;
6358
6359         crtc->lowfreq_avail = false;
6360         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6361             reduced_clock) {
6362                 crtc_state->dpll_hw_state.fp1 = fp2;
6363                 crtc->lowfreq_avail = true;
6364         } else {
6365                 crtc_state->dpll_hw_state.fp1 = fp;
6366         }
6367 }
6368
6369 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6370                 pipe)
6371 {
6372         u32 reg_val;
6373
6374         /*
6375          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6376          * and set it to a reasonable value instead.
6377          */
6378         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6379         reg_val &= 0xffffff00;
6380         reg_val |= 0x00000030;
6381         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6382
6383         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6384         reg_val &= 0x00ffffff;
6385         reg_val |= 0x8c000000;
6386         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6387
6388         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6389         reg_val &= 0xffffff00;
6390         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6391
6392         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6393         reg_val &= 0x00ffffff;
6394         reg_val |= 0xb0000000;
6395         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6396 }
6397
6398 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6399                                          struct intel_link_m_n *m_n)
6400 {
6401         struct drm_device *dev = crtc->base.dev;
6402         struct drm_i915_private *dev_priv = to_i915(dev);
6403         int pipe = crtc->pipe;
6404
6405         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6406         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6407         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6408         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6409 }
6410
6411 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6412                                          struct intel_link_m_n *m_n,
6413                                          struct intel_link_m_n *m2_n2)
6414 {
6415         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6416         int pipe = crtc->pipe;
6417         enum transcoder transcoder = crtc->config->cpu_transcoder;
6418
6419         if (INTEL_GEN(dev_priv) >= 5) {
6420                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6421                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6422                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6423                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6424                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6425                  * for gen < 8) and if DRRS is supported (to make sure the
6426                  * registers are not unnecessarily accessed).
6427                  */
6428                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6429                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6430                         I915_WRITE(PIPE_DATA_M2(transcoder),
6431                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6432                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6433                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6434                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6435                 }
6436         } else {
6437                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6438                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6439                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6440                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6441         }
6442 }
6443
6444 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6445 {
6446         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6447
6448         if (m_n == M1_N1) {
6449                 dp_m_n = &crtc->config->dp_m_n;
6450                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6451         } else if (m_n == M2_N2) {
6452
6453                 /*
6454                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6455                  * needs to be programmed into M1_N1.
6456                  */
6457                 dp_m_n = &crtc->config->dp_m2_n2;
6458         } else {
6459                 DRM_ERROR("Unsupported divider value\n");
6460                 return;
6461         }
6462
6463         if (crtc->config->has_pch_encoder)
6464                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6465         else
6466                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6467 }
6468
6469 static void vlv_compute_dpll(struct intel_crtc *crtc,
6470                              struct intel_crtc_state *pipe_config)
6471 {
6472         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6473                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6474         if (crtc->pipe != PIPE_A)
6475                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6476
6477         /* DPLL not used with DSI, but still need the rest set up */
6478         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6479                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6480                         DPLL_EXT_BUFFER_ENABLE_VLV;
6481
6482         pipe_config->dpll_hw_state.dpll_md =
6483                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6484 }
6485
6486 static void chv_compute_dpll(struct intel_crtc *crtc,
6487                              struct intel_crtc_state *pipe_config)
6488 {
6489         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6490                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6491         if (crtc->pipe != PIPE_A)
6492                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6493
6494         /* DPLL not used with DSI, but still need the rest set up */
6495         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6496                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6497
6498         pipe_config->dpll_hw_state.dpll_md =
6499                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6500 }
6501
6502 static void vlv_prepare_pll(struct intel_crtc *crtc,
6503                             const struct intel_crtc_state *pipe_config)
6504 {
6505         struct drm_device *dev = crtc->base.dev;
6506         struct drm_i915_private *dev_priv = to_i915(dev);
6507         enum pipe pipe = crtc->pipe;
6508         u32 mdiv;
6509         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6510         u32 coreclk, reg_val;
6511
6512         /* Enable Refclk */
6513         I915_WRITE(DPLL(pipe),
6514                    pipe_config->dpll_hw_state.dpll &
6515                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6516
6517         /* No need to actually set up the DPLL with DSI */
6518         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6519                 return;
6520
6521         mutex_lock(&dev_priv->sb_lock);
6522
6523         bestn = pipe_config->dpll.n;
6524         bestm1 = pipe_config->dpll.m1;
6525         bestm2 = pipe_config->dpll.m2;
6526         bestp1 = pipe_config->dpll.p1;
6527         bestp2 = pipe_config->dpll.p2;
6528
6529         /* See eDP HDMI DPIO driver vbios notes doc */
6530
6531         /* PLL B needs special handling */
6532         if (pipe == PIPE_B)
6533                 vlv_pllb_recal_opamp(dev_priv, pipe);
6534
6535         /* Set up Tx target for periodic Rcomp update */
6536         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6537
6538         /* Disable target IRef on PLL */
6539         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6540         reg_val &= 0x00ffffff;
6541         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6542
6543         /* Disable fast lock */
6544         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6545
6546         /* Set idtafcrecal before PLL is enabled */
6547         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6548         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6549         mdiv |= ((bestn << DPIO_N_SHIFT));
6550         mdiv |= (1 << DPIO_K_SHIFT);
6551
6552         /*
6553          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6554          * but we don't support that).
6555          * Note: don't use the DAC post divider as it seems unstable.
6556          */
6557         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6558         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6559
6560         mdiv |= DPIO_ENABLE_CALIBRATION;
6561         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6562
6563         /* Set HBR and RBR LPF coefficients */
6564         if (pipe_config->port_clock == 162000 ||
6565             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6566             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6567                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6568                                  0x009f0003);
6569         else
6570                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6571                                  0x00d0000f);
6572
6573         if (intel_crtc_has_dp_encoder(pipe_config)) {
6574                 /* Use SSC source */
6575                 if (pipe == PIPE_A)
6576                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6577                                          0x0df40000);
6578                 else
6579                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6580                                          0x0df70000);
6581         } else { /* HDMI or VGA */
6582                 /* Use bend source */
6583                 if (pipe == PIPE_A)
6584                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6585                                          0x0df70000);
6586                 else
6587                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6588                                          0x0df40000);
6589         }
6590
6591         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6592         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6593         if (intel_crtc_has_dp_encoder(crtc->config))
6594                 coreclk |= 0x01000000;
6595         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6596
6597         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6598         mutex_unlock(&dev_priv->sb_lock);
6599 }
6600
6601 static void chv_prepare_pll(struct intel_crtc *crtc,
6602                             const struct intel_crtc_state *pipe_config)
6603 {
6604         struct drm_device *dev = crtc->base.dev;
6605         struct drm_i915_private *dev_priv = to_i915(dev);
6606         enum pipe pipe = crtc->pipe;
6607         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6608         u32 loopfilter, tribuf_calcntr;
6609         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6610         u32 dpio_val;
6611         int vco;
6612
6613         /* Enable Refclk and SSC */
6614         I915_WRITE(DPLL(pipe),
6615                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6616
6617         /* No need to actually set up the DPLL with DSI */
6618         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6619                 return;
6620
6621         bestn = pipe_config->dpll.n;
6622         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6623         bestm1 = pipe_config->dpll.m1;
6624         bestm2 = pipe_config->dpll.m2 >> 22;
6625         bestp1 = pipe_config->dpll.p1;
6626         bestp2 = pipe_config->dpll.p2;
6627         vco = pipe_config->dpll.vco;
6628         dpio_val = 0;
6629         loopfilter = 0;
6630
6631         mutex_lock(&dev_priv->sb_lock);
6632
6633         /* p1 and p2 divider */
6634         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6635                         5 << DPIO_CHV_S1_DIV_SHIFT |
6636                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6637                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6638                         1 << DPIO_CHV_K_DIV_SHIFT);
6639
6640         /* Feedback post-divider - m2 */
6641         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6642
6643         /* Feedback refclk divider - n and m1 */
6644         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6645                         DPIO_CHV_M1_DIV_BY_2 |
6646                         1 << DPIO_CHV_N_DIV_SHIFT);
6647
6648         /* M2 fraction division */
6649         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6650
6651         /* M2 fraction division enable */
6652         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6653         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6654         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6655         if (bestm2_frac)
6656                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6657         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6658
6659         /* Program digital lock detect threshold */
6660         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6661         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6662                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6663         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6664         if (!bestm2_frac)
6665                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6666         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6667
6668         /* Loop filter */
6669         if (vco == 5400000) {
6670                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6671                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6672                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6673                 tribuf_calcntr = 0x9;
6674         } else if (vco <= 6200000) {
6675                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6676                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6677                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6678                 tribuf_calcntr = 0x9;
6679         } else if (vco <= 6480000) {
6680                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6681                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6682                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6683                 tribuf_calcntr = 0x8;
6684         } else {
6685                 /* Not supported. Apply the same limits as in the max case */
6686                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6687                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6688                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6689                 tribuf_calcntr = 0;
6690         }
6691         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6692
6693         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6694         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6695         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6696         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6697
6698         /* AFC Recal */
6699         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6700                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6701                         DPIO_AFC_RECAL);
6702
6703         mutex_unlock(&dev_priv->sb_lock);
6704 }
6705
6706 /**
6707  * vlv_force_pll_on - forcibly enable just the PLL
6708  * @dev_priv: i915 private structure
6709  * @pipe: pipe PLL to enable
6710  * @dpll: PLL configuration
6711  *
6712  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6713  * in cases where we need the PLL enabled even when @pipe is not going to
6714  * be enabled.
6715  */
6716 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6717                      const struct dpll *dpll)
6718 {
6719         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6720         struct intel_crtc_state *pipe_config;
6721
6722         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6723         if (!pipe_config)
6724                 return -ENOMEM;
6725
6726         pipe_config->base.crtc = &crtc->base;
6727         pipe_config->pixel_multiplier = 1;
6728         pipe_config->dpll = *dpll;
6729
6730         if (IS_CHERRYVIEW(dev_priv)) {
6731                 chv_compute_dpll(crtc, pipe_config);
6732                 chv_prepare_pll(crtc, pipe_config);
6733                 chv_enable_pll(crtc, pipe_config);
6734         } else {
6735                 vlv_compute_dpll(crtc, pipe_config);
6736                 vlv_prepare_pll(crtc, pipe_config);
6737                 vlv_enable_pll(crtc, pipe_config);
6738         }
6739
6740         kfree(pipe_config);
6741
6742         return 0;
6743 }
6744
6745 /**
6746  * vlv_force_pll_off - forcibly disable just the PLL
6747  * @dev_priv: i915 private structure
6748  * @pipe: pipe PLL to disable
6749  *
6750  * Disable the PLL for @pipe. To be used in cases where we need
6751  * the PLL enabled even when @pipe is not going to be enabled.
6752  */
6753 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
6754 {
6755         if (IS_CHERRYVIEW(dev_priv))
6756                 chv_disable_pll(dev_priv, pipe);
6757         else
6758                 vlv_disable_pll(dev_priv, pipe);
6759 }
6760
6761 static void i9xx_compute_dpll(struct intel_crtc *crtc,
6762                               struct intel_crtc_state *crtc_state,
6763                               struct dpll *reduced_clock)
6764 {
6765         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6766         u32 dpll;
6767         struct dpll *clock = &crtc_state->dpll;
6768
6769         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6770
6771         dpll = DPLL_VGA_MODE_DIS;
6772
6773         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
6774                 dpll |= DPLLB_MODE_LVDS;
6775         else
6776                 dpll |= DPLLB_MODE_DAC_SERIAL;
6777
6778         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
6779             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
6780                 dpll |= (crtc_state->pixel_multiplier - 1)
6781                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6782         }
6783
6784         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
6785             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
6786                 dpll |= DPLL_SDVO_HIGH_SPEED;
6787
6788         if (intel_crtc_has_dp_encoder(crtc_state))
6789                 dpll |= DPLL_SDVO_HIGH_SPEED;
6790
6791         /* compute bitmask from p1 value */
6792         if (IS_PINEVIEW(dev_priv))
6793                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6794         else {
6795                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6796                 if (IS_G4X(dev_priv) && reduced_clock)
6797                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6798         }
6799         switch (clock->p2) {
6800         case 5:
6801                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6802                 break;
6803         case 7:
6804                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6805                 break;
6806         case 10:
6807                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6808                 break;
6809         case 14:
6810                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6811                 break;
6812         }
6813         if (INTEL_GEN(dev_priv) >= 4)
6814                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6815
6816         if (crtc_state->sdvo_tv_clock)
6817                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6818         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6819                  intel_panel_use_ssc(dev_priv))
6820                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6821         else
6822                 dpll |= PLL_REF_INPUT_DREFCLK;
6823
6824         dpll |= DPLL_VCO_ENABLE;
6825         crtc_state->dpll_hw_state.dpll = dpll;
6826
6827         if (INTEL_GEN(dev_priv) >= 4) {
6828                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6829                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6830                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
6831         }
6832 }
6833
6834 static void i8xx_compute_dpll(struct intel_crtc *crtc,
6835                               struct intel_crtc_state *crtc_state,
6836                               struct dpll *reduced_clock)
6837 {
6838         struct drm_device *dev = crtc->base.dev;
6839         struct drm_i915_private *dev_priv = to_i915(dev);
6840         u32 dpll;
6841         struct dpll *clock = &crtc_state->dpll;
6842
6843         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6844
6845         dpll = DPLL_VGA_MODE_DIS;
6846
6847         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
6848                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6849         } else {
6850                 if (clock->p1 == 2)
6851                         dpll |= PLL_P1_DIVIDE_BY_TWO;
6852                 else
6853                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6854                 if (clock->p2 == 4)
6855                         dpll |= PLL_P2_DIVIDE_BY_4;
6856         }
6857
6858         if (!IS_I830(dev_priv) &&
6859             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
6860                 dpll |= DPLL_DVO_2X_MODE;
6861
6862         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6863             intel_panel_use_ssc(dev_priv))
6864                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6865         else
6866                 dpll |= PLL_REF_INPUT_DREFCLK;
6867
6868         dpll |= DPLL_VCO_ENABLE;
6869         crtc_state->dpll_hw_state.dpll = dpll;
6870 }
6871
6872 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
6873 {
6874         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
6875         enum pipe pipe = intel_crtc->pipe;
6876         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
6877         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
6878         uint32_t crtc_vtotal, crtc_vblank_end;
6879         int vsyncshift = 0;
6880
6881         /* We need to be careful not to changed the adjusted mode, for otherwise
6882          * the hw state checker will get angry at the mismatch. */
6883         crtc_vtotal = adjusted_mode->crtc_vtotal;
6884         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
6885
6886         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
6887                 /* the chip adds 2 halflines automatically */
6888                 crtc_vtotal -= 1;
6889                 crtc_vblank_end -= 1;
6890
6891                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
6892                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
6893                 else
6894                         vsyncshift = adjusted_mode->crtc_hsync_start -
6895                                 adjusted_mode->crtc_htotal / 2;
6896                 if (vsyncshift < 0)
6897                         vsyncshift += adjusted_mode->crtc_htotal;
6898         }
6899
6900         if (INTEL_GEN(dev_priv) > 3)
6901                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
6902
6903         I915_WRITE(HTOTAL(cpu_transcoder),
6904                    (adjusted_mode->crtc_hdisplay - 1) |
6905                    ((adjusted_mode->crtc_htotal - 1) << 16));
6906         I915_WRITE(HBLANK(cpu_transcoder),
6907                    (adjusted_mode->crtc_hblank_start - 1) |
6908                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
6909         I915_WRITE(HSYNC(cpu_transcoder),
6910                    (adjusted_mode->crtc_hsync_start - 1) |
6911                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
6912
6913         I915_WRITE(VTOTAL(cpu_transcoder),
6914                    (adjusted_mode->crtc_vdisplay - 1) |
6915                    ((crtc_vtotal - 1) << 16));
6916         I915_WRITE(VBLANK(cpu_transcoder),
6917                    (adjusted_mode->crtc_vblank_start - 1) |
6918                    ((crtc_vblank_end - 1) << 16));
6919         I915_WRITE(VSYNC(cpu_transcoder),
6920                    (adjusted_mode->crtc_vsync_start - 1) |
6921                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
6922
6923         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
6924          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
6925          * documented on the DDI_FUNC_CTL register description, EDP Input Select
6926          * bits. */
6927         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
6928             (pipe == PIPE_B || pipe == PIPE_C))
6929                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
6930
6931 }
6932
6933 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
6934 {
6935         struct drm_device *dev = intel_crtc->base.dev;
6936         struct drm_i915_private *dev_priv = to_i915(dev);
6937         enum pipe pipe = intel_crtc->pipe;
6938
6939         /* pipesrc controls the size that is scaled from, which should
6940          * always be the user's requested size.
6941          */
6942         I915_WRITE(PIPESRC(pipe),
6943                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
6944                    (intel_crtc->config->pipe_src_h - 1));
6945 }
6946
6947 static void intel_get_pipe_timings(struct intel_crtc *crtc,
6948                                    struct intel_crtc_state *pipe_config)
6949 {
6950         struct drm_device *dev = crtc->base.dev;
6951         struct drm_i915_private *dev_priv = to_i915(dev);
6952         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
6953         uint32_t tmp;
6954
6955         tmp = I915_READ(HTOTAL(cpu_transcoder));
6956         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
6957         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
6958         tmp = I915_READ(HBLANK(cpu_transcoder));
6959         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
6960         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
6961         tmp = I915_READ(HSYNC(cpu_transcoder));
6962         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
6963         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
6964
6965         tmp = I915_READ(VTOTAL(cpu_transcoder));
6966         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
6967         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
6968         tmp = I915_READ(VBLANK(cpu_transcoder));
6969         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
6970         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
6971         tmp = I915_READ(VSYNC(cpu_transcoder));
6972         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
6973         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
6974
6975         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
6976                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
6977                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
6978                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
6979         }
6980 }
6981
6982 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
6983                                     struct intel_crtc_state *pipe_config)
6984 {
6985         struct drm_device *dev = crtc->base.dev;
6986         struct drm_i915_private *dev_priv = to_i915(dev);
6987         u32 tmp;
6988
6989         tmp = I915_READ(PIPESRC(crtc->pipe));
6990         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
6991         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
6992
6993         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
6994         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
6995 }
6996
6997 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
6998                                  struct intel_crtc_state *pipe_config)
6999 {
7000         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7001         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7002         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7003         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7004
7005         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7006         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7007         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7008         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7009
7010         mode->flags = pipe_config->base.adjusted_mode.flags;
7011         mode->type = DRM_MODE_TYPE_DRIVER;
7012
7013         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7014
7015         mode->hsync = drm_mode_hsync(mode);
7016         mode->vrefresh = drm_mode_vrefresh(mode);
7017         drm_mode_set_name(mode);
7018 }
7019
7020 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7021 {
7022         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7023         uint32_t pipeconf;
7024
7025         pipeconf = 0;
7026
7027         /* we keep both pipes enabled on 830 */
7028         if (IS_I830(dev_priv))
7029                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7030
7031         if (intel_crtc->config->double_wide)
7032                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7033
7034         /* only g4x and later have fancy bpc/dither controls */
7035         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7036             IS_CHERRYVIEW(dev_priv)) {
7037                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7038                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7039                         pipeconf |= PIPECONF_DITHER_EN |
7040                                     PIPECONF_DITHER_TYPE_SP;
7041
7042                 switch (intel_crtc->config->pipe_bpp) {
7043                 case 18:
7044                         pipeconf |= PIPECONF_6BPC;
7045                         break;
7046                 case 24:
7047                         pipeconf |= PIPECONF_8BPC;
7048                         break;
7049                 case 30:
7050                         pipeconf |= PIPECONF_10BPC;
7051                         break;
7052                 default:
7053                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7054                         BUG();
7055                 }
7056         }
7057
7058         if (HAS_PIPE_CXSR(dev_priv)) {
7059                 if (intel_crtc->lowfreq_avail) {
7060                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7061                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7062                 } else {
7063                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7064                 }
7065         }
7066
7067         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7068                 if (INTEL_GEN(dev_priv) < 4 ||
7069                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7070                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7071                 else
7072                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7073         } else
7074                 pipeconf |= PIPECONF_PROGRESSIVE;
7075
7076         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7077              intel_crtc->config->limited_color_range)
7078                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7079
7080         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7081         POSTING_READ(PIPECONF(intel_crtc->pipe));
7082 }
7083
7084 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7085                                    struct intel_crtc_state *crtc_state)
7086 {
7087         struct drm_device *dev = crtc->base.dev;
7088         struct drm_i915_private *dev_priv = to_i915(dev);
7089         const struct intel_limit *limit;
7090         int refclk = 48000;
7091
7092         memset(&crtc_state->dpll_hw_state, 0,
7093                sizeof(crtc_state->dpll_hw_state));
7094
7095         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7096                 if (intel_panel_use_ssc(dev_priv)) {
7097                         refclk = dev_priv->vbt.lvds_ssc_freq;
7098                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7099                 }
7100
7101                 limit = &intel_limits_i8xx_lvds;
7102         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7103                 limit = &intel_limits_i8xx_dvo;
7104         } else {
7105                 limit = &intel_limits_i8xx_dac;
7106         }
7107
7108         if (!crtc_state->clock_set &&
7109             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7110                                  refclk, NULL, &crtc_state->dpll)) {
7111                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7112                 return -EINVAL;
7113         }
7114
7115         i8xx_compute_dpll(crtc, crtc_state, NULL);
7116
7117         return 0;
7118 }
7119
7120 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7121                                   struct intel_crtc_state *crtc_state)
7122 {
7123         struct drm_device *dev = crtc->base.dev;
7124         struct drm_i915_private *dev_priv = to_i915(dev);
7125         const struct intel_limit *limit;
7126         int refclk = 96000;
7127
7128         memset(&crtc_state->dpll_hw_state, 0,
7129                sizeof(crtc_state->dpll_hw_state));
7130
7131         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7132                 if (intel_panel_use_ssc(dev_priv)) {
7133                         refclk = dev_priv->vbt.lvds_ssc_freq;
7134                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7135                 }
7136
7137                 if (intel_is_dual_link_lvds(dev))
7138                         limit = &intel_limits_g4x_dual_channel_lvds;
7139                 else
7140                         limit = &intel_limits_g4x_single_channel_lvds;
7141         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7142                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7143                 limit = &intel_limits_g4x_hdmi;
7144         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7145                 limit = &intel_limits_g4x_sdvo;
7146         } else {
7147                 /* The option is for other outputs */
7148                 limit = &intel_limits_i9xx_sdvo;
7149         }
7150
7151         if (!crtc_state->clock_set &&
7152             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7153                                 refclk, NULL, &crtc_state->dpll)) {
7154                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7155                 return -EINVAL;
7156         }
7157
7158         i9xx_compute_dpll(crtc, crtc_state, NULL);
7159
7160         return 0;
7161 }
7162
7163 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7164                                   struct intel_crtc_state *crtc_state)
7165 {
7166         struct drm_device *dev = crtc->base.dev;
7167         struct drm_i915_private *dev_priv = to_i915(dev);
7168         const struct intel_limit *limit;
7169         int refclk = 96000;
7170
7171         memset(&crtc_state->dpll_hw_state, 0,
7172                sizeof(crtc_state->dpll_hw_state));
7173
7174         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7175                 if (intel_panel_use_ssc(dev_priv)) {
7176                         refclk = dev_priv->vbt.lvds_ssc_freq;
7177                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7178                 }
7179
7180                 limit = &intel_limits_pineview_lvds;
7181         } else {
7182                 limit = &intel_limits_pineview_sdvo;
7183         }
7184
7185         if (!crtc_state->clock_set &&
7186             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7187                                 refclk, NULL, &crtc_state->dpll)) {
7188                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7189                 return -EINVAL;
7190         }
7191
7192         i9xx_compute_dpll(crtc, crtc_state, NULL);
7193
7194         return 0;
7195 }
7196
7197 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7198                                    struct intel_crtc_state *crtc_state)
7199 {
7200         struct drm_device *dev = crtc->base.dev;
7201         struct drm_i915_private *dev_priv = to_i915(dev);
7202         const struct intel_limit *limit;
7203         int refclk = 96000;
7204
7205         memset(&crtc_state->dpll_hw_state, 0,
7206                sizeof(crtc_state->dpll_hw_state));
7207
7208         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7209                 if (intel_panel_use_ssc(dev_priv)) {
7210                         refclk = dev_priv->vbt.lvds_ssc_freq;
7211                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7212                 }
7213
7214                 limit = &intel_limits_i9xx_lvds;
7215         } else {
7216                 limit = &intel_limits_i9xx_sdvo;
7217         }
7218
7219         if (!crtc_state->clock_set &&
7220             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7221                                  refclk, NULL, &crtc_state->dpll)) {
7222                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7223                 return -EINVAL;
7224         }
7225
7226         i9xx_compute_dpll(crtc, crtc_state, NULL);
7227
7228         return 0;
7229 }
7230
7231 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7232                                   struct intel_crtc_state *crtc_state)
7233 {
7234         int refclk = 100000;
7235         const struct intel_limit *limit = &intel_limits_chv;
7236
7237         memset(&crtc_state->dpll_hw_state, 0,
7238                sizeof(crtc_state->dpll_hw_state));
7239
7240         if (!crtc_state->clock_set &&
7241             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7242                                 refclk, NULL, &crtc_state->dpll)) {
7243                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7244                 return -EINVAL;
7245         }
7246
7247         chv_compute_dpll(crtc, crtc_state);
7248
7249         return 0;
7250 }
7251
7252 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7253                                   struct intel_crtc_state *crtc_state)
7254 {
7255         int refclk = 100000;
7256         const struct intel_limit *limit = &intel_limits_vlv;
7257
7258         memset(&crtc_state->dpll_hw_state, 0,
7259                sizeof(crtc_state->dpll_hw_state));
7260
7261         if (!crtc_state->clock_set &&
7262             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7263                                 refclk, NULL, &crtc_state->dpll)) {
7264                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7265                 return -EINVAL;
7266         }
7267
7268         vlv_compute_dpll(crtc, crtc_state);
7269
7270         return 0;
7271 }
7272
7273 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7274                                  struct intel_crtc_state *pipe_config)
7275 {
7276         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7277         uint32_t tmp;
7278
7279         if (INTEL_GEN(dev_priv) <= 3 &&
7280             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7281                 return;
7282
7283         tmp = I915_READ(PFIT_CONTROL);
7284         if (!(tmp & PFIT_ENABLE))
7285                 return;
7286
7287         /* Check whether the pfit is attached to our pipe. */
7288         if (INTEL_GEN(dev_priv) < 4) {
7289                 if (crtc->pipe != PIPE_B)
7290                         return;
7291         } else {
7292                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7293                         return;
7294         }
7295
7296         pipe_config->gmch_pfit.control = tmp;
7297         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7298 }
7299
7300 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7301                                struct intel_crtc_state *pipe_config)
7302 {
7303         struct drm_device *dev = crtc->base.dev;
7304         struct drm_i915_private *dev_priv = to_i915(dev);
7305         int pipe = pipe_config->cpu_transcoder;
7306         struct dpll clock;
7307         u32 mdiv;
7308         int refclk = 100000;
7309
7310         /* In case of DSI, DPLL will not be used */
7311         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7312                 return;
7313
7314         mutex_lock(&dev_priv->sb_lock);
7315         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7316         mutex_unlock(&dev_priv->sb_lock);
7317
7318         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7319         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7320         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7321         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7322         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7323
7324         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7325 }
7326
7327 static void
7328 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7329                               struct intel_initial_plane_config *plane_config)
7330 {
7331         struct drm_device *dev = crtc->base.dev;
7332         struct drm_i915_private *dev_priv = to_i915(dev);
7333         u32 val, base, offset;
7334         int pipe = crtc->pipe, plane = crtc->plane;
7335         int fourcc, pixel_format;
7336         unsigned int aligned_height;
7337         struct drm_framebuffer *fb;
7338         struct intel_framebuffer *intel_fb;
7339
7340         val = I915_READ(DSPCNTR(plane));
7341         if (!(val & DISPLAY_PLANE_ENABLE))
7342                 return;
7343
7344         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7345         if (!intel_fb) {
7346                 DRM_DEBUG_KMS("failed to alloc fb\n");
7347                 return;
7348         }
7349
7350         fb = &intel_fb->base;
7351
7352         fb->dev = dev;
7353
7354         if (INTEL_GEN(dev_priv) >= 4) {
7355                 if (val & DISPPLANE_TILED) {
7356                         plane_config->tiling = I915_TILING_X;
7357                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7358                 }
7359         }
7360
7361         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7362         fourcc = i9xx_format_to_fourcc(pixel_format);
7363         fb->format = drm_format_info(fourcc);
7364
7365         if (INTEL_GEN(dev_priv) >= 4) {
7366                 if (plane_config->tiling)
7367                         offset = I915_READ(DSPTILEOFF(plane));
7368                 else
7369                         offset = I915_READ(DSPLINOFF(plane));
7370                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7371         } else {
7372                 base = I915_READ(DSPADDR(plane));
7373         }
7374         plane_config->base = base;
7375
7376         val = I915_READ(PIPESRC(pipe));
7377         fb->width = ((val >> 16) & 0xfff) + 1;
7378         fb->height = ((val >> 0) & 0xfff) + 1;
7379
7380         val = I915_READ(DSPSTRIDE(pipe));
7381         fb->pitches[0] = val & 0xffffffc0;
7382
7383         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7384
7385         plane_config->size = fb->pitches[0] * aligned_height;
7386
7387         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7388                       pipe_name(pipe), plane, fb->width, fb->height,
7389                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7390                       plane_config->size);
7391
7392         plane_config->fb = intel_fb;
7393 }
7394
7395 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7396                                struct intel_crtc_state *pipe_config)
7397 {
7398         struct drm_device *dev = crtc->base.dev;
7399         struct drm_i915_private *dev_priv = to_i915(dev);
7400         int pipe = pipe_config->cpu_transcoder;
7401         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7402         struct dpll clock;
7403         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7404         int refclk = 100000;
7405
7406         /* In case of DSI, DPLL will not be used */
7407         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7408                 return;
7409
7410         mutex_lock(&dev_priv->sb_lock);
7411         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7412         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7413         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7414         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7415         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7416         mutex_unlock(&dev_priv->sb_lock);
7417
7418         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7419         clock.m2 = (pll_dw0 & 0xff) << 22;
7420         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7421                 clock.m2 |= pll_dw2 & 0x3fffff;
7422         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7423         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7424         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7425
7426         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7427 }
7428
7429 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7430                                  struct intel_crtc_state *pipe_config)
7431 {
7432         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7433         enum intel_display_power_domain power_domain;
7434         uint32_t tmp;
7435         bool ret;
7436
7437         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7438         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7439                 return false;
7440
7441         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7442         pipe_config->shared_dpll = NULL;
7443
7444         ret = false;
7445
7446         tmp = I915_READ(PIPECONF(crtc->pipe));
7447         if (!(tmp & PIPECONF_ENABLE))
7448                 goto out;
7449
7450         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7451             IS_CHERRYVIEW(dev_priv)) {
7452                 switch (tmp & PIPECONF_BPC_MASK) {
7453                 case PIPECONF_6BPC:
7454                         pipe_config->pipe_bpp = 18;
7455                         break;
7456                 case PIPECONF_8BPC:
7457                         pipe_config->pipe_bpp = 24;
7458                         break;
7459                 case PIPECONF_10BPC:
7460                         pipe_config->pipe_bpp = 30;
7461                         break;
7462                 default:
7463                         break;
7464                 }
7465         }
7466
7467         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7468             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7469                 pipe_config->limited_color_range = true;
7470
7471         if (INTEL_GEN(dev_priv) < 4)
7472                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7473
7474         intel_get_pipe_timings(crtc, pipe_config);
7475         intel_get_pipe_src_size(crtc, pipe_config);
7476
7477         i9xx_get_pfit_config(crtc, pipe_config);
7478
7479         if (INTEL_GEN(dev_priv) >= 4) {
7480                 /* No way to read it out on pipes B and C */
7481                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7482                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7483                 else
7484                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7485                 pipe_config->pixel_multiplier =
7486                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7487                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7488                 pipe_config->dpll_hw_state.dpll_md = tmp;
7489         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7490                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7491                 tmp = I915_READ(DPLL(crtc->pipe));
7492                 pipe_config->pixel_multiplier =
7493                         ((tmp & SDVO_MULTIPLIER_MASK)
7494                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7495         } else {
7496                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7497                  * port and will be fixed up in the encoder->get_config
7498                  * function. */
7499                 pipe_config->pixel_multiplier = 1;
7500         }
7501         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7502         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7503                 /*
7504                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7505                  * on 830. Filter it out here so that we don't
7506                  * report errors due to that.
7507                  */
7508                 if (IS_I830(dev_priv))
7509                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7510
7511                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7512                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7513         } else {
7514                 /* Mask out read-only status bits. */
7515                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7516                                                      DPLL_PORTC_READY_MASK |
7517                                                      DPLL_PORTB_READY_MASK);
7518         }
7519
7520         if (IS_CHERRYVIEW(dev_priv))
7521                 chv_crtc_clock_get(crtc, pipe_config);
7522         else if (IS_VALLEYVIEW(dev_priv))
7523                 vlv_crtc_clock_get(crtc, pipe_config);
7524         else
7525                 i9xx_crtc_clock_get(crtc, pipe_config);
7526
7527         /*
7528          * Normally the dotclock is filled in by the encoder .get_config()
7529          * but in case the pipe is enabled w/o any ports we need a sane
7530          * default.
7531          */
7532         pipe_config->base.adjusted_mode.crtc_clock =
7533                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7534
7535         ret = true;
7536
7537 out:
7538         intel_display_power_put(dev_priv, power_domain);
7539
7540         return ret;
7541 }
7542
7543 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7544 {
7545         struct intel_encoder *encoder;
7546         int i;
7547         u32 val, final;
7548         bool has_lvds = false;
7549         bool has_cpu_edp = false;
7550         bool has_panel = false;
7551         bool has_ck505 = false;
7552         bool can_ssc = false;
7553         bool using_ssc_source = false;
7554
7555         /* We need to take the global config into account */
7556         for_each_intel_encoder(&dev_priv->drm, encoder) {
7557                 switch (encoder->type) {
7558                 case INTEL_OUTPUT_LVDS:
7559                         has_panel = true;
7560                         has_lvds = true;
7561                         break;
7562                 case INTEL_OUTPUT_EDP:
7563                         has_panel = true;
7564                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
7565                                 has_cpu_edp = true;
7566                         break;
7567                 default:
7568                         break;
7569                 }
7570         }
7571
7572         if (HAS_PCH_IBX(dev_priv)) {
7573                 has_ck505 = dev_priv->vbt.display_clock_mode;
7574                 can_ssc = has_ck505;
7575         } else {
7576                 has_ck505 = false;
7577                 can_ssc = true;
7578         }
7579
7580         /* Check if any DPLLs are using the SSC source */
7581         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7582                 u32 temp = I915_READ(PCH_DPLL(i));
7583
7584                 if (!(temp & DPLL_VCO_ENABLE))
7585                         continue;
7586
7587                 if ((temp & PLL_REF_INPUT_MASK) ==
7588                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7589                         using_ssc_source = true;
7590                         break;
7591                 }
7592         }
7593
7594         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7595                       has_panel, has_lvds, has_ck505, using_ssc_source);
7596
7597         /* Ironlake: try to setup display ref clock before DPLL
7598          * enabling. This is only under driver's control after
7599          * PCH B stepping, previous chipset stepping should be
7600          * ignoring this setting.
7601          */
7602         val = I915_READ(PCH_DREF_CONTROL);
7603
7604         /* As we must carefully and slowly disable/enable each source in turn,
7605          * compute the final state we want first and check if we need to
7606          * make any changes at all.
7607          */
7608         final = val;
7609         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7610         if (has_ck505)
7611                 final |= DREF_NONSPREAD_CK505_ENABLE;
7612         else
7613                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7614
7615         final &= ~DREF_SSC_SOURCE_MASK;
7616         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7617         final &= ~DREF_SSC1_ENABLE;
7618
7619         if (has_panel) {
7620                 final |= DREF_SSC_SOURCE_ENABLE;
7621
7622                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7623                         final |= DREF_SSC1_ENABLE;
7624
7625                 if (has_cpu_edp) {
7626                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7627                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7628                         else
7629                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7630                 } else
7631                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7632         } else if (using_ssc_source) {
7633                 final |= DREF_SSC_SOURCE_ENABLE;
7634                 final |= DREF_SSC1_ENABLE;
7635         }
7636
7637         if (final == val)
7638                 return;
7639
7640         /* Always enable nonspread source */
7641         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7642
7643         if (has_ck505)
7644                 val |= DREF_NONSPREAD_CK505_ENABLE;
7645         else
7646                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7647
7648         if (has_panel) {
7649                 val &= ~DREF_SSC_SOURCE_MASK;
7650                 val |= DREF_SSC_SOURCE_ENABLE;
7651
7652                 /* SSC must be turned on before enabling the CPU output  */
7653                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7654                         DRM_DEBUG_KMS("Using SSC on panel\n");
7655                         val |= DREF_SSC1_ENABLE;
7656                 } else
7657                         val &= ~DREF_SSC1_ENABLE;
7658
7659                 /* Get SSC going before enabling the outputs */
7660                 I915_WRITE(PCH_DREF_CONTROL, val);
7661                 POSTING_READ(PCH_DREF_CONTROL);
7662                 udelay(200);
7663
7664                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7665
7666                 /* Enable CPU source on CPU attached eDP */
7667                 if (has_cpu_edp) {
7668                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7669                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7670                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7671                         } else
7672                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7673                 } else
7674                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7675
7676                 I915_WRITE(PCH_DREF_CONTROL, val);
7677                 POSTING_READ(PCH_DREF_CONTROL);
7678                 udelay(200);
7679         } else {
7680                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7681
7682                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7683
7684                 /* Turn off CPU output */
7685                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7686
7687                 I915_WRITE(PCH_DREF_CONTROL, val);
7688                 POSTING_READ(PCH_DREF_CONTROL);
7689                 udelay(200);
7690
7691                 if (!using_ssc_source) {
7692                         DRM_DEBUG_KMS("Disabling SSC source\n");
7693
7694                         /* Turn off the SSC source */
7695                         val &= ~DREF_SSC_SOURCE_MASK;
7696                         val |= DREF_SSC_SOURCE_DISABLE;
7697
7698                         /* Turn off SSC1 */
7699                         val &= ~DREF_SSC1_ENABLE;
7700
7701                         I915_WRITE(PCH_DREF_CONTROL, val);
7702                         POSTING_READ(PCH_DREF_CONTROL);
7703                         udelay(200);
7704                 }
7705         }
7706
7707         BUG_ON(val != final);
7708 }
7709
7710 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7711 {
7712         uint32_t tmp;
7713
7714         tmp = I915_READ(SOUTH_CHICKEN2);
7715         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7716         I915_WRITE(SOUTH_CHICKEN2, tmp);
7717
7718         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7719                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7720                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7721
7722         tmp = I915_READ(SOUTH_CHICKEN2);
7723         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7724         I915_WRITE(SOUTH_CHICKEN2, tmp);
7725
7726         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7727                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7728                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7729 }
7730
7731 /* WaMPhyProgramming:hsw */
7732 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7733 {
7734         uint32_t tmp;
7735
7736         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7737         tmp &= ~(0xFF << 24);
7738         tmp |= (0x12 << 24);
7739         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7740
7741         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7742         tmp |= (1 << 11);
7743         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7744
7745         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7746         tmp |= (1 << 11);
7747         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7748
7749         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7750         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7751         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7752
7753         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7754         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7755         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7756
7757         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7758         tmp &= ~(7 << 13);
7759         tmp |= (5 << 13);
7760         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7761
7762         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7763         tmp &= ~(7 << 13);
7764         tmp |= (5 << 13);
7765         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7766
7767         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7768         tmp &= ~0xFF;
7769         tmp |= 0x1C;
7770         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7771
7772         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7773         tmp &= ~0xFF;
7774         tmp |= 0x1C;
7775         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7776
7777         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7778         tmp &= ~(0xFF << 16);
7779         tmp |= (0x1C << 16);
7780         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7781
7782         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7783         tmp &= ~(0xFF << 16);
7784         tmp |= (0x1C << 16);
7785         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7786
7787         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7788         tmp |= (1 << 27);
7789         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7790
7791         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7792         tmp |= (1 << 27);
7793         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7794
7795         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7796         tmp &= ~(0xF << 28);
7797         tmp |= (4 << 28);
7798         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7799
7800         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7801         tmp &= ~(0xF << 28);
7802         tmp |= (4 << 28);
7803         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7804 }
7805
7806 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7807  * Programming" based on the parameters passed:
7808  * - Sequence to enable CLKOUT_DP
7809  * - Sequence to enable CLKOUT_DP without spread
7810  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7811  */
7812 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
7813                                  bool with_spread, bool with_fdi)
7814 {
7815         uint32_t reg, tmp;
7816
7817         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7818                 with_spread = true;
7819         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
7820             with_fdi, "LP PCH doesn't have FDI\n"))
7821                 with_fdi = false;
7822
7823         mutex_lock(&dev_priv->sb_lock);
7824
7825         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7826         tmp &= ~SBI_SSCCTL_DISABLE;
7827         tmp |= SBI_SSCCTL_PATHALT;
7828         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7829
7830         udelay(24);
7831
7832         if (with_spread) {
7833                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7834                 tmp &= ~SBI_SSCCTL_PATHALT;
7835                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7836
7837                 if (with_fdi) {
7838                         lpt_reset_fdi_mphy(dev_priv);
7839                         lpt_program_fdi_mphy(dev_priv);
7840                 }
7841         }
7842
7843         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7844         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7845         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7846         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7847
7848         mutex_unlock(&dev_priv->sb_lock);
7849 }
7850
7851 /* Sequence to disable CLKOUT_DP */
7852 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
7853 {
7854         uint32_t reg, tmp;
7855
7856         mutex_lock(&dev_priv->sb_lock);
7857
7858         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7859         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7860         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7861         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7862
7863         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7864         if (!(tmp & SBI_SSCCTL_DISABLE)) {
7865                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
7866                         tmp |= SBI_SSCCTL_PATHALT;
7867                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7868                         udelay(32);
7869                 }
7870                 tmp |= SBI_SSCCTL_DISABLE;
7871                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7872         }
7873
7874         mutex_unlock(&dev_priv->sb_lock);
7875 }
7876
7877 #define BEND_IDX(steps) ((50 + (steps)) / 5)
7878
7879 static const uint16_t sscdivintphase[] = {
7880         [BEND_IDX( 50)] = 0x3B23,
7881         [BEND_IDX( 45)] = 0x3B23,
7882         [BEND_IDX( 40)] = 0x3C23,
7883         [BEND_IDX( 35)] = 0x3C23,
7884         [BEND_IDX( 30)] = 0x3D23,
7885         [BEND_IDX( 25)] = 0x3D23,
7886         [BEND_IDX( 20)] = 0x3E23,
7887         [BEND_IDX( 15)] = 0x3E23,
7888         [BEND_IDX( 10)] = 0x3F23,
7889         [BEND_IDX(  5)] = 0x3F23,
7890         [BEND_IDX(  0)] = 0x0025,
7891         [BEND_IDX( -5)] = 0x0025,
7892         [BEND_IDX(-10)] = 0x0125,
7893         [BEND_IDX(-15)] = 0x0125,
7894         [BEND_IDX(-20)] = 0x0225,
7895         [BEND_IDX(-25)] = 0x0225,
7896         [BEND_IDX(-30)] = 0x0325,
7897         [BEND_IDX(-35)] = 0x0325,
7898         [BEND_IDX(-40)] = 0x0425,
7899         [BEND_IDX(-45)] = 0x0425,
7900         [BEND_IDX(-50)] = 0x0525,
7901 };
7902
7903 /*
7904  * Bend CLKOUT_DP
7905  * steps -50 to 50 inclusive, in steps of 5
7906  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
7907  * change in clock period = -(steps / 10) * 5.787 ps
7908  */
7909 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
7910 {
7911         uint32_t tmp;
7912         int idx = BEND_IDX(steps);
7913
7914         if (WARN_ON(steps % 5 != 0))
7915                 return;
7916
7917         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
7918                 return;
7919
7920         mutex_lock(&dev_priv->sb_lock);
7921
7922         if (steps % 10 != 0)
7923                 tmp = 0xAAAAAAAB;
7924         else
7925                 tmp = 0x00000000;
7926         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
7927
7928         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
7929         tmp &= 0xffff0000;
7930         tmp |= sscdivintphase[idx];
7931         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
7932
7933         mutex_unlock(&dev_priv->sb_lock);
7934 }
7935
7936 #undef BEND_IDX
7937
7938 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
7939 {
7940         struct intel_encoder *encoder;
7941         bool has_vga = false;
7942
7943         for_each_intel_encoder(&dev_priv->drm, encoder) {
7944                 switch (encoder->type) {
7945                 case INTEL_OUTPUT_ANALOG:
7946                         has_vga = true;
7947                         break;
7948                 default:
7949                         break;
7950                 }
7951         }
7952
7953         if (has_vga) {
7954                 lpt_bend_clkout_dp(dev_priv, 0);
7955                 lpt_enable_clkout_dp(dev_priv, true, true);
7956         } else {
7957                 lpt_disable_clkout_dp(dev_priv);
7958         }
7959 }
7960
7961 /*
7962  * Initialize reference clocks when the driver loads
7963  */
7964 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
7965 {
7966         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
7967                 ironlake_init_pch_refclk(dev_priv);
7968         else if (HAS_PCH_LPT(dev_priv))
7969                 lpt_init_pch_refclk(dev_priv);
7970 }
7971
7972 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
7973 {
7974         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
7975         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
7976         int pipe = intel_crtc->pipe;
7977         uint32_t val;
7978
7979         val = 0;
7980
7981         switch (intel_crtc->config->pipe_bpp) {
7982         case 18:
7983                 val |= PIPECONF_6BPC;
7984                 break;
7985         case 24:
7986                 val |= PIPECONF_8BPC;
7987                 break;
7988         case 30:
7989                 val |= PIPECONF_10BPC;
7990                 break;
7991         case 36:
7992                 val |= PIPECONF_12BPC;
7993                 break;
7994         default:
7995                 /* Case prevented by intel_choose_pipe_bpp_dither. */
7996                 BUG();
7997         }
7998
7999         if (intel_crtc->config->dither)
8000                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8001
8002         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8003                 val |= PIPECONF_INTERLACED_ILK;
8004         else
8005                 val |= PIPECONF_PROGRESSIVE;
8006
8007         if (intel_crtc->config->limited_color_range)
8008                 val |= PIPECONF_COLOR_RANGE_SELECT;
8009
8010         I915_WRITE(PIPECONF(pipe), val);
8011         POSTING_READ(PIPECONF(pipe));
8012 }
8013
8014 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8015 {
8016         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8017         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8018         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8019         u32 val = 0;
8020
8021         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8022                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8023
8024         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8025                 val |= PIPECONF_INTERLACED_ILK;
8026         else
8027                 val |= PIPECONF_PROGRESSIVE;
8028
8029         I915_WRITE(PIPECONF(cpu_transcoder), val);
8030         POSTING_READ(PIPECONF(cpu_transcoder));
8031 }
8032
8033 static void haswell_set_pipemisc(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
8038         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8039                 u32 val = 0;
8040
8041                 switch (intel_crtc->config->pipe_bpp) {
8042                 case 18:
8043                         val |= PIPEMISC_DITHER_6_BPC;
8044                         break;
8045                 case 24:
8046                         val |= PIPEMISC_DITHER_8_BPC;
8047                         break;
8048                 case 30:
8049                         val |= PIPEMISC_DITHER_10_BPC;
8050                         break;
8051                 case 36:
8052                         val |= PIPEMISC_DITHER_12_BPC;
8053                         break;
8054                 default:
8055                         /* Case prevented by pipe_config_set_bpp. */
8056                         BUG();
8057                 }
8058
8059                 if (intel_crtc->config->dither)
8060                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8061
8062                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8063         }
8064 }
8065
8066 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8067 {
8068         /*
8069          * Account for spread spectrum to avoid
8070          * oversubscribing the link. Max center spread
8071          * is 2.5%; use 5% for safety's sake.
8072          */
8073         u32 bps = target_clock * bpp * 21 / 20;
8074         return DIV_ROUND_UP(bps, link_bw * 8);
8075 }
8076
8077 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8078 {
8079         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8080 }
8081
8082 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8083                                   struct intel_crtc_state *crtc_state,
8084                                   struct dpll *reduced_clock)
8085 {
8086         struct drm_crtc *crtc = &intel_crtc->base;
8087         struct drm_device *dev = crtc->dev;
8088         struct drm_i915_private *dev_priv = to_i915(dev);
8089         u32 dpll, fp, fp2;
8090         int factor;
8091
8092         /* Enable autotuning of the PLL clock (if permissible) */
8093         factor = 21;
8094         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8095                 if ((intel_panel_use_ssc(dev_priv) &&
8096                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8097                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8098                         factor = 25;
8099         } else if (crtc_state->sdvo_tv_clock)
8100                 factor = 20;
8101
8102         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8103
8104         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8105                 fp |= FP_CB_TUNE;
8106
8107         if (reduced_clock) {
8108                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8109
8110                 if (reduced_clock->m < factor * reduced_clock->n)
8111                         fp2 |= FP_CB_TUNE;
8112         } else {
8113                 fp2 = fp;
8114         }
8115
8116         dpll = 0;
8117
8118         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8119                 dpll |= DPLLB_MODE_LVDS;
8120         else
8121                 dpll |= DPLLB_MODE_DAC_SERIAL;
8122
8123         dpll |= (crtc_state->pixel_multiplier - 1)
8124                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8125
8126         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8127             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8128                 dpll |= DPLL_SDVO_HIGH_SPEED;
8129
8130         if (intel_crtc_has_dp_encoder(crtc_state))
8131                 dpll |= DPLL_SDVO_HIGH_SPEED;
8132
8133         /*
8134          * The high speed IO clock is only really required for
8135          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8136          * possible to share the DPLL between CRT and HDMI. Enabling
8137          * the clock needlessly does no real harm, except use up a
8138          * bit of power potentially.
8139          *
8140          * We'll limit this to IVB with 3 pipes, since it has only two
8141          * DPLLs and so DPLL sharing is the only way to get three pipes
8142          * driving PCH ports at the same time. On SNB we could do this,
8143          * and potentially avoid enabling the second DPLL, but it's not
8144          * clear if it''s a win or loss power wise. No point in doing
8145          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8146          */
8147         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8148             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8149                 dpll |= DPLL_SDVO_HIGH_SPEED;
8150
8151         /* compute bitmask from p1 value */
8152         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8153         /* also FPA1 */
8154         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8155
8156         switch (crtc_state->dpll.p2) {
8157         case 5:
8158                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8159                 break;
8160         case 7:
8161                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8162                 break;
8163         case 10:
8164                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8165                 break;
8166         case 14:
8167                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8168                 break;
8169         }
8170
8171         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8172             intel_panel_use_ssc(dev_priv))
8173                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8174         else
8175                 dpll |= PLL_REF_INPUT_DREFCLK;
8176
8177         dpll |= DPLL_VCO_ENABLE;
8178
8179         crtc_state->dpll_hw_state.dpll = dpll;
8180         crtc_state->dpll_hw_state.fp0 = fp;
8181         crtc_state->dpll_hw_state.fp1 = fp2;
8182 }
8183
8184 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8185                                        struct intel_crtc_state *crtc_state)
8186 {
8187         struct drm_device *dev = crtc->base.dev;
8188         struct drm_i915_private *dev_priv = to_i915(dev);
8189         const struct intel_limit *limit;
8190         int refclk = 120000;
8191
8192         memset(&crtc_state->dpll_hw_state, 0,
8193                sizeof(crtc_state->dpll_hw_state));
8194
8195         crtc->lowfreq_avail = false;
8196
8197         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8198         if (!crtc_state->has_pch_encoder)
8199                 return 0;
8200
8201         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8202                 if (intel_panel_use_ssc(dev_priv)) {
8203                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8204                                       dev_priv->vbt.lvds_ssc_freq);
8205                         refclk = dev_priv->vbt.lvds_ssc_freq;
8206                 }
8207
8208                 if (intel_is_dual_link_lvds(dev)) {
8209                         if (refclk == 100000)
8210                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8211                         else
8212                                 limit = &intel_limits_ironlake_dual_lvds;
8213                 } else {
8214                         if (refclk == 100000)
8215                                 limit = &intel_limits_ironlake_single_lvds_100m;
8216                         else
8217                                 limit = &intel_limits_ironlake_single_lvds;
8218                 }
8219         } else {
8220                 limit = &intel_limits_ironlake_dac;
8221         }
8222
8223         if (!crtc_state->clock_set &&
8224             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8225                                 refclk, NULL, &crtc_state->dpll)) {
8226                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8227                 return -EINVAL;
8228         }
8229
8230         ironlake_compute_dpll(crtc, crtc_state, NULL);
8231
8232         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8233                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8234                                  pipe_name(crtc->pipe));
8235                 return -EINVAL;
8236         }
8237
8238         return 0;
8239 }
8240
8241 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8242                                          struct intel_link_m_n *m_n)
8243 {
8244         struct drm_device *dev = crtc->base.dev;
8245         struct drm_i915_private *dev_priv = to_i915(dev);
8246         enum pipe pipe = crtc->pipe;
8247
8248         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8249         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8250         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8251                 & ~TU_SIZE_MASK;
8252         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8253         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8254                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8255 }
8256
8257 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8258                                          enum transcoder transcoder,
8259                                          struct intel_link_m_n *m_n,
8260                                          struct intel_link_m_n *m2_n2)
8261 {
8262         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8263         enum pipe pipe = crtc->pipe;
8264
8265         if (INTEL_GEN(dev_priv) >= 5) {
8266                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8267                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8268                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8269                         & ~TU_SIZE_MASK;
8270                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8271                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8272                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8273                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8274                  * gen < 8) and if DRRS is supported (to make sure the
8275                  * registers are not unnecessarily read).
8276                  */
8277                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8278                         crtc->config->has_drrs) {
8279                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8280                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8281                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8282                                         & ~TU_SIZE_MASK;
8283                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8284                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8285                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8286                 }
8287         } else {
8288                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8289                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8290                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8291                         & ~TU_SIZE_MASK;
8292                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8293                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8294                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8295         }
8296 }
8297
8298 void intel_dp_get_m_n(struct intel_crtc *crtc,
8299                       struct intel_crtc_state *pipe_config)
8300 {
8301         if (pipe_config->has_pch_encoder)
8302                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8303         else
8304                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8305                                              &pipe_config->dp_m_n,
8306                                              &pipe_config->dp_m2_n2);
8307 }
8308
8309 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8310                                         struct intel_crtc_state *pipe_config)
8311 {
8312         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8313                                      &pipe_config->fdi_m_n, NULL);
8314 }
8315
8316 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8317                                     struct intel_crtc_state *pipe_config)
8318 {
8319         struct drm_device *dev = crtc->base.dev;
8320         struct drm_i915_private *dev_priv = to_i915(dev);
8321         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8322         uint32_t ps_ctrl = 0;
8323         int id = -1;
8324         int i;
8325
8326         /* find scaler attached to this pipe */
8327         for (i = 0; i < crtc->num_scalers; i++) {
8328                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8329                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8330                         id = i;
8331                         pipe_config->pch_pfit.enabled = true;
8332                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8333                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8334                         break;
8335                 }
8336         }
8337
8338         scaler_state->scaler_id = id;
8339         if (id >= 0) {
8340                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8341         } else {
8342                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8343         }
8344 }
8345
8346 static void
8347 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8348                                  struct intel_initial_plane_config *plane_config)
8349 {
8350         struct drm_device *dev = crtc->base.dev;
8351         struct drm_i915_private *dev_priv = to_i915(dev);
8352         u32 val, base, offset, stride_mult, tiling;
8353         int pipe = crtc->pipe;
8354         int fourcc, pixel_format;
8355         unsigned int aligned_height;
8356         struct drm_framebuffer *fb;
8357         struct intel_framebuffer *intel_fb;
8358
8359         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8360         if (!intel_fb) {
8361                 DRM_DEBUG_KMS("failed to alloc fb\n");
8362                 return;
8363         }
8364
8365         fb = &intel_fb->base;
8366
8367         fb->dev = dev;
8368
8369         val = I915_READ(PLANE_CTL(pipe, 0));
8370         if (!(val & PLANE_CTL_ENABLE))
8371                 goto error;
8372
8373         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8374         fourcc = skl_format_to_fourcc(pixel_format,
8375                                       val & PLANE_CTL_ORDER_RGBX,
8376                                       val & PLANE_CTL_ALPHA_MASK);
8377         fb->format = drm_format_info(fourcc);
8378
8379         tiling = val & PLANE_CTL_TILED_MASK;
8380         switch (tiling) {
8381         case PLANE_CTL_TILED_LINEAR:
8382                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8383                 break;
8384         case PLANE_CTL_TILED_X:
8385                 plane_config->tiling = I915_TILING_X;
8386                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8387                 break;
8388         case PLANE_CTL_TILED_Y:
8389                 fb->modifier = I915_FORMAT_MOD_Y_TILED;
8390                 break;
8391         case PLANE_CTL_TILED_YF:
8392                 fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8393                 break;
8394         default:
8395                 MISSING_CASE(tiling);
8396                 goto error;
8397         }
8398
8399         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
8400         plane_config->base = base;
8401
8402         offset = I915_READ(PLANE_OFFSET(pipe, 0));
8403
8404         val = I915_READ(PLANE_SIZE(pipe, 0));
8405         fb->height = ((val >> 16) & 0xfff) + 1;
8406         fb->width = ((val >> 0) & 0x1fff) + 1;
8407
8408         val = I915_READ(PLANE_STRIDE(pipe, 0));
8409         stride_mult = intel_fb_stride_alignment(fb, 0);
8410         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8411
8412         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8413
8414         plane_config->size = fb->pitches[0] * aligned_height;
8415
8416         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8417                       pipe_name(pipe), fb->width, fb->height,
8418                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8419                       plane_config->size);
8420
8421         plane_config->fb = intel_fb;
8422         return;
8423
8424 error:
8425         kfree(intel_fb);
8426 }
8427
8428 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8429                                      struct intel_crtc_state *pipe_config)
8430 {
8431         struct drm_device *dev = crtc->base.dev;
8432         struct drm_i915_private *dev_priv = to_i915(dev);
8433         uint32_t tmp;
8434
8435         tmp = I915_READ(PF_CTL(crtc->pipe));
8436
8437         if (tmp & PF_ENABLE) {
8438                 pipe_config->pch_pfit.enabled = true;
8439                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8440                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8441
8442                 /* We currently do not free assignements of panel fitters on
8443                  * ivb/hsw (since we don't use the higher upscaling modes which
8444                  * differentiates them) so just WARN about this case for now. */
8445                 if (IS_GEN7(dev_priv)) {
8446                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8447                                 PF_PIPE_SEL_IVB(crtc->pipe));
8448                 }
8449         }
8450 }
8451
8452 static void
8453 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
8454                                   struct intel_initial_plane_config *plane_config)
8455 {
8456         struct drm_device *dev = crtc->base.dev;
8457         struct drm_i915_private *dev_priv = to_i915(dev);
8458         u32 val, base, offset;
8459         int pipe = crtc->pipe;
8460         int fourcc, pixel_format;
8461         unsigned int aligned_height;
8462         struct drm_framebuffer *fb;
8463         struct intel_framebuffer *intel_fb;
8464
8465         val = I915_READ(DSPCNTR(pipe));
8466         if (!(val & DISPLAY_PLANE_ENABLE))
8467                 return;
8468
8469         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8470         if (!intel_fb) {
8471                 DRM_DEBUG_KMS("failed to alloc fb\n");
8472                 return;
8473         }
8474
8475         fb = &intel_fb->base;
8476
8477         fb->dev = dev;
8478
8479         if (INTEL_GEN(dev_priv) >= 4) {
8480                 if (val & DISPPLANE_TILED) {
8481                         plane_config->tiling = I915_TILING_X;
8482                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8483                 }
8484         }
8485
8486         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8487         fourcc = i9xx_format_to_fourcc(pixel_format);
8488         fb->format = drm_format_info(fourcc);
8489
8490         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
8491         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8492                 offset = I915_READ(DSPOFFSET(pipe));
8493         } else {
8494                 if (plane_config->tiling)
8495                         offset = I915_READ(DSPTILEOFF(pipe));
8496                 else
8497                         offset = I915_READ(DSPLINOFF(pipe));
8498         }
8499         plane_config->base = base;
8500
8501         val = I915_READ(PIPESRC(pipe));
8502         fb->width = ((val >> 16) & 0xfff) + 1;
8503         fb->height = ((val >> 0) & 0xfff) + 1;
8504
8505         val = I915_READ(DSPSTRIDE(pipe));
8506         fb->pitches[0] = val & 0xffffffc0;
8507
8508         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8509
8510         plane_config->size = fb->pitches[0] * aligned_height;
8511
8512         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8513                       pipe_name(pipe), fb->width, fb->height,
8514                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8515                       plane_config->size);
8516
8517         plane_config->fb = intel_fb;
8518 }
8519
8520 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8521                                      struct intel_crtc_state *pipe_config)
8522 {
8523         struct drm_device *dev = crtc->base.dev;
8524         struct drm_i915_private *dev_priv = to_i915(dev);
8525         enum intel_display_power_domain power_domain;
8526         uint32_t tmp;
8527         bool ret;
8528
8529         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8530         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8531                 return false;
8532
8533         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8534         pipe_config->shared_dpll = NULL;
8535
8536         ret = false;
8537         tmp = I915_READ(PIPECONF(crtc->pipe));
8538         if (!(tmp & PIPECONF_ENABLE))
8539                 goto out;
8540
8541         switch (tmp & PIPECONF_BPC_MASK) {
8542         case PIPECONF_6BPC:
8543                 pipe_config->pipe_bpp = 18;
8544                 break;
8545         case PIPECONF_8BPC:
8546                 pipe_config->pipe_bpp = 24;
8547                 break;
8548         case PIPECONF_10BPC:
8549                 pipe_config->pipe_bpp = 30;
8550                 break;
8551         case PIPECONF_12BPC:
8552                 pipe_config->pipe_bpp = 36;
8553                 break;
8554         default:
8555                 break;
8556         }
8557
8558         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8559                 pipe_config->limited_color_range = true;
8560
8561         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8562                 struct intel_shared_dpll *pll;
8563                 enum intel_dpll_id pll_id;
8564
8565                 pipe_config->has_pch_encoder = true;
8566
8567                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8568                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8569                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8570
8571                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8572
8573                 if (HAS_PCH_IBX(dev_priv)) {
8574                         /*
8575                          * The pipe->pch transcoder and pch transcoder->pll
8576                          * mapping is fixed.
8577                          */
8578                         pll_id = (enum intel_dpll_id) crtc->pipe;
8579                 } else {
8580                         tmp = I915_READ(PCH_DPLL_SEL);
8581                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8582                                 pll_id = DPLL_ID_PCH_PLL_B;
8583                         else
8584                                 pll_id= DPLL_ID_PCH_PLL_A;
8585                 }
8586
8587                 pipe_config->shared_dpll =
8588                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8589                 pll = pipe_config->shared_dpll;
8590
8591                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
8592                                                  &pipe_config->dpll_hw_state));
8593
8594                 tmp = pipe_config->dpll_hw_state.dpll;
8595                 pipe_config->pixel_multiplier =
8596                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8597                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8598
8599                 ironlake_pch_clock_get(crtc, pipe_config);
8600         } else {
8601                 pipe_config->pixel_multiplier = 1;
8602         }
8603
8604         intel_get_pipe_timings(crtc, pipe_config);
8605         intel_get_pipe_src_size(crtc, pipe_config);
8606
8607         ironlake_get_pfit_config(crtc, pipe_config);
8608
8609         ret = true;
8610
8611 out:
8612         intel_display_power_put(dev_priv, power_domain);
8613
8614         return ret;
8615 }
8616
8617 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8618 {
8619         struct drm_device *dev = &dev_priv->drm;
8620         struct intel_crtc *crtc;
8621
8622         for_each_intel_crtc(dev, crtc)
8623                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8624                      pipe_name(crtc->pipe));
8625
8626         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
8627         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8628         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8629         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8630         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8631         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8632              "CPU PWM1 enabled\n");
8633         if (IS_HASWELL(dev_priv))
8634                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8635                      "CPU PWM2 enabled\n");
8636         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8637              "PCH PWM1 enabled\n");
8638         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8639              "Utility pin enabled\n");
8640         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8641
8642         /*
8643          * In theory we can still leave IRQs enabled, as long as only the HPD
8644          * interrupts remain enabled. We used to check for that, but since it's
8645          * gen-specific and since we only disable LCPLL after we fully disable
8646          * the interrupts, the check below should be enough.
8647          */
8648         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8649 }
8650
8651 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8652 {
8653         if (IS_HASWELL(dev_priv))
8654                 return I915_READ(D_COMP_HSW);
8655         else
8656                 return I915_READ(D_COMP_BDW);
8657 }
8658
8659 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8660 {
8661         if (IS_HASWELL(dev_priv)) {
8662                 mutex_lock(&dev_priv->rps.hw_lock);
8663                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8664                                             val))
8665                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8666                 mutex_unlock(&dev_priv->rps.hw_lock);
8667         } else {
8668                 I915_WRITE(D_COMP_BDW, val);
8669                 POSTING_READ(D_COMP_BDW);
8670         }
8671 }
8672
8673 /*
8674  * This function implements pieces of two sequences from BSpec:
8675  * - Sequence for display software to disable LCPLL
8676  * - Sequence for display software to allow package C8+
8677  * The steps implemented here are just the steps that actually touch the LCPLL
8678  * register. Callers should take care of disabling all the display engine
8679  * functions, doing the mode unset, fixing interrupts, etc.
8680  */
8681 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8682                               bool switch_to_fclk, bool allow_power_down)
8683 {
8684         uint32_t val;
8685
8686         assert_can_disable_lcpll(dev_priv);
8687
8688         val = I915_READ(LCPLL_CTL);
8689
8690         if (switch_to_fclk) {
8691                 val |= LCPLL_CD_SOURCE_FCLK;
8692                 I915_WRITE(LCPLL_CTL, val);
8693
8694                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8695                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8696                         DRM_ERROR("Switching to FCLK failed\n");
8697
8698                 val = I915_READ(LCPLL_CTL);
8699         }
8700
8701         val |= LCPLL_PLL_DISABLE;
8702         I915_WRITE(LCPLL_CTL, val);
8703         POSTING_READ(LCPLL_CTL);
8704
8705         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8706                 DRM_ERROR("LCPLL still locked\n");
8707
8708         val = hsw_read_dcomp(dev_priv);
8709         val |= D_COMP_COMP_DISABLE;
8710         hsw_write_dcomp(dev_priv, val);
8711         ndelay(100);
8712
8713         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8714                      1))
8715                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8716
8717         if (allow_power_down) {
8718                 val = I915_READ(LCPLL_CTL);
8719                 val |= LCPLL_POWER_DOWN_ALLOW;
8720                 I915_WRITE(LCPLL_CTL, val);
8721                 POSTING_READ(LCPLL_CTL);
8722         }
8723 }
8724
8725 /*
8726  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8727  * source.
8728  */
8729 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8730 {
8731         uint32_t val;
8732
8733         val = I915_READ(LCPLL_CTL);
8734
8735         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8736                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8737                 return;
8738
8739         /*
8740          * Make sure we're not on PC8 state before disabling PC8, otherwise
8741          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8742          */
8743         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8744
8745         if (val & LCPLL_POWER_DOWN_ALLOW) {
8746                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8747                 I915_WRITE(LCPLL_CTL, val);
8748                 POSTING_READ(LCPLL_CTL);
8749         }
8750
8751         val = hsw_read_dcomp(dev_priv);
8752         val |= D_COMP_COMP_FORCE;
8753         val &= ~D_COMP_COMP_DISABLE;
8754         hsw_write_dcomp(dev_priv, val);
8755
8756         val = I915_READ(LCPLL_CTL);
8757         val &= ~LCPLL_PLL_DISABLE;
8758         I915_WRITE(LCPLL_CTL, val);
8759
8760         if (intel_wait_for_register(dev_priv,
8761                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8762                                     5))
8763                 DRM_ERROR("LCPLL not locked yet\n");
8764
8765         if (val & LCPLL_CD_SOURCE_FCLK) {
8766                 val = I915_READ(LCPLL_CTL);
8767                 val &= ~LCPLL_CD_SOURCE_FCLK;
8768                 I915_WRITE(LCPLL_CTL, val);
8769
8770                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8771                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8772                         DRM_ERROR("Switching back to LCPLL failed\n");
8773         }
8774
8775         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8776         intel_update_cdclk(dev_priv);
8777 }
8778
8779 /*
8780  * Package states C8 and deeper are really deep PC states that can only be
8781  * reached when all the devices on the system allow it, so even if the graphics
8782  * device allows PC8+, it doesn't mean the system will actually get to these
8783  * states. Our driver only allows PC8+ when going into runtime PM.
8784  *
8785  * The requirements for PC8+ are that all the outputs are disabled, the power
8786  * well is disabled and most interrupts are disabled, and these are also
8787  * requirements for runtime PM. When these conditions are met, we manually do
8788  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8789  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8790  * hang the machine.
8791  *
8792  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8793  * the state of some registers, so when we come back from PC8+ we need to
8794  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8795  * need to take care of the registers kept by RC6. Notice that this happens even
8796  * if we don't put the device in PCI D3 state (which is what currently happens
8797  * because of the runtime PM support).
8798  *
8799  * For more, read "Display Sequences for Package C8" on the hardware
8800  * documentation.
8801  */
8802 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8803 {
8804         uint32_t val;
8805
8806         DRM_DEBUG_KMS("Enabling package C8+\n");
8807
8808         if (HAS_PCH_LPT_LP(dev_priv)) {
8809                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8810                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8811                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8812         }
8813
8814         lpt_disable_clkout_dp(dev_priv);
8815         hsw_disable_lcpll(dev_priv, true, true);
8816 }
8817
8818 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8819 {
8820         uint32_t val;
8821
8822         DRM_DEBUG_KMS("Disabling package C8+\n");
8823
8824         hsw_restore_lcpll(dev_priv);
8825         lpt_init_pch_refclk(dev_priv);
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
8834 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
8835                                       struct intel_crtc_state *crtc_state)
8836 {
8837         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
8838                 struct intel_encoder *encoder =
8839                         intel_ddi_get_crtc_new_encoder(crtc_state);
8840
8841                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
8842                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8843                                          pipe_name(crtc->pipe));
8844                         return -EINVAL;
8845                 }
8846         }
8847
8848         crtc->lowfreq_avail = false;
8849
8850         return 0;
8851 }
8852
8853 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
8854                                    enum port port,
8855                                    struct intel_crtc_state *pipe_config)
8856 {
8857         enum intel_dpll_id id;
8858         u32 temp;
8859
8860         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
8861         id = temp >> (port * 2);
8862
8863         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
8864                 return;
8865
8866         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8867 }
8868
8869 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
8870                                 enum port port,
8871                                 struct intel_crtc_state *pipe_config)
8872 {
8873         enum intel_dpll_id id;
8874
8875         switch (port) {
8876         case PORT_A:
8877                 id = DPLL_ID_SKL_DPLL0;
8878                 break;
8879         case PORT_B:
8880                 id = DPLL_ID_SKL_DPLL1;
8881                 break;
8882         case PORT_C:
8883                 id = DPLL_ID_SKL_DPLL2;
8884                 break;
8885         default:
8886                 DRM_ERROR("Incorrect port type\n");
8887                 return;
8888         }
8889
8890         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8891 }
8892
8893 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
8894                                 enum port port,
8895                                 struct intel_crtc_state *pipe_config)
8896 {
8897         enum intel_dpll_id id;
8898         u32 temp;
8899
8900         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
8901         id = temp >> (port * 3 + 1);
8902
8903         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
8904                 return;
8905
8906         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8907 }
8908
8909 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
8910                                 enum port port,
8911                                 struct intel_crtc_state *pipe_config)
8912 {
8913         enum intel_dpll_id id;
8914         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
8915
8916         switch (ddi_pll_sel) {
8917         case PORT_CLK_SEL_WRPLL1:
8918                 id = DPLL_ID_WRPLL1;
8919                 break;
8920         case PORT_CLK_SEL_WRPLL2:
8921                 id = DPLL_ID_WRPLL2;
8922                 break;
8923         case PORT_CLK_SEL_SPLL:
8924                 id = DPLL_ID_SPLL;
8925                 break;
8926         case PORT_CLK_SEL_LCPLL_810:
8927                 id = DPLL_ID_LCPLL_810;
8928                 break;
8929         case PORT_CLK_SEL_LCPLL_1350:
8930                 id = DPLL_ID_LCPLL_1350;
8931                 break;
8932         case PORT_CLK_SEL_LCPLL_2700:
8933                 id = DPLL_ID_LCPLL_2700;
8934                 break;
8935         default:
8936                 MISSING_CASE(ddi_pll_sel);
8937                 /* fall through */
8938         case PORT_CLK_SEL_NONE:
8939                 return;
8940         }
8941
8942         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8943 }
8944
8945 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
8946                                      struct intel_crtc_state *pipe_config,
8947                                      u64 *power_domain_mask)
8948 {
8949         struct drm_device *dev = crtc->base.dev;
8950         struct drm_i915_private *dev_priv = to_i915(dev);
8951         enum intel_display_power_domain power_domain;
8952         u32 tmp;
8953
8954         /*
8955          * The pipe->transcoder mapping is fixed with the exception of the eDP
8956          * transcoder handled below.
8957          */
8958         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8959
8960         /*
8961          * XXX: Do intel_display_power_get_if_enabled before reading this (for
8962          * consistency and less surprising code; it's in always on power).
8963          */
8964         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
8965         if (tmp & TRANS_DDI_FUNC_ENABLE) {
8966                 enum pipe trans_edp_pipe;
8967                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
8968                 default:
8969                         WARN(1, "unknown pipe linked to edp transcoder\n");
8970                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
8971                 case TRANS_DDI_EDP_INPUT_A_ON:
8972                         trans_edp_pipe = PIPE_A;
8973                         break;
8974                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
8975                         trans_edp_pipe = PIPE_B;
8976                         break;
8977                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
8978                         trans_edp_pipe = PIPE_C;
8979                         break;
8980                 }
8981
8982                 if (trans_edp_pipe == crtc->pipe)
8983                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
8984         }
8985
8986         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
8987         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8988                 return false;
8989         *power_domain_mask |= BIT_ULL(power_domain);
8990
8991         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
8992
8993         return tmp & PIPECONF_ENABLE;
8994 }
8995
8996 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
8997                                          struct intel_crtc_state *pipe_config,
8998                                          u64 *power_domain_mask)
8999 {
9000         struct drm_device *dev = crtc->base.dev;
9001         struct drm_i915_private *dev_priv = to_i915(dev);
9002         enum intel_display_power_domain power_domain;
9003         enum port port;
9004         enum transcoder cpu_transcoder;
9005         u32 tmp;
9006
9007         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9008                 if (port == PORT_A)
9009                         cpu_transcoder = TRANSCODER_DSI_A;
9010                 else
9011                         cpu_transcoder = TRANSCODER_DSI_C;
9012
9013                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9014                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9015                         continue;
9016                 *power_domain_mask |= BIT_ULL(power_domain);
9017
9018                 /*
9019                  * The PLL needs to be enabled with a valid divider
9020                  * configuration, otherwise accessing DSI registers will hang
9021                  * the machine. See BSpec North Display Engine
9022                  * registers/MIPI[BXT]. We can break out here early, since we
9023                  * need the same DSI PLL to be enabled for both DSI ports.
9024                  */
9025                 if (!intel_dsi_pll_is_enabled(dev_priv))
9026                         break;
9027
9028                 /* XXX: this works for video mode only */
9029                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9030                 if (!(tmp & DPI_ENABLE))
9031                         continue;
9032
9033                 tmp = I915_READ(MIPI_CTRL(port));
9034                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9035                         continue;
9036
9037                 pipe_config->cpu_transcoder = cpu_transcoder;
9038                 break;
9039         }
9040
9041         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9042 }
9043
9044 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9045                                        struct intel_crtc_state *pipe_config)
9046 {
9047         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9048         struct intel_shared_dpll *pll;
9049         enum port port;
9050         uint32_t tmp;
9051
9052         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9053
9054         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9055
9056         if (IS_CANNONLAKE(dev_priv))
9057                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9058         else if (IS_GEN9_BC(dev_priv))
9059                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9060         else if (IS_GEN9_LP(dev_priv))
9061                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9062         else
9063                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9064
9065         pll = pipe_config->shared_dpll;
9066         if (pll) {
9067                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9068                                                  &pipe_config->dpll_hw_state));
9069         }
9070
9071         /*
9072          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9073          * DDI E. So just check whether this pipe is wired to DDI E and whether
9074          * the PCH transcoder is on.
9075          */
9076         if (INTEL_GEN(dev_priv) < 9 &&
9077             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9078                 pipe_config->has_pch_encoder = true;
9079
9080                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9081                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9082                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9083
9084                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9085         }
9086 }
9087
9088 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9089                                     struct intel_crtc_state *pipe_config)
9090 {
9091         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9092         enum intel_display_power_domain power_domain;
9093         u64 power_domain_mask;
9094         bool active;
9095
9096         if (INTEL_GEN(dev_priv) >= 9) {
9097                 intel_crtc_init_scalers(crtc, pipe_config);
9098
9099                 pipe_config->scaler_state.scaler_id = -1;
9100                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9101         }
9102
9103         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9104         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9105                 return false;
9106         power_domain_mask = BIT_ULL(power_domain);
9107
9108         pipe_config->shared_dpll = NULL;
9109
9110         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9111
9112         if (IS_GEN9_LP(dev_priv) &&
9113             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9114                 WARN_ON(active);
9115                 active = true;
9116         }
9117
9118         if (!active)
9119                 goto out;
9120
9121         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9122                 haswell_get_ddi_port_state(crtc, pipe_config);
9123                 intel_get_pipe_timings(crtc, pipe_config);
9124         }
9125
9126         intel_get_pipe_src_size(crtc, pipe_config);
9127
9128         pipe_config->gamma_mode =
9129                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9130
9131         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9132         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9133                 power_domain_mask |= BIT_ULL(power_domain);
9134                 if (INTEL_GEN(dev_priv) >= 9)
9135                         skylake_get_pfit_config(crtc, pipe_config);
9136                 else
9137                         ironlake_get_pfit_config(crtc, pipe_config);
9138         }
9139
9140         if (IS_HASWELL(dev_priv))
9141                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9142                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9143
9144         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9145             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9146                 pipe_config->pixel_multiplier =
9147                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9148         } else {
9149                 pipe_config->pixel_multiplier = 1;
9150         }
9151
9152 out:
9153         for_each_power_domain(power_domain, power_domain_mask)
9154                 intel_display_power_put(dev_priv, power_domain);
9155
9156         return active;
9157 }
9158
9159 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9160 {
9161         struct drm_i915_private *dev_priv =
9162                 to_i915(plane_state->base.plane->dev);
9163         const struct drm_framebuffer *fb = plane_state->base.fb;
9164         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9165         u32 base;
9166
9167         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9168                 base = obj->phys_handle->busaddr;
9169         else
9170                 base = intel_plane_ggtt_offset(plane_state);
9171
9172         base += plane_state->main.offset;
9173
9174         /* ILK+ do this automagically */
9175         if (HAS_GMCH_DISPLAY(dev_priv) &&
9176             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9177                 base += (plane_state->base.crtc_h *
9178                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9179
9180         return base;
9181 }
9182
9183 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9184 {
9185         int x = plane_state->base.crtc_x;
9186         int y = plane_state->base.crtc_y;
9187         u32 pos = 0;
9188
9189         if (x < 0) {
9190                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9191                 x = -x;
9192         }
9193         pos |= x << CURSOR_X_SHIFT;
9194
9195         if (y < 0) {
9196                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9197                 y = -y;
9198         }
9199         pos |= y << CURSOR_Y_SHIFT;
9200
9201         return pos;
9202 }
9203
9204 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9205 {
9206         const struct drm_mode_config *config =
9207                 &plane_state->base.plane->dev->mode_config;
9208         int width = plane_state->base.crtc_w;
9209         int height = plane_state->base.crtc_h;
9210
9211         return width > 0 && width <= config->cursor_width &&
9212                 height > 0 && height <= config->cursor_height;
9213 }
9214
9215 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9216                               struct intel_plane_state *plane_state)
9217 {
9218         const struct drm_framebuffer *fb = plane_state->base.fb;
9219         int src_x, src_y;
9220         u32 offset;
9221         int ret;
9222
9223         ret = drm_plane_helper_check_state(&plane_state->base,
9224                                            &plane_state->clip,
9225                                            DRM_PLANE_HELPER_NO_SCALING,
9226                                            DRM_PLANE_HELPER_NO_SCALING,
9227                                            true, true);
9228         if (ret)
9229                 return ret;
9230
9231         if (!fb)
9232                 return 0;
9233
9234         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9235                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9236                 return -EINVAL;
9237         }
9238
9239         src_x = plane_state->base.src_x >> 16;
9240         src_y = plane_state->base.src_y >> 16;
9241
9242         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9243         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9244
9245         if (src_x != 0 || src_y != 0) {
9246                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9247                 return -EINVAL;
9248         }
9249
9250         plane_state->main.offset = offset;
9251
9252         return 0;
9253 }
9254
9255 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9256                            const struct intel_plane_state *plane_state)
9257 {
9258         const struct drm_framebuffer *fb = plane_state->base.fb;
9259
9260         return CURSOR_ENABLE |
9261                 CURSOR_GAMMA_ENABLE |
9262                 CURSOR_FORMAT_ARGB |
9263                 CURSOR_STRIDE(fb->pitches[0]);
9264 }
9265
9266 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9267 {
9268         int width = plane_state->base.crtc_w;
9269
9270         /*
9271          * 845g/865g are only limited by the width of their cursors,
9272          * the height is arbitrary up to the precision of the register.
9273          */
9274         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9275 }
9276
9277 static int i845_check_cursor(struct intel_plane *plane,
9278                              struct intel_crtc_state *crtc_state,
9279                              struct intel_plane_state *plane_state)
9280 {
9281         const struct drm_framebuffer *fb = plane_state->base.fb;
9282         int ret;
9283
9284         ret = intel_check_cursor(crtc_state, plane_state);
9285         if (ret)
9286                 return ret;
9287
9288         /* if we want to turn off the cursor ignore width and height */
9289         if (!fb)
9290                 return 0;
9291
9292         /* Check for which cursor types we support */
9293         if (!i845_cursor_size_ok(plane_state)) {
9294                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9295                           plane_state->base.crtc_w,
9296                           plane_state->base.crtc_h);
9297                 return -EINVAL;
9298         }
9299
9300         switch (fb->pitches[0]) {
9301         case 256:
9302         case 512:
9303         case 1024:
9304         case 2048:
9305                 break;
9306         default:
9307                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9308                               fb->pitches[0]);
9309                 return -EINVAL;
9310         }
9311
9312         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9313
9314         return 0;
9315 }
9316
9317 static void i845_update_cursor(struct intel_plane *plane,
9318                                const struct intel_crtc_state *crtc_state,
9319                                const struct intel_plane_state *plane_state)
9320 {
9321         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9322         u32 cntl = 0, base = 0, pos = 0, size = 0;
9323         unsigned long irqflags;
9324
9325         if (plane_state && plane_state->base.visible) {
9326                 unsigned int width = plane_state->base.crtc_w;
9327                 unsigned int height = plane_state->base.crtc_h;
9328
9329                 cntl = plane_state->ctl;
9330                 size = (height << 12) | width;
9331
9332                 base = intel_cursor_base(plane_state);
9333                 pos = intel_cursor_position(plane_state);
9334         }
9335
9336         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9337
9338         /* On these chipsets we can only modify the base/size/stride
9339          * whilst the cursor is disabled.
9340          */
9341         if (plane->cursor.base != base ||
9342             plane->cursor.size != size ||
9343             plane->cursor.cntl != cntl) {
9344                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9345                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9346                 I915_WRITE_FW(CURSIZE, size);
9347                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9348                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9349
9350                 plane->cursor.base = base;
9351                 plane->cursor.size = size;
9352                 plane->cursor.cntl = cntl;
9353         } else {
9354                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9355         }
9356
9357         POSTING_READ_FW(CURCNTR(PIPE_A));
9358
9359         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9360 }
9361
9362 static void i845_disable_cursor(struct intel_plane *plane,
9363                                 struct intel_crtc *crtc)
9364 {
9365         i845_update_cursor(plane, NULL, NULL);
9366 }
9367
9368 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9369                            const struct intel_plane_state *plane_state)
9370 {
9371         struct drm_i915_private *dev_priv =
9372                 to_i915(plane_state->base.plane->dev);
9373         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9374         u32 cntl;
9375
9376         cntl = MCURSOR_GAMMA_ENABLE;
9377
9378         if (HAS_DDI(dev_priv))
9379                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9380
9381         cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9382
9383         switch (plane_state->base.crtc_w) {
9384         case 64:
9385                 cntl |= CURSOR_MODE_64_ARGB_AX;
9386                 break;
9387         case 128:
9388                 cntl |= CURSOR_MODE_128_ARGB_AX;
9389                 break;
9390         case 256:
9391                 cntl |= CURSOR_MODE_256_ARGB_AX;
9392                 break;
9393         default:
9394                 MISSING_CASE(plane_state->base.crtc_w);
9395                 return 0;
9396         }
9397
9398         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9399                 cntl |= CURSOR_ROTATE_180;
9400
9401         return cntl;
9402 }
9403
9404 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9405 {
9406         struct drm_i915_private *dev_priv =
9407                 to_i915(plane_state->base.plane->dev);
9408         int width = plane_state->base.crtc_w;
9409         int height = plane_state->base.crtc_h;
9410
9411         if (!intel_cursor_size_ok(plane_state))
9412                 return false;
9413
9414         /* Cursor width is limited to a few power-of-two sizes */
9415         switch (width) {
9416         case 256:
9417         case 128:
9418         case 64:
9419                 break;
9420         default:
9421                 return false;
9422         }
9423
9424         /*
9425          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9426          * height from 8 lines up to the cursor width, when the
9427          * cursor is not rotated. Everything else requires square
9428          * cursors.
9429          */
9430         if (HAS_CUR_FBC(dev_priv) &&
9431             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9432                 if (height < 8 || height > width)
9433                         return false;
9434         } else {
9435                 if (height != width)
9436                         return false;
9437         }
9438
9439         return true;
9440 }
9441
9442 static int i9xx_check_cursor(struct intel_plane *plane,
9443                              struct intel_crtc_state *crtc_state,
9444                              struct intel_plane_state *plane_state)
9445 {
9446         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9447         const struct drm_framebuffer *fb = plane_state->base.fb;
9448         enum pipe pipe = plane->pipe;
9449         int ret;
9450
9451         ret = intel_check_cursor(crtc_state, plane_state);
9452         if (ret)
9453                 return ret;
9454
9455         /* if we want to turn off the cursor ignore width and height */
9456         if (!fb)
9457                 return 0;
9458
9459         /* Check for which cursor types we support */
9460         if (!i9xx_cursor_size_ok(plane_state)) {
9461                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9462                           plane_state->base.crtc_w,
9463                           plane_state->base.crtc_h);
9464                 return -EINVAL;
9465         }
9466
9467         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9468                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9469                               fb->pitches[0], plane_state->base.crtc_w);
9470                 return -EINVAL;
9471         }
9472
9473         /*
9474          * There's something wrong with the cursor on CHV pipe C.
9475          * If it straddles the left edge of the screen then
9476          * moving it away from the edge or disabling it often
9477          * results in a pipe underrun, and often that can lead to
9478          * dead pipe (constant underrun reported, and it scans
9479          * out just a solid color). To recover from that, the
9480          * display power well must be turned off and on again.
9481          * Refuse the put the cursor into that compromised position.
9482          */
9483         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9484             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9485                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9486                 return -EINVAL;
9487         }
9488
9489         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9490
9491         return 0;
9492 }
9493
9494 static void i9xx_update_cursor(struct intel_plane *plane,
9495                                const struct intel_crtc_state *crtc_state,
9496                                const struct intel_plane_state *plane_state)
9497 {
9498         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9499         enum pipe pipe = plane->pipe;
9500         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9501         unsigned long irqflags;
9502
9503         if (plane_state && plane_state->base.visible) {
9504                 cntl = plane_state->ctl;
9505
9506                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9507                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9508
9509                 base = intel_cursor_base(plane_state);
9510                 pos = intel_cursor_position(plane_state);
9511         }
9512
9513         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9514
9515         /*
9516          * On some platforms writing CURCNTR first will also
9517          * cause CURPOS to be armed by the CURBASE write.
9518          * Without the CURCNTR write the CURPOS write would
9519          * arm itself. Thus we always start the full update
9520          * with a CURCNTR write.
9521          *
9522          * On other platforms CURPOS always requires the
9523          * CURBASE write to arm the update. Additonally
9524          * a write to any of the cursor register will cancel
9525          * an already armed cursor update. Thus leaving out
9526          * the CURBASE write after CURPOS could lead to a
9527          * cursor that doesn't appear to move, or even change
9528          * shape. Thus we always write CURBASE.
9529          *
9530          * CURCNTR and CUR_FBC_CTL are always
9531          * armed by the CURBASE write only.
9532          */
9533         if (plane->cursor.base != base ||
9534             plane->cursor.size != fbc_ctl ||
9535             plane->cursor.cntl != cntl) {
9536                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9537                 if (HAS_CUR_FBC(dev_priv))
9538                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9539                 I915_WRITE_FW(CURPOS(pipe), pos);
9540                 I915_WRITE_FW(CURBASE(pipe), base);
9541
9542                 plane->cursor.base = base;
9543                 plane->cursor.size = fbc_ctl;
9544                 plane->cursor.cntl = cntl;
9545         } else {
9546                 I915_WRITE_FW(CURPOS(pipe), pos);
9547                 I915_WRITE_FW(CURBASE(pipe), base);
9548         }
9549
9550         POSTING_READ_FW(CURBASE(pipe));
9551
9552         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9553 }
9554
9555 static void i9xx_disable_cursor(struct intel_plane *plane,
9556                                 struct intel_crtc *crtc)
9557 {
9558         i9xx_update_cursor(plane, NULL, NULL);
9559 }
9560
9561
9562 /* VESA 640x480x72Hz mode to set on the pipe */
9563 static struct drm_display_mode load_detect_mode = {
9564         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9565                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9566 };
9567
9568 struct drm_framebuffer *
9569 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9570                          struct drm_mode_fb_cmd2 *mode_cmd)
9571 {
9572         struct intel_framebuffer *intel_fb;
9573         int ret;
9574
9575         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9576         if (!intel_fb)
9577                 return ERR_PTR(-ENOMEM);
9578
9579         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9580         if (ret)
9581                 goto err;
9582
9583         return &intel_fb->base;
9584
9585 err:
9586         kfree(intel_fb);
9587         return ERR_PTR(ret);
9588 }
9589
9590 static u32
9591 intel_framebuffer_pitch_for_width(int width, int bpp)
9592 {
9593         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
9594         return ALIGN(pitch, 64);
9595 }
9596
9597 static u32
9598 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
9599 {
9600         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
9601         return PAGE_ALIGN(pitch * mode->vdisplay);
9602 }
9603
9604 static struct drm_framebuffer *
9605 intel_framebuffer_create_for_mode(struct drm_device *dev,
9606                                   struct drm_display_mode *mode,
9607                                   int depth, int bpp)
9608 {
9609         struct drm_framebuffer *fb;
9610         struct drm_i915_gem_object *obj;
9611         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
9612
9613         obj = i915_gem_object_create(to_i915(dev),
9614                                     intel_framebuffer_size_for_mode(mode, bpp));
9615         if (IS_ERR(obj))
9616                 return ERR_CAST(obj);
9617
9618         mode_cmd.width = mode->hdisplay;
9619         mode_cmd.height = mode->vdisplay;
9620         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
9621                                                                 bpp);
9622         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
9623
9624         fb = intel_framebuffer_create(obj, &mode_cmd);
9625         if (IS_ERR(fb))
9626                 i915_gem_object_put(obj);
9627
9628         return fb;
9629 }
9630
9631 static struct drm_framebuffer *
9632 mode_fits_in_fbdev(struct drm_device *dev,
9633                    struct drm_display_mode *mode)
9634 {
9635 #ifdef CONFIG_DRM_FBDEV_EMULATION
9636         struct drm_i915_private *dev_priv = to_i915(dev);
9637         struct drm_i915_gem_object *obj;
9638         struct drm_framebuffer *fb;
9639
9640         if (!dev_priv->fbdev)
9641                 return NULL;
9642
9643         if (!dev_priv->fbdev->fb)
9644                 return NULL;
9645
9646         obj = dev_priv->fbdev->fb->obj;
9647         BUG_ON(!obj);
9648
9649         fb = &dev_priv->fbdev->fb->base;
9650         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
9651                                                                fb->format->cpp[0] * 8))
9652                 return NULL;
9653
9654         if (obj->base.size < mode->vdisplay * fb->pitches[0])
9655                 return NULL;
9656
9657         drm_framebuffer_reference(fb);
9658         return fb;
9659 #else
9660         return NULL;
9661 #endif
9662 }
9663
9664 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
9665                                            struct drm_crtc *crtc,
9666                                            struct drm_display_mode *mode,
9667                                            struct drm_framebuffer *fb,
9668                                            int x, int y)
9669 {
9670         struct drm_plane_state *plane_state;
9671         int hdisplay, vdisplay;
9672         int ret;
9673
9674         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
9675         if (IS_ERR(plane_state))
9676                 return PTR_ERR(plane_state);
9677
9678         if (mode)
9679                 drm_mode_get_hv_timing(mode, &hdisplay, &vdisplay);
9680         else
9681                 hdisplay = vdisplay = 0;
9682
9683         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
9684         if (ret)
9685                 return ret;
9686         drm_atomic_set_fb_for_plane(plane_state, fb);
9687         plane_state->crtc_x = 0;
9688         plane_state->crtc_y = 0;
9689         plane_state->crtc_w = hdisplay;
9690         plane_state->crtc_h = vdisplay;
9691         plane_state->src_x = x << 16;
9692         plane_state->src_y = y << 16;
9693         plane_state->src_w = hdisplay << 16;
9694         plane_state->src_h = vdisplay << 16;
9695
9696         return 0;
9697 }
9698
9699 int intel_get_load_detect_pipe(struct drm_connector *connector,
9700                                struct drm_display_mode *mode,
9701                                struct intel_load_detect_pipe *old,
9702                                struct drm_modeset_acquire_ctx *ctx)
9703 {
9704         struct intel_crtc *intel_crtc;
9705         struct intel_encoder *intel_encoder =
9706                 intel_attached_encoder(connector);
9707         struct drm_crtc *possible_crtc;
9708         struct drm_encoder *encoder = &intel_encoder->base;
9709         struct drm_crtc *crtc = NULL;
9710         struct drm_device *dev = encoder->dev;
9711         struct drm_i915_private *dev_priv = to_i915(dev);
9712         struct drm_framebuffer *fb;
9713         struct drm_mode_config *config = &dev->mode_config;
9714         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9715         struct drm_connector_state *connector_state;
9716         struct intel_crtc_state *crtc_state;
9717         int ret, i = -1;
9718
9719         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9720                       connector->base.id, connector->name,
9721                       encoder->base.id, encoder->name);
9722
9723         old->restore_state = NULL;
9724
9725         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9726
9727         /*
9728          * Algorithm gets a little messy:
9729          *
9730          *   - if the connector already has an assigned crtc, use it (but make
9731          *     sure it's on first)
9732          *
9733          *   - try to find the first unused crtc that can drive this connector,
9734          *     and use that if we find one
9735          */
9736
9737         /* See if we already have a CRTC for this connector */
9738         if (connector->state->crtc) {
9739                 crtc = connector->state->crtc;
9740
9741                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9742                 if (ret)
9743                         goto fail;
9744
9745                 /* Make sure the crtc and connector are running */
9746                 goto found;
9747         }
9748
9749         /* Find an unused one (if possible) */
9750         for_each_crtc(dev, possible_crtc) {
9751                 i++;
9752                 if (!(encoder->possible_crtcs & (1 << i)))
9753                         continue;
9754
9755                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9756                 if (ret)
9757                         goto fail;
9758
9759                 if (possible_crtc->state->enable) {
9760                         drm_modeset_unlock(&possible_crtc->mutex);
9761                         continue;
9762                 }
9763
9764                 crtc = possible_crtc;
9765                 break;
9766         }
9767
9768         /*
9769          * If we didn't find an unused CRTC, don't use any.
9770          */
9771         if (!crtc) {
9772                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9773                 ret = -ENODEV;
9774                 goto fail;
9775         }
9776
9777 found:
9778         intel_crtc = to_intel_crtc(crtc);
9779
9780         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
9781         if (ret)
9782                 goto fail;
9783
9784         state = drm_atomic_state_alloc(dev);
9785         restore_state = drm_atomic_state_alloc(dev);
9786         if (!state || !restore_state) {
9787                 ret = -ENOMEM;
9788                 goto fail;
9789         }
9790
9791         state->acquire_ctx = ctx;
9792         restore_state->acquire_ctx = ctx;
9793
9794         connector_state = drm_atomic_get_connector_state(state, connector);
9795         if (IS_ERR(connector_state)) {
9796                 ret = PTR_ERR(connector_state);
9797                 goto fail;
9798         }
9799
9800         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
9801         if (ret)
9802                 goto fail;
9803
9804         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9805         if (IS_ERR(crtc_state)) {
9806                 ret = PTR_ERR(crtc_state);
9807                 goto fail;
9808         }
9809
9810         crtc_state->base.active = crtc_state->base.enable = true;
9811
9812         if (!mode)
9813                 mode = &load_detect_mode;
9814
9815         /* We need a framebuffer large enough to accommodate all accesses
9816          * that the plane may generate whilst we perform load detection.
9817          * We can not rely on the fbcon either being present (we get called
9818          * during its initialisation to detect all boot displays, or it may
9819          * not even exist) or that it is large enough to satisfy the
9820          * requested mode.
9821          */
9822         fb = mode_fits_in_fbdev(dev, mode);
9823         if (fb == NULL) {
9824                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
9825                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
9826         } else
9827                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
9828         if (IS_ERR(fb)) {
9829                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
9830                 ret = PTR_ERR(fb);
9831                 goto fail;
9832         }
9833
9834         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
9835         if (ret)
9836                 goto fail;
9837
9838         drm_framebuffer_unreference(fb);
9839
9840         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
9841         if (ret)
9842                 goto fail;
9843
9844         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
9845         if (!ret)
9846                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
9847         if (!ret)
9848                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
9849         if (ret) {
9850                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
9851                 goto fail;
9852         }
9853
9854         ret = drm_atomic_commit(state);
9855         if (ret) {
9856                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9857                 goto fail;
9858         }
9859
9860         old->restore_state = restore_state;
9861         drm_atomic_state_put(state);
9862
9863         /* let the connector get through one full cycle before testing */
9864         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
9865         return true;
9866
9867 fail:
9868         if (state) {
9869                 drm_atomic_state_put(state);
9870                 state = NULL;
9871         }
9872         if (restore_state) {
9873                 drm_atomic_state_put(restore_state);
9874                 restore_state = NULL;
9875         }
9876
9877         if (ret == -EDEADLK)
9878                 return ret;
9879
9880         return false;
9881 }
9882
9883 void intel_release_load_detect_pipe(struct drm_connector *connector,
9884                                     struct intel_load_detect_pipe *old,
9885                                     struct drm_modeset_acquire_ctx *ctx)
9886 {
9887         struct intel_encoder *intel_encoder =
9888                 intel_attached_encoder(connector);
9889         struct drm_encoder *encoder = &intel_encoder->base;
9890         struct drm_atomic_state *state = old->restore_state;
9891         int ret;
9892
9893         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9894                       connector->base.id, connector->name,
9895                       encoder->base.id, encoder->name);
9896
9897         if (!state)
9898                 return;
9899
9900         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
9901         if (ret)
9902                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
9903         drm_atomic_state_put(state);
9904 }
9905
9906 static int i9xx_pll_refclk(struct drm_device *dev,
9907                            const struct intel_crtc_state *pipe_config)
9908 {
9909         struct drm_i915_private *dev_priv = to_i915(dev);
9910         u32 dpll = pipe_config->dpll_hw_state.dpll;
9911
9912         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
9913                 return dev_priv->vbt.lvds_ssc_freq;
9914         else if (HAS_PCH_SPLIT(dev_priv))
9915                 return 120000;
9916         else if (!IS_GEN2(dev_priv))
9917                 return 96000;
9918         else
9919                 return 48000;
9920 }
9921
9922 /* Returns the clock of the currently programmed mode of the given pipe. */
9923 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
9924                                 struct intel_crtc_state *pipe_config)
9925 {
9926         struct drm_device *dev = crtc->base.dev;
9927         struct drm_i915_private *dev_priv = to_i915(dev);
9928         int pipe = pipe_config->cpu_transcoder;
9929         u32 dpll = pipe_config->dpll_hw_state.dpll;
9930         u32 fp;
9931         struct dpll clock;
9932         int port_clock;
9933         int refclk = i9xx_pll_refclk(dev, pipe_config);
9934
9935         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
9936                 fp = pipe_config->dpll_hw_state.fp0;
9937         else
9938                 fp = pipe_config->dpll_hw_state.fp1;
9939
9940         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
9941         if (IS_PINEVIEW(dev_priv)) {
9942                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
9943                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
9944         } else {
9945                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
9946                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
9947         }
9948
9949         if (!IS_GEN2(dev_priv)) {
9950                 if (IS_PINEVIEW(dev_priv))
9951                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
9952                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
9953                 else
9954                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
9955                                DPLL_FPA01_P1_POST_DIV_SHIFT);
9956
9957                 switch (dpll & DPLL_MODE_MASK) {
9958                 case DPLLB_MODE_DAC_SERIAL:
9959                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
9960                                 5 : 10;
9961                         break;
9962                 case DPLLB_MODE_LVDS:
9963                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
9964                                 7 : 14;
9965                         break;
9966                 default:
9967                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
9968                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
9969                         return;
9970                 }
9971
9972                 if (IS_PINEVIEW(dev_priv))
9973                         port_clock = pnv_calc_dpll_params(refclk, &clock);
9974                 else
9975                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
9976         } else {
9977                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
9978                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
9979
9980                 if (is_lvds) {
9981                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
9982                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
9983
9984                         if (lvds & LVDS_CLKB_POWER_UP)
9985                                 clock.p2 = 7;
9986                         else
9987                                 clock.p2 = 14;
9988                 } else {
9989                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
9990                                 clock.p1 = 2;
9991                         else {
9992                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
9993                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
9994                         }
9995                         if (dpll & PLL_P2_DIVIDE_BY_4)
9996                                 clock.p2 = 4;
9997                         else
9998                                 clock.p2 = 2;
9999                 }
10000
10001                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10002         }
10003
10004         /*
10005          * This value includes pixel_multiplier. We will use
10006          * port_clock to compute adjusted_mode.crtc_clock in the
10007          * encoder's get_config() function.
10008          */
10009         pipe_config->port_clock = port_clock;
10010 }
10011
10012 int intel_dotclock_calculate(int link_freq,
10013                              const struct intel_link_m_n *m_n)
10014 {
10015         /*
10016          * The calculation for the data clock is:
10017          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10018          * But we want to avoid losing precison if possible, so:
10019          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10020          *
10021          * and the link clock is simpler:
10022          * link_clock = (m * link_clock) / n
10023          */
10024
10025         if (!m_n->link_n)
10026                 return 0;
10027
10028         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10029 }
10030
10031 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10032                                    struct intel_crtc_state *pipe_config)
10033 {
10034         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10035
10036         /* read out port_clock from the DPLL */
10037         i9xx_crtc_clock_get(crtc, pipe_config);
10038
10039         /*
10040          * In case there is an active pipe without active ports,
10041          * we may need some idea for the dotclock anyway.
10042          * Calculate one based on the FDI configuration.
10043          */
10044         pipe_config->base.adjusted_mode.crtc_clock =
10045                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10046                                          &pipe_config->fdi_m_n);
10047 }
10048
10049 /** Returns the currently programmed mode of the given pipe. */
10050 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10051                                              struct drm_crtc *crtc)
10052 {
10053         struct drm_i915_private *dev_priv = to_i915(dev);
10054         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10055         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10056         struct drm_display_mode *mode;
10057         struct intel_crtc_state *pipe_config;
10058         int htot = I915_READ(HTOTAL(cpu_transcoder));
10059         int hsync = I915_READ(HSYNC(cpu_transcoder));
10060         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10061         int vsync = I915_READ(VSYNC(cpu_transcoder));
10062         enum pipe pipe = intel_crtc->pipe;
10063
10064         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10065         if (!mode)
10066                 return NULL;
10067
10068         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10069         if (!pipe_config) {
10070                 kfree(mode);
10071                 return NULL;
10072         }
10073
10074         /*
10075          * Construct a pipe_config sufficient for getting the clock info
10076          * back out of crtc_clock_get.
10077          *
10078          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10079          * to use a real value here instead.
10080          */
10081         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10082         pipe_config->pixel_multiplier = 1;
10083         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10084         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10085         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10086         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10087
10088         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10089         mode->hdisplay = (htot & 0xffff) + 1;
10090         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10091         mode->hsync_start = (hsync & 0xffff) + 1;
10092         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10093         mode->vdisplay = (vtot & 0xffff) + 1;
10094         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10095         mode->vsync_start = (vsync & 0xffff) + 1;
10096         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10097
10098         drm_mode_set_name(mode);
10099
10100         kfree(pipe_config);
10101
10102         return mode;
10103 }
10104
10105 static void intel_crtc_destroy(struct drm_crtc *crtc)
10106 {
10107         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10108         struct drm_device *dev = crtc->dev;
10109         struct intel_flip_work *work;
10110
10111         spin_lock_irq(&dev->event_lock);
10112         work = intel_crtc->flip_work;
10113         intel_crtc->flip_work = NULL;
10114         spin_unlock_irq(&dev->event_lock);
10115
10116         if (work) {
10117                 cancel_work_sync(&work->mmio_work);
10118                 cancel_work_sync(&work->unpin_work);
10119                 kfree(work);
10120         }
10121
10122         drm_crtc_cleanup(crtc);
10123
10124         kfree(intel_crtc);
10125 }
10126
10127 static void intel_unpin_work_fn(struct work_struct *__work)
10128 {
10129         struct intel_flip_work *work =
10130                 container_of(__work, struct intel_flip_work, unpin_work);
10131         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10132         struct drm_device *dev = crtc->base.dev;
10133         struct drm_plane *primary = crtc->base.primary;
10134
10135         if (is_mmio_work(work))
10136                 flush_work(&work->mmio_work);
10137
10138         mutex_lock(&dev->struct_mutex);
10139         intel_unpin_fb_vma(work->old_vma);
10140         i915_gem_object_put(work->pending_flip_obj);
10141         mutex_unlock(&dev->struct_mutex);
10142
10143         i915_gem_request_put(work->flip_queued_req);
10144
10145         intel_frontbuffer_flip_complete(to_i915(dev),
10146                                         to_intel_plane(primary)->frontbuffer_bit);
10147         intel_fbc_post_update(crtc);
10148         drm_framebuffer_unreference(work->old_fb);
10149
10150         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10151         atomic_dec(&crtc->unpin_work_count);
10152
10153         kfree(work);
10154 }
10155
10156 /* Is 'a' after or equal to 'b'? */
10157 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10158 {
10159         return !((a - b) & 0x80000000);
10160 }
10161
10162 static bool __pageflip_finished_cs(struct intel_crtc *crtc,
10163                                    struct intel_flip_work *work)
10164 {
10165         struct drm_device *dev = crtc->base.dev;
10166         struct drm_i915_private *dev_priv = to_i915(dev);
10167
10168         if (abort_flip_on_reset(crtc))
10169                 return true;
10170
10171         /*
10172          * The relevant registers doen't exist on pre-ctg.
10173          * As the flip done interrupt doesn't trigger for mmio
10174          * flips on gmch platforms, a flip count check isn't
10175          * really needed there. But since ctg has the registers,
10176          * include it in the check anyway.
10177          */
10178         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10179                 return true;
10180
10181         /*
10182          * BDW signals flip done immediately if the plane
10183          * is disabled, even if the plane enable is already
10184          * armed to occur at the next vblank :(
10185          */
10186
10187         /*
10188          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10189          * used the same base address. In that case the mmio flip might
10190          * have completed, but the CS hasn't even executed the flip yet.
10191          *
10192          * A flip count check isn't enough as the CS might have updated
10193          * the base address just after start of vblank, but before we
10194          * managed to process the interrupt. This means we'd complete the
10195          * CS flip too soon.
10196          *
10197          * Combining both checks should get us a good enough result. It may
10198          * still happen that the CS flip has been executed, but has not
10199          * yet actually completed. But in case the base address is the same
10200          * anyway, we don't really care.
10201          */
10202         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10203                 crtc->flip_work->gtt_offset &&
10204                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10205                                     crtc->flip_work->flip_count);
10206 }
10207
10208 static bool
10209 __pageflip_finished_mmio(struct intel_crtc *crtc,
10210                                struct intel_flip_work *work)
10211 {
10212         /*
10213          * MMIO work completes when vblank is different from
10214          * flip_queued_vblank.
10215          *
10216          * Reset counter value doesn't matter, this is handled by
10217          * i915_wait_request finishing early, so no need to handle
10218          * reset here.
10219          */
10220         return intel_crtc_get_vblank_counter(crtc) != work->flip_queued_vblank;
10221 }
10222
10223
10224 static bool pageflip_finished(struct intel_crtc *crtc,
10225                               struct intel_flip_work *work)
10226 {
10227         if (!atomic_read(&work->pending))
10228                 return false;
10229
10230         smp_rmb();
10231
10232         if (is_mmio_work(work))
10233                 return __pageflip_finished_mmio(crtc, work);
10234         else
10235                 return __pageflip_finished_cs(crtc, work);
10236 }
10237
10238 void intel_finish_page_flip_cs(struct drm_i915_private *dev_priv, int pipe)
10239 {
10240         struct drm_device *dev = &dev_priv->drm;
10241         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10242         struct intel_flip_work *work;
10243         unsigned long flags;
10244
10245         /* Ignore early vblank irqs */
10246         if (!crtc)
10247                 return;
10248
10249         /*
10250          * This is called both by irq handlers and the reset code (to complete
10251          * lost pageflips) so needs the full irqsave spinlocks.
10252          */
10253         spin_lock_irqsave(&dev->event_lock, flags);
10254         work = crtc->flip_work;
10255
10256         if (work != NULL &&
10257             !is_mmio_work(work) &&
10258             pageflip_finished(crtc, work))
10259                 page_flip_completed(crtc);
10260
10261         spin_unlock_irqrestore(&dev->event_lock, flags);
10262 }
10263
10264 void intel_finish_page_flip_mmio(struct drm_i915_private *dev_priv, int pipe)
10265 {
10266         struct drm_device *dev = &dev_priv->drm;
10267         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10268         struct intel_flip_work *work;
10269         unsigned long flags;
10270
10271         /* Ignore early vblank irqs */
10272         if (!crtc)
10273                 return;
10274
10275         /*
10276          * This is called both by irq handlers and the reset code (to complete
10277          * lost pageflips) so needs the full irqsave spinlocks.
10278          */
10279         spin_lock_irqsave(&dev->event_lock, flags);
10280         work = crtc->flip_work;
10281
10282         if (work != NULL &&
10283             is_mmio_work(work) &&
10284             pageflip_finished(crtc, work))
10285                 page_flip_completed(crtc);
10286
10287         spin_unlock_irqrestore(&dev->event_lock, flags);
10288 }
10289
10290 static inline void intel_mark_page_flip_active(struct intel_crtc *crtc,
10291                                                struct intel_flip_work *work)
10292 {
10293         work->flip_queued_vblank = intel_crtc_get_vblank_counter(crtc);
10294
10295         /* Ensure that the work item is consistent when activating it ... */
10296         smp_mb__before_atomic();
10297         atomic_set(&work->pending, 1);
10298 }
10299
10300 static int intel_gen2_queue_flip(struct drm_device *dev,
10301                                  struct drm_crtc *crtc,
10302                                  struct drm_framebuffer *fb,
10303                                  struct drm_i915_gem_object *obj,
10304                                  struct drm_i915_gem_request *req,
10305                                  uint32_t flags)
10306 {
10307         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10308         u32 flip_mask, *cs;
10309
10310         cs = intel_ring_begin(req, 6);
10311         if (IS_ERR(cs))
10312                 return PTR_ERR(cs);
10313
10314         /* Can't queue multiple flips, so wait for the previous
10315          * one to finish before executing the next.
10316          */
10317         if (intel_crtc->plane)
10318                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10319         else
10320                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10321         *cs++ = MI_WAIT_FOR_EVENT | flip_mask;
10322         *cs++ = MI_NOOP;
10323         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10324         *cs++ = fb->pitches[0];
10325         *cs++ = intel_crtc->flip_work->gtt_offset;
10326         *cs++ = 0; /* aux display base address, unused */
10327
10328         return 0;
10329 }
10330
10331 static int intel_gen3_queue_flip(struct drm_device *dev,
10332                                  struct drm_crtc *crtc,
10333                                  struct drm_framebuffer *fb,
10334                                  struct drm_i915_gem_object *obj,
10335                                  struct drm_i915_gem_request *req,
10336                                  uint32_t flags)
10337 {
10338         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10339         u32 flip_mask, *cs;
10340
10341         cs = intel_ring_begin(req, 6);
10342         if (IS_ERR(cs))
10343                 return PTR_ERR(cs);
10344
10345         if (intel_crtc->plane)
10346                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10347         else
10348                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10349         *cs++ = MI_WAIT_FOR_EVENT | flip_mask;
10350         *cs++ = MI_NOOP;
10351         *cs++ = MI_DISPLAY_FLIP_I915 | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10352         *cs++ = fb->pitches[0];
10353         *cs++ = intel_crtc->flip_work->gtt_offset;
10354         *cs++ = MI_NOOP;
10355
10356         return 0;
10357 }
10358
10359 static int intel_gen4_queue_flip(struct drm_device *dev,
10360                                  struct drm_crtc *crtc,
10361                                  struct drm_framebuffer *fb,
10362                                  struct drm_i915_gem_object *obj,
10363                                  struct drm_i915_gem_request *req,
10364                                  uint32_t flags)
10365 {
10366         struct drm_i915_private *dev_priv = to_i915(dev);
10367         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10368         u32 pf, pipesrc, *cs;
10369
10370         cs = intel_ring_begin(req, 4);
10371         if (IS_ERR(cs))
10372                 return PTR_ERR(cs);
10373
10374         /* i965+ uses the linear or tiled offsets from the
10375          * Display Registers (which do not change across a page-flip)
10376          * so we need only reprogram the base address.
10377          */
10378         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10379         *cs++ = fb->pitches[0];
10380         *cs++ = intel_crtc->flip_work->gtt_offset |
10381                 intel_fb_modifier_to_tiling(fb->modifier);
10382
10383         /* XXX Enabling the panel-fitter across page-flip is so far
10384          * untested on non-native modes, so ignore it for now.
10385          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
10386          */
10387         pf = 0;
10388         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10389         *cs++ = pf | pipesrc;
10390
10391         return 0;
10392 }
10393
10394 static int intel_gen6_queue_flip(struct drm_device *dev,
10395                                  struct drm_crtc *crtc,
10396                                  struct drm_framebuffer *fb,
10397                                  struct drm_i915_gem_object *obj,
10398                                  struct drm_i915_gem_request *req,
10399                                  uint32_t flags)
10400 {
10401         struct drm_i915_private *dev_priv = to_i915(dev);
10402         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10403         u32 pf, pipesrc, *cs;
10404
10405         cs = intel_ring_begin(req, 4);
10406         if (IS_ERR(cs))
10407                 return PTR_ERR(cs);
10408
10409         *cs++ = MI_DISPLAY_FLIP | MI_DISPLAY_FLIP_PLANE(intel_crtc->plane);
10410         *cs++ = fb->pitches[0] | intel_fb_modifier_to_tiling(fb->modifier);
10411         *cs++ = intel_crtc->flip_work->gtt_offset;
10412
10413         /* Contrary to the suggestions in the documentation,
10414          * "Enable Panel Fitter" does not seem to be required when page
10415          * flipping with a non-native mode, and worse causes a normal
10416          * modeset to fail.
10417          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
10418          */
10419         pf = 0;
10420         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
10421         *cs++ = pf | pipesrc;
10422
10423         return 0;
10424 }
10425
10426 static int intel_gen7_queue_flip(struct drm_device *dev,
10427                                  struct drm_crtc *crtc,
10428                                  struct drm_framebuffer *fb,
10429                                  struct drm_i915_gem_object *obj,
10430                                  struct drm_i915_gem_request *req,
10431                                  uint32_t flags)
10432 {
10433         struct drm_i915_private *dev_priv = to_i915(dev);
10434         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10435         u32 *cs, plane_bit = 0;
10436         int len, ret;
10437
10438         switch (intel_crtc->plane) {
10439         case PLANE_A:
10440                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
10441                 break;
10442         case PLANE_B:
10443                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
10444                 break;
10445         case PLANE_C:
10446                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
10447                 break;
10448         default:
10449                 WARN_ONCE(1, "unknown plane in flip command\n");
10450                 return -ENODEV;
10451         }
10452
10453         len = 4;
10454         if (req->engine->id == RCS) {
10455                 len += 6;
10456                 /*
10457                  * On Gen 8, SRM is now taking an extra dword to accommodate
10458                  * 48bits addresses, and we need a NOOP for the batch size to
10459                  * stay even.
10460                  */
10461                 if (IS_GEN8(dev_priv))
10462                         len += 2;
10463         }
10464
10465         /*
10466          * BSpec MI_DISPLAY_FLIP for IVB:
10467          * "The full packet must be contained within the same cache line."
10468          *
10469          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
10470          * cacheline, if we ever start emitting more commands before
10471          * the MI_DISPLAY_FLIP we may need to first emit everything else,
10472          * then do the cacheline alignment, and finally emit the
10473          * MI_DISPLAY_FLIP.
10474          */
10475         ret = intel_ring_cacheline_align(req);
10476         if (ret)
10477                 return ret;
10478
10479         cs = intel_ring_begin(req, len);
10480         if (IS_ERR(cs))
10481                 return PTR_ERR(cs);
10482
10483         /* Unmask the flip-done completion message. Note that the bspec says that
10484          * we should do this for both the BCS and RCS, and that we must not unmask
10485          * more than one flip event at any time (or ensure that one flip message
10486          * can be sent by waiting for flip-done prior to queueing new flips).
10487          * Experimentation says that BCS works despite DERRMR masking all
10488          * flip-done completion events and that unmasking all planes at once
10489          * for the RCS also doesn't appear to drop events. Setting the DERRMR
10490          * to zero does lead to lockups within MI_DISPLAY_FLIP.
10491          */
10492         if (req->engine->id == RCS) {
10493                 *cs++ = MI_LOAD_REGISTER_IMM(1);
10494                 *cs++ = i915_mmio_reg_offset(DERRMR);
10495                 *cs++ = ~(DERRMR_PIPEA_PRI_FLIP_DONE |
10496                           DERRMR_PIPEB_PRI_FLIP_DONE |
10497                           DERRMR_PIPEC_PRI_FLIP_DONE);
10498                 if (IS_GEN8(dev_priv))
10499                         *cs++ = MI_STORE_REGISTER_MEM_GEN8 |
10500                                 MI_SRM_LRM_GLOBAL_GTT;
10501                 else
10502                         *cs++ = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
10503                 *cs++ = i915_mmio_reg_offset(DERRMR);
10504                 *cs++ = i915_ggtt_offset(req->engine->scratch) + 256;
10505                 if (IS_GEN8(dev_priv)) {
10506                         *cs++ = 0;
10507                         *cs++ = MI_NOOP;
10508                 }
10509         }
10510
10511         *cs++ = MI_DISPLAY_FLIP_I915 | plane_bit;
10512         *cs++ = fb->pitches[0] | intel_fb_modifier_to_tiling(fb->modifier);
10513         *cs++ = intel_crtc->flip_work->gtt_offset;
10514         *cs++ = MI_NOOP;
10515
10516         return 0;
10517 }
10518
10519 static bool use_mmio_flip(struct intel_engine_cs *engine,
10520                           struct drm_i915_gem_object *obj)
10521 {
10522         /*
10523          * This is not being used for older platforms, because
10524          * non-availability of flip done interrupt forces us to use
10525          * CS flips. Older platforms derive flip done using some clever
10526          * tricks involving the flip_pending status bits and vblank irqs.
10527          * So using MMIO flips there would disrupt this mechanism.
10528          */
10529
10530         if (engine == NULL)
10531                 return true;
10532
10533         if (INTEL_GEN(engine->i915) < 5)
10534                 return false;
10535
10536         if (i915.use_mmio_flip < 0)
10537                 return false;
10538         else if (i915.use_mmio_flip > 0)
10539                 return true;
10540         else if (i915.enable_execlists)
10541                 return true;
10542
10543         return engine != i915_gem_object_last_write_engine(obj);
10544 }
10545
10546 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
10547                              unsigned int rotation,
10548                              struct intel_flip_work *work)
10549 {
10550         struct drm_device *dev = intel_crtc->base.dev;
10551         struct drm_i915_private *dev_priv = to_i915(dev);
10552         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
10553         const enum pipe pipe = intel_crtc->pipe;
10554         u32 ctl, stride = skl_plane_stride(fb, 0, rotation);
10555
10556         ctl = I915_READ(PLANE_CTL(pipe, 0));
10557         ctl &= ~PLANE_CTL_TILED_MASK;
10558         switch (fb->modifier) {
10559         case DRM_FORMAT_MOD_LINEAR:
10560                 break;
10561         case I915_FORMAT_MOD_X_TILED:
10562                 ctl |= PLANE_CTL_TILED_X;
10563                 break;
10564         case I915_FORMAT_MOD_Y_TILED:
10565                 ctl |= PLANE_CTL_TILED_Y;
10566                 break;
10567         case I915_FORMAT_MOD_Yf_TILED:
10568                 ctl |= PLANE_CTL_TILED_YF;
10569                 break;
10570         default:
10571                 MISSING_CASE(fb->modifier);
10572         }
10573
10574         /*
10575          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
10576          * PLANE_SURF updates, the update is then guaranteed to be atomic.
10577          */
10578         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
10579         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
10580
10581         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
10582         POSTING_READ(PLANE_SURF(pipe, 0));
10583 }
10584
10585 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
10586                              struct intel_flip_work *work)
10587 {
10588         struct drm_device *dev = intel_crtc->base.dev;
10589         struct drm_i915_private *dev_priv = to_i915(dev);
10590         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
10591         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
10592         u32 dspcntr;
10593
10594         dspcntr = I915_READ(reg);
10595
10596         if (fb->modifier == I915_FORMAT_MOD_X_TILED)
10597                 dspcntr |= DISPPLANE_TILED;
10598         else
10599                 dspcntr &= ~DISPPLANE_TILED;
10600
10601         I915_WRITE(reg, dspcntr);
10602
10603         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
10604         POSTING_READ(DSPSURF(intel_crtc->plane));
10605 }
10606
10607 static void intel_mmio_flip_work_func(struct work_struct *w)
10608 {
10609         struct intel_flip_work *work =
10610                 container_of(w, struct intel_flip_work, mmio_work);
10611         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10612         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10613         struct intel_framebuffer *intel_fb =
10614                 to_intel_framebuffer(crtc->base.primary->fb);
10615         struct drm_i915_gem_object *obj = intel_fb->obj;
10616
10617         WARN_ON(i915_gem_object_wait(obj, 0, MAX_SCHEDULE_TIMEOUT, NULL) < 0);
10618
10619         intel_pipe_update_start(crtc);
10620
10621         if (INTEL_GEN(dev_priv) >= 9)
10622                 skl_do_mmio_flip(crtc, work->rotation, work);
10623         else
10624                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
10625                 ilk_do_mmio_flip(crtc, work);
10626
10627         intel_pipe_update_end(crtc, work);
10628 }
10629
10630 static int intel_default_queue_flip(struct drm_device *dev,
10631                                     struct drm_crtc *crtc,
10632                                     struct drm_framebuffer *fb,
10633                                     struct drm_i915_gem_object *obj,
10634                                     struct drm_i915_gem_request *req,
10635                                     uint32_t flags)
10636 {
10637         return -ENODEV;
10638 }
10639
10640 static bool __pageflip_stall_check_cs(struct drm_i915_private *dev_priv,
10641                                       struct intel_crtc *intel_crtc,
10642                                       struct intel_flip_work *work)
10643 {
10644         u32 addr, vblank;
10645
10646         if (!atomic_read(&work->pending))
10647                 return false;
10648
10649         smp_rmb();
10650
10651         vblank = intel_crtc_get_vblank_counter(intel_crtc);
10652         if (work->flip_ready_vblank == 0) {
10653                 if (work->flip_queued_req &&
10654                     !i915_gem_request_completed(work->flip_queued_req))
10655                         return false;
10656
10657                 work->flip_ready_vblank = vblank;
10658         }
10659
10660         if (vblank - work->flip_ready_vblank < 3)
10661                 return false;
10662
10663         /* Potential stall - if we see that the flip has happened,
10664          * assume a missed interrupt. */
10665         if (INTEL_GEN(dev_priv) >= 4)
10666                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
10667         else
10668                 addr = I915_READ(DSPADDR(intel_crtc->plane));
10669
10670         /* There is a potential issue here with a false positive after a flip
10671          * to the same address. We could address this by checking for a
10672          * non-incrementing frame counter.
10673          */
10674         return addr == work->gtt_offset;
10675 }
10676
10677 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
10678 {
10679         struct drm_device *dev = &dev_priv->drm;
10680         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10681         struct intel_flip_work *work;
10682
10683         WARN_ON(!in_interrupt());
10684
10685         if (crtc == NULL)
10686                 return;
10687
10688         spin_lock(&dev->event_lock);
10689         work = crtc->flip_work;
10690
10691         if (work != NULL && !is_mmio_work(work) &&
10692             __pageflip_stall_check_cs(dev_priv, crtc, work)) {
10693                 WARN_ONCE(1,
10694                           "Kicking stuck page flip: queued at %d, now %d\n",
10695                         work->flip_queued_vblank, intel_crtc_get_vblank_counter(crtc));
10696                 page_flip_completed(crtc);
10697                 work = NULL;
10698         }
10699
10700         if (work != NULL && !is_mmio_work(work) &&
10701             intel_crtc_get_vblank_counter(crtc) - work->flip_queued_vblank > 1)
10702                 intel_queue_rps_boost_for_request(work->flip_queued_req);
10703         spin_unlock(&dev->event_lock);
10704 }
10705
10706 __maybe_unused
10707 static int intel_crtc_page_flip(struct drm_crtc *crtc,
10708                                 struct drm_framebuffer *fb,
10709                                 struct drm_pending_vblank_event *event,
10710                                 uint32_t page_flip_flags)
10711 {
10712         struct drm_device *dev = crtc->dev;
10713         struct drm_i915_private *dev_priv = to_i915(dev);
10714         struct drm_framebuffer *old_fb = crtc->primary->fb;
10715         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
10716         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10717         struct drm_plane *primary = crtc->primary;
10718         enum pipe pipe = intel_crtc->pipe;
10719         struct intel_flip_work *work;
10720         struct intel_engine_cs *engine;
10721         bool mmio_flip;
10722         struct drm_i915_gem_request *request;
10723         struct i915_vma *vma;
10724         int ret;
10725
10726         /*
10727          * drm_mode_page_flip_ioctl() should already catch this, but double
10728          * check to be safe.  In the future we may enable pageflipping from
10729          * a disabled primary plane.
10730          */
10731         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
10732                 return -EBUSY;
10733
10734         /* Can't change pixel format via MI display flips. */
10735         if (fb->format != crtc->primary->fb->format)
10736                 return -EINVAL;
10737
10738         /*
10739          * TILEOFF/LINOFF registers can't be changed via MI display flips.
10740          * Note that pitch changes could also affect these register.
10741          */
10742         if (INTEL_GEN(dev_priv) > 3 &&
10743             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
10744              fb->pitches[0] != crtc->primary->fb->pitches[0]))
10745                 return -EINVAL;
10746
10747         if (i915_terminally_wedged(&dev_priv->gpu_error))
10748                 goto out_hang;
10749
10750         work = kzalloc(sizeof(*work), GFP_KERNEL);
10751         if (work == NULL)
10752                 return -ENOMEM;
10753
10754         work->event = event;
10755         work->crtc = crtc;
10756         work->old_fb = old_fb;
10757         INIT_WORK(&work->unpin_work, intel_unpin_work_fn);
10758
10759         ret = drm_crtc_vblank_get(crtc);
10760         if (ret)
10761                 goto free_work;
10762
10763         /* We borrow the event spin lock for protecting flip_work */
10764         spin_lock_irq(&dev->event_lock);
10765         if (intel_crtc->flip_work) {
10766                 /* Before declaring the flip queue wedged, check if
10767                  * the hardware completed the operation behind our backs.
10768                  */
10769                 if (pageflip_finished(intel_crtc, intel_crtc->flip_work)) {
10770                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
10771                         page_flip_completed(intel_crtc);
10772                 } else {
10773                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
10774                         spin_unlock_irq(&dev->event_lock);
10775
10776                         drm_crtc_vblank_put(crtc);
10777                         kfree(work);
10778                         return -EBUSY;
10779                 }
10780         }
10781         intel_crtc->flip_work = work;
10782         spin_unlock_irq(&dev->event_lock);
10783
10784         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
10785                 flush_workqueue(dev_priv->wq);
10786
10787         /* Reference the objects for the scheduled work. */
10788         drm_framebuffer_reference(work->old_fb);
10789
10790         crtc->primary->fb = fb;
10791         update_state_fb(crtc->primary);
10792
10793         work->pending_flip_obj = i915_gem_object_get(obj);
10794
10795         ret = i915_mutex_lock_interruptible(dev);
10796         if (ret)
10797                 goto cleanup;
10798
10799         intel_crtc->reset_count = i915_reset_count(&dev_priv->gpu_error);
10800         if (i915_reset_backoff_or_wedged(&dev_priv->gpu_error)) {
10801                 ret = -EIO;
10802                 goto unlock;
10803         }
10804
10805         atomic_inc(&intel_crtc->unpin_work_count);
10806
10807         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10808                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
10809
10810         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
10811                 engine = dev_priv->engine[BCS];
10812                 if (fb->modifier != old_fb->modifier)
10813                         /* vlv: DISPLAY_FLIP fails to change tiling */
10814                         engine = NULL;
10815         } else if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv)) {
10816                 engine = dev_priv->engine[BCS];
10817         } else if (INTEL_GEN(dev_priv) >= 7) {
10818                 engine = i915_gem_object_last_write_engine(obj);
10819                 if (engine == NULL || engine->id != RCS)
10820                         engine = dev_priv->engine[BCS];
10821         } else {
10822                 engine = dev_priv->engine[RCS];
10823         }
10824
10825         mmio_flip = use_mmio_flip(engine, obj);
10826
10827         vma = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
10828         if (IS_ERR(vma)) {
10829                 ret = PTR_ERR(vma);
10830                 goto cleanup_pending;
10831         }
10832
10833         work->old_vma = to_intel_plane_state(primary->state)->vma;
10834         to_intel_plane_state(primary->state)->vma = vma;
10835
10836         work->gtt_offset = i915_ggtt_offset(vma) + intel_crtc->dspaddr_offset;
10837         work->rotation = crtc->primary->state->rotation;
10838
10839         /*
10840          * There's the potential that the next frame will not be compatible with
10841          * FBC, so we want to call pre_update() before the actual page flip.
10842          * The problem is that pre_update() caches some information about the fb
10843          * object, so we want to do this only after the object is pinned. Let's
10844          * be on the safe side and do this immediately before scheduling the
10845          * flip.
10846          */
10847         intel_fbc_pre_update(intel_crtc, intel_crtc->config,
10848                              to_intel_plane_state(primary->state));
10849
10850         if (mmio_flip) {
10851                 INIT_WORK(&work->mmio_work, intel_mmio_flip_work_func);
10852                 queue_work(system_unbound_wq, &work->mmio_work);
10853         } else {
10854                 request = i915_gem_request_alloc(engine,
10855                                                  dev_priv->kernel_context);
10856                 if (IS_ERR(request)) {
10857                         ret = PTR_ERR(request);
10858                         goto cleanup_unpin;
10859                 }
10860
10861                 ret = i915_gem_request_await_object(request, obj, false);
10862                 if (ret)
10863                         goto cleanup_request;
10864
10865                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
10866                                                    page_flip_flags);
10867                 if (ret)
10868                         goto cleanup_request;
10869
10870                 intel_mark_page_flip_active(intel_crtc, work);
10871
10872                 work->flip_queued_req = i915_gem_request_get(request);
10873                 i915_add_request(request);
10874         }
10875
10876         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
10877         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
10878                           to_intel_plane(primary)->frontbuffer_bit);
10879         mutex_unlock(&dev->struct_mutex);
10880
10881         intel_frontbuffer_flip_prepare(to_i915(dev),
10882                                        to_intel_plane(primary)->frontbuffer_bit);
10883
10884         trace_i915_flip_request(intel_crtc->plane, obj);
10885
10886         return 0;
10887
10888 cleanup_request:
10889         i915_add_request(request);
10890 cleanup_unpin:
10891         to_intel_plane_state(primary->state)->vma = work->old_vma;
10892         intel_unpin_fb_vma(vma);
10893 cleanup_pending:
10894         atomic_dec(&intel_crtc->unpin_work_count);
10895 unlock:
10896         mutex_unlock(&dev->struct_mutex);
10897 cleanup:
10898         crtc->primary->fb = old_fb;
10899         update_state_fb(crtc->primary);
10900
10901         i915_gem_object_put(obj);
10902         drm_framebuffer_unreference(work->old_fb);
10903
10904         spin_lock_irq(&dev->event_lock);
10905         intel_crtc->flip_work = NULL;
10906         spin_unlock_irq(&dev->event_lock);
10907
10908         drm_crtc_vblank_put(crtc);
10909 free_work:
10910         kfree(work);
10911
10912         if (ret == -EIO) {
10913                 struct drm_atomic_state *state;
10914                 struct drm_plane_state *plane_state;
10915
10916 out_hang:
10917                 state = drm_atomic_state_alloc(dev);
10918                 if (!state)
10919                         return -ENOMEM;
10920                 state->acquire_ctx = dev->mode_config.acquire_ctx;
10921
10922 retry:
10923                 plane_state = drm_atomic_get_plane_state(state, primary);
10924                 ret = PTR_ERR_OR_ZERO(plane_state);
10925                 if (!ret) {
10926                         drm_atomic_set_fb_for_plane(plane_state, fb);
10927
10928                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
10929                         if (!ret)
10930                                 ret = drm_atomic_commit(state);
10931                 }
10932
10933                 if (ret == -EDEADLK) {
10934                         drm_modeset_backoff(state->acquire_ctx);
10935                         drm_atomic_state_clear(state);
10936                         goto retry;
10937                 }
10938
10939                 drm_atomic_state_put(state);
10940
10941                 if (ret == 0 && event) {
10942                         spin_lock_irq(&dev->event_lock);
10943                         drm_crtc_send_vblank_event(crtc, event);
10944                         spin_unlock_irq(&dev->event_lock);
10945                 }
10946         }
10947         return ret;
10948 }
10949
10950
10951 /**
10952  * intel_wm_need_update - Check whether watermarks need updating
10953  * @plane: drm plane
10954  * @state: new plane state
10955  *
10956  * Check current plane state versus the new one to determine whether
10957  * watermarks need to be recalculated.
10958  *
10959  * Returns true or false.
10960  */
10961 static bool intel_wm_need_update(struct drm_plane *plane,
10962                                  struct drm_plane_state *state)
10963 {
10964         struct intel_plane_state *new = to_intel_plane_state(state);
10965         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10966
10967         /* Update watermarks on tiling or size changes. */
10968         if (new->base.visible != cur->base.visible)
10969                 return true;
10970
10971         if (!cur->base.fb || !new->base.fb)
10972                 return false;
10973
10974         if (cur->base.fb->modifier != new->base.fb->modifier ||
10975             cur->base.rotation != new->base.rotation ||
10976             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10977             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10978             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10979             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10980                 return true;
10981
10982         return false;
10983 }
10984
10985 static bool needs_scaling(struct intel_plane_state *state)
10986 {
10987         int src_w = drm_rect_width(&state->base.src) >> 16;
10988         int src_h = drm_rect_height(&state->base.src) >> 16;
10989         int dst_w = drm_rect_width(&state->base.dst);
10990         int dst_h = drm_rect_height(&state->base.dst);
10991
10992         return (src_w != dst_w || src_h != dst_h);
10993 }
10994
10995 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
10996                                     struct drm_plane_state *plane_state)
10997 {
10998         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10999         struct drm_crtc *crtc = crtc_state->crtc;
11000         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11001         struct intel_plane *plane = to_intel_plane(plane_state->plane);
11002         struct drm_device *dev = crtc->dev;
11003         struct drm_i915_private *dev_priv = to_i915(dev);
11004         struct intel_plane_state *old_plane_state =
11005                 to_intel_plane_state(plane->base.state);
11006         bool mode_changed = needs_modeset(crtc_state);
11007         bool was_crtc_enabled = crtc->state->active;
11008         bool is_crtc_enabled = crtc_state->active;
11009         bool turn_off, turn_on, visible, was_visible;
11010         struct drm_framebuffer *fb = plane_state->fb;
11011         int ret;
11012
11013         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
11014                 ret = skl_update_scaler_plane(
11015                         to_intel_crtc_state(crtc_state),
11016                         to_intel_plane_state(plane_state));
11017                 if (ret)
11018                         return ret;
11019         }
11020
11021         was_visible = old_plane_state->base.visible;
11022         visible = plane_state->visible;
11023
11024         if (!was_crtc_enabled && WARN_ON(was_visible))
11025                 was_visible = false;
11026
11027         /*
11028          * Visibility is calculated as if the crtc was on, but
11029          * after scaler setup everything depends on it being off
11030          * when the crtc isn't active.
11031          *
11032          * FIXME this is wrong for watermarks. Watermarks should also
11033          * be computed as if the pipe would be active. Perhaps move
11034          * per-plane wm computation to the .check_plane() hook, and
11035          * only combine the results from all planes in the current place?
11036          */
11037         if (!is_crtc_enabled) {
11038                 plane_state->visible = visible = false;
11039                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
11040         }
11041
11042         if (!was_visible && !visible)
11043                 return 0;
11044
11045         if (fb != old_plane_state->base.fb)
11046                 pipe_config->fb_changed = true;
11047
11048         turn_off = was_visible && (!visible || mode_changed);
11049         turn_on = visible && (!was_visible || mode_changed);
11050
11051         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
11052                          intel_crtc->base.base.id, intel_crtc->base.name,
11053                          plane->base.base.id, plane->base.name,
11054                          fb ? fb->base.id : -1);
11055
11056         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
11057                          plane->base.base.id, plane->base.name,
11058                          was_visible, visible,
11059                          turn_off, turn_on, mode_changed);
11060
11061         if (turn_on) {
11062                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11063                         pipe_config->update_wm_pre = true;
11064
11065                 /* must disable cxsr around plane enable/disable */
11066                 if (plane->id != PLANE_CURSOR)
11067                         pipe_config->disable_cxsr = true;
11068         } else if (turn_off) {
11069                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
11070                         pipe_config->update_wm_post = true;
11071
11072                 /* must disable cxsr around plane enable/disable */
11073                 if (plane->id != PLANE_CURSOR)
11074                         pipe_config->disable_cxsr = true;
11075         } else if (intel_wm_need_update(&plane->base, plane_state)) {
11076                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
11077                         /* FIXME bollocks */
11078                         pipe_config->update_wm_pre = true;
11079                         pipe_config->update_wm_post = true;
11080                 }
11081         }
11082
11083         if (visible || was_visible)
11084                 pipe_config->fb_bits |= plane->frontbuffer_bit;
11085
11086         /*
11087          * WaCxSRDisabledForSpriteScaling:ivb
11088          *
11089          * cstate->update_wm was already set above, so this flag will
11090          * take effect when we commit and program watermarks.
11091          */
11092         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
11093             needs_scaling(to_intel_plane_state(plane_state)) &&
11094             !needs_scaling(old_plane_state))
11095                 pipe_config->disable_lp_wm = true;
11096
11097         return 0;
11098 }
11099
11100 static bool encoders_cloneable(const struct intel_encoder *a,
11101                                const struct intel_encoder *b)
11102 {
11103         /* masks could be asymmetric, so check both ways */
11104         return a == b || (a->cloneable & (1 << b->type) &&
11105                           b->cloneable & (1 << a->type));
11106 }
11107
11108 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11109                                          struct intel_crtc *crtc,
11110                                          struct intel_encoder *encoder)
11111 {
11112         struct intel_encoder *source_encoder;
11113         struct drm_connector *connector;
11114         struct drm_connector_state *connector_state;
11115         int i;
11116
11117         for_each_new_connector_in_state(state, connector, connector_state, i) {
11118                 if (connector_state->crtc != &crtc->base)
11119                         continue;
11120
11121                 source_encoder =
11122                         to_intel_encoder(connector_state->best_encoder);
11123                 if (!encoders_cloneable(encoder, source_encoder))
11124                         return false;
11125         }
11126
11127         return true;
11128 }
11129
11130 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11131                                    struct drm_crtc_state *crtc_state)
11132 {
11133         struct drm_device *dev = crtc->dev;
11134         struct drm_i915_private *dev_priv = to_i915(dev);
11135         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11136         struct intel_crtc_state *pipe_config =
11137                 to_intel_crtc_state(crtc_state);
11138         struct drm_atomic_state *state = crtc_state->state;
11139         int ret;
11140         bool mode_changed = needs_modeset(crtc_state);
11141
11142         if (mode_changed && !crtc_state->active)
11143                 pipe_config->update_wm_post = true;
11144
11145         if (mode_changed && crtc_state->enable &&
11146             dev_priv->display.crtc_compute_clock &&
11147             !WARN_ON(pipe_config->shared_dpll)) {
11148                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11149                                                            pipe_config);
11150                 if (ret)
11151                         return ret;
11152         }
11153
11154         if (crtc_state->color_mgmt_changed) {
11155                 ret = intel_color_check(crtc, crtc_state);
11156                 if (ret)
11157                         return ret;
11158
11159                 /*
11160                  * Changing color management on Intel hardware is
11161                  * handled as part of planes update.
11162                  */
11163                 crtc_state->planes_changed = true;
11164         }
11165
11166         ret = 0;
11167         if (dev_priv->display.compute_pipe_wm) {
11168                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11169                 if (ret) {
11170                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11171                         return ret;
11172                 }
11173         }
11174
11175         if (dev_priv->display.compute_intermediate_wm &&
11176             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11177                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11178                         return 0;
11179
11180                 /*
11181                  * Calculate 'intermediate' watermarks that satisfy both the
11182                  * old state and the new state.  We can program these
11183                  * immediately.
11184                  */
11185                 ret = dev_priv->display.compute_intermediate_wm(dev,
11186                                                                 intel_crtc,
11187                                                                 pipe_config);
11188                 if (ret) {
11189                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11190                         return ret;
11191                 }
11192         } else if (dev_priv->display.compute_intermediate_wm) {
11193                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
11194                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
11195         }
11196
11197         if (INTEL_GEN(dev_priv) >= 9) {
11198                 if (mode_changed)
11199                         ret = skl_update_scaler_crtc(pipe_config);
11200
11201                 if (!ret)
11202                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11203                                                             pipe_config);
11204                 if (!ret)
11205                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11206                                                          pipe_config);
11207         }
11208
11209         return ret;
11210 }
11211
11212 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11213         .atomic_begin = intel_begin_crtc_commit,
11214         .atomic_flush = intel_finish_crtc_commit,
11215         .atomic_check = intel_crtc_atomic_check,
11216 };
11217
11218 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11219 {
11220         struct intel_connector *connector;
11221         struct drm_connector_list_iter conn_iter;
11222
11223         drm_connector_list_iter_begin(dev, &conn_iter);
11224         for_each_intel_connector_iter(connector, &conn_iter) {
11225                 if (connector->base.state->crtc)
11226                         drm_connector_unreference(&connector->base);
11227
11228                 if (connector->base.encoder) {
11229                         connector->base.state->best_encoder =
11230                                 connector->base.encoder;
11231                         connector->base.state->crtc =
11232                                 connector->base.encoder->crtc;
11233
11234                         drm_connector_reference(&connector->base);
11235                 } else {
11236                         connector->base.state->best_encoder = NULL;
11237                         connector->base.state->crtc = NULL;
11238                 }
11239         }
11240         drm_connector_list_iter_end(&conn_iter);
11241 }
11242
11243 static void
11244 connected_sink_compute_bpp(struct intel_connector *connector,
11245                            struct intel_crtc_state *pipe_config)
11246 {
11247         const struct drm_display_info *info = &connector->base.display_info;
11248         int bpp = pipe_config->pipe_bpp;
11249
11250         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
11251                       connector->base.base.id,
11252                       connector->base.name);
11253
11254         /* Don't use an invalid EDID bpc value */
11255         if (info->bpc != 0 && info->bpc * 3 < bpp) {
11256                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
11257                               bpp, info->bpc * 3);
11258                 pipe_config->pipe_bpp = info->bpc * 3;
11259         }
11260
11261         /* Clamp bpp to 8 on screens without EDID 1.4 */
11262         if (info->bpc == 0 && bpp > 24) {
11263                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
11264                               bpp);
11265                 pipe_config->pipe_bpp = 24;
11266         }
11267 }
11268
11269 static int
11270 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11271                           struct intel_crtc_state *pipe_config)
11272 {
11273         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11274         struct drm_atomic_state *state;
11275         struct drm_connector *connector;
11276         struct drm_connector_state *connector_state;
11277         int bpp, i;
11278
11279         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11280             IS_CHERRYVIEW(dev_priv)))
11281                 bpp = 10*3;
11282         else if (INTEL_GEN(dev_priv) >= 5)
11283                 bpp = 12*3;
11284         else
11285                 bpp = 8*3;
11286
11287
11288         pipe_config->pipe_bpp = bpp;
11289
11290         state = pipe_config->base.state;
11291
11292         /* Clamp display bpp to EDID value */
11293         for_each_new_connector_in_state(state, connector, connector_state, i) {
11294                 if (connector_state->crtc != &crtc->base)
11295                         continue;
11296
11297                 connected_sink_compute_bpp(to_intel_connector(connector),
11298                                            pipe_config);
11299         }
11300
11301         return bpp;
11302 }
11303
11304 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11305 {
11306         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11307                         "type: 0x%x flags: 0x%x\n",
11308                 mode->crtc_clock,
11309                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11310                 mode->crtc_hsync_end, mode->crtc_htotal,
11311                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11312                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11313 }
11314
11315 static inline void
11316 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11317                       unsigned int lane_count, struct intel_link_m_n *m_n)
11318 {
11319         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11320                       id, lane_count,
11321                       m_n->gmch_m, m_n->gmch_n,
11322                       m_n->link_m, m_n->link_n, m_n->tu);
11323 }
11324
11325 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11326                                    struct intel_crtc_state *pipe_config,
11327                                    const char *context)
11328 {
11329         struct drm_device *dev = crtc->base.dev;
11330         struct drm_i915_private *dev_priv = to_i915(dev);
11331         struct drm_plane *plane;
11332         struct intel_plane *intel_plane;
11333         struct intel_plane_state *state;
11334         struct drm_framebuffer *fb;
11335
11336         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11337                       crtc->base.base.id, crtc->base.name, context);
11338
11339         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11340                       transcoder_name(pipe_config->cpu_transcoder),
11341                       pipe_config->pipe_bpp, pipe_config->dither);
11342
11343         if (pipe_config->has_pch_encoder)
11344                 intel_dump_m_n_config(pipe_config, "fdi",
11345                                       pipe_config->fdi_lanes,
11346                                       &pipe_config->fdi_m_n);
11347
11348         if (intel_crtc_has_dp_encoder(pipe_config)) {
11349                 intel_dump_m_n_config(pipe_config, "dp m_n",
11350                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11351                 if (pipe_config->has_drrs)
11352                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11353                                               pipe_config->lane_count,
11354                                               &pipe_config->dp_m2_n2);
11355         }
11356
11357         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11358                       pipe_config->has_audio, pipe_config->has_infoframe);
11359
11360         DRM_DEBUG_KMS("requested mode:\n");
11361         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11362         DRM_DEBUG_KMS("adjusted mode:\n");
11363         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11364         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11365         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11366                       pipe_config->port_clock,
11367                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11368                       pipe_config->pixel_rate);
11369
11370         if (INTEL_GEN(dev_priv) >= 9)
11371                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11372                               crtc->num_scalers,
11373                               pipe_config->scaler_state.scaler_users,
11374                               pipe_config->scaler_state.scaler_id);
11375
11376         if (HAS_GMCH_DISPLAY(dev_priv))
11377                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11378                               pipe_config->gmch_pfit.control,
11379                               pipe_config->gmch_pfit.pgm_ratios,
11380                               pipe_config->gmch_pfit.lvds_border_bits);
11381         else
11382                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11383                               pipe_config->pch_pfit.pos,
11384                               pipe_config->pch_pfit.size,
11385                               enableddisabled(pipe_config->pch_pfit.enabled));
11386
11387         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11388                       pipe_config->ips_enabled, pipe_config->double_wide);
11389
11390         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11391
11392         DRM_DEBUG_KMS("planes on this crtc\n");
11393         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11394                 struct drm_format_name_buf format_name;
11395                 intel_plane = to_intel_plane(plane);
11396                 if (intel_plane->pipe != crtc->pipe)
11397                         continue;
11398
11399                 state = to_intel_plane_state(plane->state);
11400                 fb = state->base.fb;
11401                 if (!fb) {
11402                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11403                                       plane->base.id, plane->name, state->scaler_id);
11404                         continue;
11405                 }
11406
11407                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11408                               plane->base.id, plane->name,
11409                               fb->base.id, fb->width, fb->height,
11410                               drm_get_format_name(fb->format->format, &format_name));
11411                 if (INTEL_GEN(dev_priv) >= 9)
11412                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11413                                       state->scaler_id,
11414                                       state->base.src.x1 >> 16,
11415                                       state->base.src.y1 >> 16,
11416                                       drm_rect_width(&state->base.src) >> 16,
11417                                       drm_rect_height(&state->base.src) >> 16,
11418                                       state->base.dst.x1, state->base.dst.y1,
11419                                       drm_rect_width(&state->base.dst),
11420                                       drm_rect_height(&state->base.dst));
11421         }
11422 }
11423
11424 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11425 {
11426         struct drm_device *dev = state->dev;
11427         struct drm_connector *connector;
11428         struct drm_connector_list_iter conn_iter;
11429         unsigned int used_ports = 0;
11430         unsigned int used_mst_ports = 0;
11431
11432         /*
11433          * Walk the connector list instead of the encoder
11434          * list to detect the problem on ddi platforms
11435          * where there's just one encoder per digital port.
11436          */
11437         drm_connector_list_iter_begin(dev, &conn_iter);
11438         drm_for_each_connector_iter(connector, &conn_iter) {
11439                 struct drm_connector_state *connector_state;
11440                 struct intel_encoder *encoder;
11441
11442                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
11443                 if (!connector_state)
11444                         connector_state = connector->state;
11445
11446                 if (!connector_state->best_encoder)
11447                         continue;
11448
11449                 encoder = to_intel_encoder(connector_state->best_encoder);
11450
11451                 WARN_ON(!connector_state->crtc);
11452
11453                 switch (encoder->type) {
11454                         unsigned int port_mask;
11455                 case INTEL_OUTPUT_UNKNOWN:
11456                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11457                                 break;
11458                 case INTEL_OUTPUT_DP:
11459                 case INTEL_OUTPUT_HDMI:
11460                 case INTEL_OUTPUT_EDP:
11461                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
11462
11463                         /* the same port mustn't appear more than once */
11464                         if (used_ports & port_mask)
11465                                 return false;
11466
11467                         used_ports |= port_mask;
11468                         break;
11469                 case INTEL_OUTPUT_DP_MST:
11470                         used_mst_ports |=
11471                                 1 << enc_to_mst(&encoder->base)->primary->port;
11472                         break;
11473                 default:
11474                         break;
11475                 }
11476         }
11477         drm_connector_list_iter_end(&conn_iter);
11478
11479         /* can't mix MST and SST/HDMI on the same port */
11480         if (used_ports & used_mst_ports)
11481                 return false;
11482
11483         return true;
11484 }
11485
11486 static void
11487 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11488 {
11489         struct drm_i915_private *dev_priv =
11490                 to_i915(crtc_state->base.crtc->dev);
11491         struct intel_crtc_scaler_state scaler_state;
11492         struct intel_dpll_hw_state dpll_hw_state;
11493         struct intel_shared_dpll *shared_dpll;
11494         struct intel_crtc_wm_state wm_state;
11495         bool force_thru;
11496
11497         /* FIXME: before the switch to atomic started, a new pipe_config was
11498          * kzalloc'd. Code that depends on any field being zero should be
11499          * fixed, so that the crtc_state can be safely duplicated. For now,
11500          * only fields that are know to not cause problems are preserved. */
11501
11502         scaler_state = crtc_state->scaler_state;
11503         shared_dpll = crtc_state->shared_dpll;
11504         dpll_hw_state = crtc_state->dpll_hw_state;
11505         force_thru = crtc_state->pch_pfit.force_thru;
11506         if (IS_G4X(dev_priv) ||
11507             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11508                 wm_state = crtc_state->wm;
11509
11510         /* Keep base drm_crtc_state intact, only clear our extended struct */
11511         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11512         memset(&crtc_state->base + 1, 0,
11513                sizeof(*crtc_state) - sizeof(crtc_state->base));
11514
11515         crtc_state->scaler_state = scaler_state;
11516         crtc_state->shared_dpll = shared_dpll;
11517         crtc_state->dpll_hw_state = dpll_hw_state;
11518         crtc_state->pch_pfit.force_thru = force_thru;
11519         if (IS_G4X(dev_priv) ||
11520             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11521                 crtc_state->wm = wm_state;
11522 }
11523
11524 static int
11525 intel_modeset_pipe_config(struct drm_crtc *crtc,
11526                           struct intel_crtc_state *pipe_config)
11527 {
11528         struct drm_atomic_state *state = pipe_config->base.state;
11529         struct intel_encoder *encoder;
11530         struct drm_connector *connector;
11531         struct drm_connector_state *connector_state;
11532         int base_bpp, ret = -EINVAL;
11533         int i;
11534         bool retry = true;
11535
11536         clear_intel_crtc_state(pipe_config);
11537
11538         pipe_config->cpu_transcoder =
11539                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11540
11541         /*
11542          * Sanitize sync polarity flags based on requested ones. If neither
11543          * positive or negative polarity is requested, treat this as meaning
11544          * negative polarity.
11545          */
11546         if (!(pipe_config->base.adjusted_mode.flags &
11547               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11548                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11549
11550         if (!(pipe_config->base.adjusted_mode.flags &
11551               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11552                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11553
11554         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11555                                              pipe_config);
11556         if (base_bpp < 0)
11557                 goto fail;
11558
11559         /*
11560          * Determine the real pipe dimensions. Note that stereo modes can
11561          * increase the actual pipe size due to the frame doubling and
11562          * insertion of additional space for blanks between the frame. This
11563          * is stored in the crtc timings. We use the requested mode to do this
11564          * computation to clearly distinguish it from the adjusted mode, which
11565          * can be changed by the connectors in the below retry loop.
11566          */
11567         drm_mode_get_hv_timing(&pipe_config->base.mode,
11568                                &pipe_config->pipe_src_w,
11569                                &pipe_config->pipe_src_h);
11570
11571         for_each_new_connector_in_state(state, connector, connector_state, i) {
11572                 if (connector_state->crtc != crtc)
11573                         continue;
11574
11575                 encoder = to_intel_encoder(connector_state->best_encoder);
11576
11577                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11578                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11579                         goto fail;
11580                 }
11581
11582                 /*
11583                  * Determine output_types before calling the .compute_config()
11584                  * hooks so that the hooks can use this information safely.
11585                  */
11586                 pipe_config->output_types |= 1 << encoder->type;
11587         }
11588
11589 encoder_retry:
11590         /* Ensure the port clock defaults are reset when retrying. */
11591         pipe_config->port_clock = 0;
11592         pipe_config->pixel_multiplier = 1;
11593
11594         /* Fill in default crtc timings, allow encoders to overwrite them. */
11595         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11596                               CRTC_STEREO_DOUBLE);
11597
11598         /* Pass our mode to the connectors and the CRTC to give them a chance to
11599          * adjust it according to limitations or connector properties, and also
11600          * a chance to reject the mode entirely.
11601          */
11602         for_each_new_connector_in_state(state, connector, connector_state, i) {
11603                 if (connector_state->crtc != crtc)
11604                         continue;
11605
11606                 encoder = to_intel_encoder(connector_state->best_encoder);
11607
11608                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11609                         DRM_DEBUG_KMS("Encoder config failure\n");
11610                         goto fail;
11611                 }
11612         }
11613
11614         /* Set default port clock if not overwritten by the encoder. Needs to be
11615          * done afterwards in case the encoder adjusts the mode. */
11616         if (!pipe_config->port_clock)
11617                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11618                         * pipe_config->pixel_multiplier;
11619
11620         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11621         if (ret < 0) {
11622                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11623                 goto fail;
11624         }
11625
11626         if (ret == RETRY) {
11627                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11628                         ret = -EINVAL;
11629                         goto fail;
11630                 }
11631
11632                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11633                 retry = false;
11634                 goto encoder_retry;
11635         }
11636
11637         /* Dithering seems to not pass-through bits correctly when it should, so
11638          * only enable it on 6bpc panels and when its not a compliance
11639          * test requesting 6bpc video pattern.
11640          */
11641         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11642                 !pipe_config->dither_force_disable;
11643         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11644                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11645
11646 fail:
11647         return ret;
11648 }
11649
11650 static void
11651 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
11652 {
11653         struct drm_crtc *crtc;
11654         struct drm_crtc_state *new_crtc_state;
11655         int i;
11656
11657         /* Double check state. */
11658         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11659                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
11660
11661                 /*
11662                  * Update legacy state to satisfy fbc code. This can
11663                  * be removed when fbc uses the atomic state.
11664                  */
11665                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
11666                         struct drm_plane_state *plane_state = crtc->primary->state;
11667
11668                         crtc->primary->fb = plane_state->fb;
11669                         crtc->x = plane_state->src_x >> 16;
11670                         crtc->y = plane_state->src_y >> 16;
11671                 }
11672         }
11673 }
11674
11675 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11676 {
11677         int diff;
11678
11679         if (clock1 == clock2)
11680                 return true;
11681
11682         if (!clock1 || !clock2)
11683                 return false;
11684
11685         diff = abs(clock1 - clock2);
11686
11687         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11688                 return true;
11689
11690         return false;
11691 }
11692
11693 static bool
11694 intel_compare_m_n(unsigned int m, unsigned int n,
11695                   unsigned int m2, unsigned int n2,
11696                   bool exact)
11697 {
11698         if (m == m2 && n == n2)
11699                 return true;
11700
11701         if (exact || !m || !n || !m2 || !n2)
11702                 return false;
11703
11704         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11705
11706         if (n > n2) {
11707                 while (n > n2) {
11708                         m2 <<= 1;
11709                         n2 <<= 1;
11710                 }
11711         } else if (n < n2) {
11712                 while (n < n2) {
11713                         m <<= 1;
11714                         n <<= 1;
11715                 }
11716         }
11717
11718         if (n != n2)
11719                 return false;
11720
11721         return intel_fuzzy_clock_check(m, m2);
11722 }
11723
11724 static bool
11725 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11726                        struct intel_link_m_n *m2_n2,
11727                        bool adjust)
11728 {
11729         if (m_n->tu == m2_n2->tu &&
11730             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11731                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11732             intel_compare_m_n(m_n->link_m, m_n->link_n,
11733                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11734                 if (adjust)
11735                         *m2_n2 = *m_n;
11736
11737                 return true;
11738         }
11739
11740         return false;
11741 }
11742
11743 static void __printf(3, 4)
11744 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11745 {
11746         char *level;
11747         unsigned int category;
11748         struct va_format vaf;
11749         va_list args;
11750
11751         if (adjust) {
11752                 level = KERN_DEBUG;
11753                 category = DRM_UT_KMS;
11754         } else {
11755                 level = KERN_ERR;
11756                 category = DRM_UT_NONE;
11757         }
11758
11759         va_start(args, format);
11760         vaf.fmt = format;
11761         vaf.va = &args;
11762
11763         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
11764
11765         va_end(args);
11766 }
11767
11768 static bool
11769 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11770                           struct intel_crtc_state *current_config,
11771                           struct intel_crtc_state *pipe_config,
11772                           bool adjust)
11773 {
11774         bool ret = true;
11775
11776 #define PIPE_CONF_CHECK_X(name) \
11777         if (current_config->name != pipe_config->name) { \
11778                 pipe_config_err(adjust, __stringify(name), \
11779                           "(expected 0x%08x, found 0x%08x)\n", \
11780                           current_config->name, \
11781                           pipe_config->name); \
11782                 ret = false; \
11783         }
11784
11785 #define PIPE_CONF_CHECK_I(name) \
11786         if (current_config->name != pipe_config->name) { \
11787                 pipe_config_err(adjust, __stringify(name), \
11788                           "(expected %i, found %i)\n", \
11789                           current_config->name, \
11790                           pipe_config->name); \
11791                 ret = false; \
11792         }
11793
11794 #define PIPE_CONF_CHECK_P(name) \
11795         if (current_config->name != pipe_config->name) { \
11796                 pipe_config_err(adjust, __stringify(name), \
11797                           "(expected %p, found %p)\n", \
11798                           current_config->name, \
11799                           pipe_config->name); \
11800                 ret = false; \
11801         }
11802
11803 #define PIPE_CONF_CHECK_M_N(name) \
11804         if (!intel_compare_link_m_n(&current_config->name, \
11805                                     &pipe_config->name,\
11806                                     adjust)) { \
11807                 pipe_config_err(adjust, __stringify(name), \
11808                           "(expected tu %i gmch %i/%i link %i/%i, " \
11809                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11810                           current_config->name.tu, \
11811                           current_config->name.gmch_m, \
11812                           current_config->name.gmch_n, \
11813                           current_config->name.link_m, \
11814                           current_config->name.link_n, \
11815                           pipe_config->name.tu, \
11816                           pipe_config->name.gmch_m, \
11817                           pipe_config->name.gmch_n, \
11818                           pipe_config->name.link_m, \
11819                           pipe_config->name.link_n); \
11820                 ret = false; \
11821         }
11822
11823 /* This is required for BDW+ where there is only one set of registers for
11824  * switching between high and low RR.
11825  * This macro can be used whenever a comparison has to be made between one
11826  * hw state and multiple sw state variables.
11827  */
11828 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11829         if (!intel_compare_link_m_n(&current_config->name, \
11830                                     &pipe_config->name, adjust) && \
11831             !intel_compare_link_m_n(&current_config->alt_name, \
11832                                     &pipe_config->name, adjust)) { \
11833                 pipe_config_err(adjust, __stringify(name), \
11834                           "(expected tu %i gmch %i/%i link %i/%i, " \
11835                           "or tu %i gmch %i/%i link %i/%i, " \
11836                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11837                           current_config->name.tu, \
11838                           current_config->name.gmch_m, \
11839                           current_config->name.gmch_n, \
11840                           current_config->name.link_m, \
11841                           current_config->name.link_n, \
11842                           current_config->alt_name.tu, \
11843                           current_config->alt_name.gmch_m, \
11844                           current_config->alt_name.gmch_n, \
11845                           current_config->alt_name.link_m, \
11846                           current_config->alt_name.link_n, \
11847                           pipe_config->name.tu, \
11848                           pipe_config->name.gmch_m, \
11849                           pipe_config->name.gmch_n, \
11850                           pipe_config->name.link_m, \
11851                           pipe_config->name.link_n); \
11852                 ret = false; \
11853         }
11854
11855 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11856         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11857                 pipe_config_err(adjust, __stringify(name), \
11858                           "(%x) (expected %i, found %i)\n", \
11859                           (mask), \
11860                           current_config->name & (mask), \
11861                           pipe_config->name & (mask)); \
11862                 ret = false; \
11863         }
11864
11865 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11866         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11867                 pipe_config_err(adjust, __stringify(name), \
11868                           "(expected %i, found %i)\n", \
11869                           current_config->name, \
11870                           pipe_config->name); \
11871                 ret = false; \
11872         }
11873
11874 #define PIPE_CONF_QUIRK(quirk)  \
11875         ((current_config->quirks | pipe_config->quirks) & (quirk))
11876
11877         PIPE_CONF_CHECK_I(cpu_transcoder);
11878
11879         PIPE_CONF_CHECK_I(has_pch_encoder);
11880         PIPE_CONF_CHECK_I(fdi_lanes);
11881         PIPE_CONF_CHECK_M_N(fdi_m_n);
11882
11883         PIPE_CONF_CHECK_I(lane_count);
11884         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11885
11886         if (INTEL_GEN(dev_priv) < 8) {
11887                 PIPE_CONF_CHECK_M_N(dp_m_n);
11888
11889                 if (current_config->has_drrs)
11890                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11891         } else
11892                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11893
11894         PIPE_CONF_CHECK_X(output_types);
11895
11896         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11897         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11898         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11899         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11900         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11901         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11902
11903         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11904         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11905         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11906         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11907         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11908         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11909
11910         PIPE_CONF_CHECK_I(pixel_multiplier);
11911         PIPE_CONF_CHECK_I(has_hdmi_sink);
11912         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11913             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11914                 PIPE_CONF_CHECK_I(limited_color_range);
11915
11916         PIPE_CONF_CHECK_I(hdmi_scrambling);
11917         PIPE_CONF_CHECK_I(hdmi_high_tmds_clock_ratio);
11918         PIPE_CONF_CHECK_I(has_infoframe);
11919
11920         PIPE_CONF_CHECK_I(has_audio);
11921
11922         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11923                               DRM_MODE_FLAG_INTERLACE);
11924
11925         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11926                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11927                                       DRM_MODE_FLAG_PHSYNC);
11928                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11929                                       DRM_MODE_FLAG_NHSYNC);
11930                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11931                                       DRM_MODE_FLAG_PVSYNC);
11932                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11933                                       DRM_MODE_FLAG_NVSYNC);
11934         }
11935
11936         PIPE_CONF_CHECK_X(gmch_pfit.control);
11937         /* pfit ratios are autocomputed by the hw on gen4+ */
11938         if (INTEL_GEN(dev_priv) < 4)
11939                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11940         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11941
11942         if (!adjust) {
11943                 PIPE_CONF_CHECK_I(pipe_src_w);
11944                 PIPE_CONF_CHECK_I(pipe_src_h);
11945
11946                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
11947                 if (current_config->pch_pfit.enabled) {
11948                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11949                         PIPE_CONF_CHECK_X(pch_pfit.size);
11950                 }
11951
11952                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11953                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11954         }
11955
11956         /* BDW+ don't expose a synchronous way to read the state */
11957         if (IS_HASWELL(dev_priv))
11958                 PIPE_CONF_CHECK_I(ips_enabled);
11959
11960         PIPE_CONF_CHECK_I(double_wide);
11961
11962         PIPE_CONF_CHECK_P(shared_dpll);
11963         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11964         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11965         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11966         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11967         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11968         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11969         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11970         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11971         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11972
11973         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11974         PIPE_CONF_CHECK_X(dsi_pll.div);
11975
11976         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11977                 PIPE_CONF_CHECK_I(pipe_bpp);
11978
11979         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11980         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11981
11982 #undef PIPE_CONF_CHECK_X
11983 #undef PIPE_CONF_CHECK_I
11984 #undef PIPE_CONF_CHECK_P
11985 #undef PIPE_CONF_CHECK_FLAGS
11986 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11987 #undef PIPE_CONF_QUIRK
11988
11989         return ret;
11990 }
11991
11992 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11993                                            const struct intel_crtc_state *pipe_config)
11994 {
11995         if (pipe_config->has_pch_encoder) {
11996                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11997                                                             &pipe_config->fdi_m_n);
11998                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11999
12000                 /*
12001                  * FDI already provided one idea for the dotclock.
12002                  * Yell if the encoder disagrees.
12003                  */
12004                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12005                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12006                      fdi_dotclock, dotclock);
12007         }
12008 }
12009
12010 static void verify_wm_state(struct drm_crtc *crtc,
12011                             struct drm_crtc_state *new_state)
12012 {
12013         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12014         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12015         struct skl_pipe_wm hw_wm, *sw_wm;
12016         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12017         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12018         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12019         const enum pipe pipe = intel_crtc->pipe;
12020         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12021
12022         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12023                 return;
12024
12025         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
12026         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12027
12028         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12029         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12030
12031         /* planes */
12032         for_each_universal_plane(dev_priv, pipe, plane) {
12033                 hw_plane_wm = &hw_wm.planes[plane];
12034                 sw_plane_wm = &sw_wm->planes[plane];
12035
12036                 /* Watermarks */
12037                 for (level = 0; level <= max_level; level++) {
12038                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12039                                                 &sw_plane_wm->wm[level]))
12040                                 continue;
12041
12042                         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",
12043                                   pipe_name(pipe), plane + 1, level,
12044                                   sw_plane_wm->wm[level].plane_en,
12045                                   sw_plane_wm->wm[level].plane_res_b,
12046                                   sw_plane_wm->wm[level].plane_res_l,
12047                                   hw_plane_wm->wm[level].plane_en,
12048                                   hw_plane_wm->wm[level].plane_res_b,
12049                                   hw_plane_wm->wm[level].plane_res_l);
12050                 }
12051
12052                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12053                                          &sw_plane_wm->trans_wm)) {
12054                         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",
12055                                   pipe_name(pipe), plane + 1,
12056                                   sw_plane_wm->trans_wm.plane_en,
12057                                   sw_plane_wm->trans_wm.plane_res_b,
12058                                   sw_plane_wm->trans_wm.plane_res_l,
12059                                   hw_plane_wm->trans_wm.plane_en,
12060                                   hw_plane_wm->trans_wm.plane_res_b,
12061                                   hw_plane_wm->trans_wm.plane_res_l);
12062                 }
12063
12064                 /* DDB */
12065                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
12066                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
12067
12068                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12069                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12070                                   pipe_name(pipe), plane + 1,
12071                                   sw_ddb_entry->start, sw_ddb_entry->end,
12072                                   hw_ddb_entry->start, hw_ddb_entry->end);
12073                 }
12074         }
12075
12076         /*
12077          * cursor
12078          * If the cursor plane isn't active, we may not have updated it's ddb
12079          * allocation. In that case since the ddb allocation will be updated
12080          * once the plane becomes visible, we can skip this check
12081          */
12082         if (1) {
12083                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
12084                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12085
12086                 /* Watermarks */
12087                 for (level = 0; level <= max_level; level++) {
12088                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12089                                                 &sw_plane_wm->wm[level]))
12090                                 continue;
12091
12092                         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",
12093                                   pipe_name(pipe), level,
12094                                   sw_plane_wm->wm[level].plane_en,
12095                                   sw_plane_wm->wm[level].plane_res_b,
12096                                   sw_plane_wm->wm[level].plane_res_l,
12097                                   hw_plane_wm->wm[level].plane_en,
12098                                   hw_plane_wm->wm[level].plane_res_b,
12099                                   hw_plane_wm->wm[level].plane_res_l);
12100                 }
12101
12102                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12103                                          &sw_plane_wm->trans_wm)) {
12104                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12105                                   pipe_name(pipe),
12106                                   sw_plane_wm->trans_wm.plane_en,
12107                                   sw_plane_wm->trans_wm.plane_res_b,
12108                                   sw_plane_wm->trans_wm.plane_res_l,
12109                                   hw_plane_wm->trans_wm.plane_en,
12110                                   hw_plane_wm->trans_wm.plane_res_b,
12111                                   hw_plane_wm->trans_wm.plane_res_l);
12112                 }
12113
12114                 /* DDB */
12115                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12116                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12117
12118                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12119                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12120                                   pipe_name(pipe),
12121                                   sw_ddb_entry->start, sw_ddb_entry->end,
12122                                   hw_ddb_entry->start, hw_ddb_entry->end);
12123                 }
12124         }
12125 }
12126
12127 static void
12128 verify_connector_state(struct drm_device *dev,
12129                        struct drm_atomic_state *state,
12130                        struct drm_crtc *crtc)
12131 {
12132         struct drm_connector *connector;
12133         struct drm_connector_state *new_conn_state;
12134         int i;
12135
12136         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12137                 struct drm_encoder *encoder = connector->encoder;
12138                 struct drm_crtc_state *crtc_state = NULL;
12139
12140                 if (new_conn_state->crtc != crtc)
12141                         continue;
12142
12143                 if (crtc)
12144                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12145
12146                 intel_connector_verify_state(crtc_state, new_conn_state);
12147
12148                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12149                      "connector's atomic encoder doesn't match legacy encoder\n");
12150         }
12151 }
12152
12153 static void
12154 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12155 {
12156         struct intel_encoder *encoder;
12157         struct drm_connector *connector;
12158         struct drm_connector_state *old_conn_state, *new_conn_state;
12159         int i;
12160
12161         for_each_intel_encoder(dev, encoder) {
12162                 bool enabled = false, found = false;
12163                 enum pipe pipe;
12164
12165                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12166                               encoder->base.base.id,
12167                               encoder->base.name);
12168
12169                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12170                                                    new_conn_state, i) {
12171                         if (old_conn_state->best_encoder == &encoder->base)
12172                                 found = true;
12173
12174                         if (new_conn_state->best_encoder != &encoder->base)
12175                                 continue;
12176                         found = enabled = true;
12177
12178                         I915_STATE_WARN(new_conn_state->crtc !=
12179                                         encoder->base.crtc,
12180                              "connector's crtc doesn't match encoder crtc\n");
12181                 }
12182
12183                 if (!found)
12184                         continue;
12185
12186                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12187                      "encoder's enabled state mismatch "
12188                      "(expected %i, found %i)\n",
12189                      !!encoder->base.crtc, enabled);
12190
12191                 if (!encoder->base.crtc) {
12192                         bool active;
12193
12194                         active = encoder->get_hw_state(encoder, &pipe);
12195                         I915_STATE_WARN(active,
12196                              "encoder detached but still enabled on pipe %c.\n",
12197                              pipe_name(pipe));
12198                 }
12199         }
12200 }
12201
12202 static void
12203 verify_crtc_state(struct drm_crtc *crtc,
12204                   struct drm_crtc_state *old_crtc_state,
12205                   struct drm_crtc_state *new_crtc_state)
12206 {
12207         struct drm_device *dev = crtc->dev;
12208         struct drm_i915_private *dev_priv = to_i915(dev);
12209         struct intel_encoder *encoder;
12210         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12211         struct intel_crtc_state *pipe_config, *sw_config;
12212         struct drm_atomic_state *old_state;
12213         bool active;
12214
12215         old_state = old_crtc_state->state;
12216         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12217         pipe_config = to_intel_crtc_state(old_crtc_state);
12218         memset(pipe_config, 0, sizeof(*pipe_config));
12219         pipe_config->base.crtc = crtc;
12220         pipe_config->base.state = old_state;
12221
12222         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12223
12224         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12225
12226         /* we keep both pipes enabled on 830 */
12227         if (IS_I830(dev_priv))
12228                 active = new_crtc_state->active;
12229
12230         I915_STATE_WARN(new_crtc_state->active != active,
12231              "crtc active state doesn't match with hw state "
12232              "(expected %i, found %i)\n", new_crtc_state->active, active);
12233
12234         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12235              "transitional active state does not match atomic hw state "
12236              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12237
12238         for_each_encoder_on_crtc(dev, crtc, encoder) {
12239                 enum pipe pipe;
12240
12241                 active = encoder->get_hw_state(encoder, &pipe);
12242                 I915_STATE_WARN(active != new_crtc_state->active,
12243                         "[ENCODER:%i] active %i with crtc active %i\n",
12244                         encoder->base.base.id, active, new_crtc_state->active);
12245
12246                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12247                                 "Encoder connected to wrong pipe %c\n",
12248                                 pipe_name(pipe));
12249
12250                 if (active) {
12251                         pipe_config->output_types |= 1 << encoder->type;
12252                         encoder->get_config(encoder, pipe_config);
12253                 }
12254         }
12255
12256         intel_crtc_compute_pixel_rate(pipe_config);
12257
12258         if (!new_crtc_state->active)
12259                 return;
12260
12261         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12262
12263         sw_config = to_intel_crtc_state(new_crtc_state);
12264         if (!intel_pipe_config_compare(dev_priv, sw_config,
12265                                        pipe_config, false)) {
12266                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12267                 intel_dump_pipe_config(intel_crtc, pipe_config,
12268                                        "[hw state]");
12269                 intel_dump_pipe_config(intel_crtc, sw_config,
12270                                        "[sw state]");
12271         }
12272 }
12273
12274 static void
12275 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12276                          struct intel_shared_dpll *pll,
12277                          struct drm_crtc *crtc,
12278                          struct drm_crtc_state *new_state)
12279 {
12280         struct intel_dpll_hw_state dpll_hw_state;
12281         unsigned crtc_mask;
12282         bool active;
12283
12284         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12285
12286         DRM_DEBUG_KMS("%s\n", pll->name);
12287
12288         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12289
12290         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12291                 I915_STATE_WARN(!pll->on && pll->active_mask,
12292                      "pll in active use but not on in sw tracking\n");
12293                 I915_STATE_WARN(pll->on && !pll->active_mask,
12294                      "pll is on but not used by any active crtc\n");
12295                 I915_STATE_WARN(pll->on != active,
12296                      "pll on state mismatch (expected %i, found %i)\n",
12297                      pll->on, active);
12298         }
12299
12300         if (!crtc) {
12301                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12302                                 "more active pll users than references: %x vs %x\n",
12303                                 pll->active_mask, pll->state.crtc_mask);
12304
12305                 return;
12306         }
12307
12308         crtc_mask = 1 << drm_crtc_index(crtc);
12309
12310         if (new_state->active)
12311                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12312                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12313                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12314         else
12315                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12316                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12317                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12318
12319         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12320                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12321                         crtc_mask, pll->state.crtc_mask);
12322
12323         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12324                                           &dpll_hw_state,
12325                                           sizeof(dpll_hw_state)),
12326                         "pll hw state mismatch\n");
12327 }
12328
12329 static void
12330 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12331                          struct drm_crtc_state *old_crtc_state,
12332                          struct drm_crtc_state *new_crtc_state)
12333 {
12334         struct drm_i915_private *dev_priv = to_i915(dev);
12335         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12336         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12337
12338         if (new_state->shared_dpll)
12339                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12340
12341         if (old_state->shared_dpll &&
12342             old_state->shared_dpll != new_state->shared_dpll) {
12343                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
12344                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12345
12346                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12347                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12348                                 pipe_name(drm_crtc_index(crtc)));
12349                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12350                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12351                                 pipe_name(drm_crtc_index(crtc)));
12352         }
12353 }
12354
12355 static void
12356 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12357                           struct drm_atomic_state *state,
12358                           struct drm_crtc_state *old_state,
12359                           struct drm_crtc_state *new_state)
12360 {
12361         if (!needs_modeset(new_state) &&
12362             !to_intel_crtc_state(new_state)->update_pipe)
12363                 return;
12364
12365         verify_wm_state(crtc, new_state);
12366         verify_connector_state(crtc->dev, state, crtc);
12367         verify_crtc_state(crtc, old_state, new_state);
12368         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12369 }
12370
12371 static void
12372 verify_disabled_dpll_state(struct drm_device *dev)
12373 {
12374         struct drm_i915_private *dev_priv = to_i915(dev);
12375         int i;
12376
12377         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12378                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12379 }
12380
12381 static void
12382 intel_modeset_verify_disabled(struct drm_device *dev,
12383                               struct drm_atomic_state *state)
12384 {
12385         verify_encoder_state(dev, state);
12386         verify_connector_state(dev, state, NULL);
12387         verify_disabled_dpll_state(dev);
12388 }
12389
12390 static void update_scanline_offset(struct intel_crtc *crtc)
12391 {
12392         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12393
12394         /*
12395          * The scanline counter increments at the leading edge of hsync.
12396          *
12397          * On most platforms it starts counting from vtotal-1 on the
12398          * first active line. That means the scanline counter value is
12399          * always one less than what we would expect. Ie. just after
12400          * start of vblank, which also occurs at start of hsync (on the
12401          * last active line), the scanline counter will read vblank_start-1.
12402          *
12403          * On gen2 the scanline counter starts counting from 1 instead
12404          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12405          * to keep the value positive), instead of adding one.
12406          *
12407          * On HSW+ the behaviour of the scanline counter depends on the output
12408          * type. For DP ports it behaves like most other platforms, but on HDMI
12409          * there's an extra 1 line difference. So we need to add two instead of
12410          * one to the value.
12411          *
12412          * On VLV/CHV DSI the scanline counter would appear to increment
12413          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12414          * that means we can't tell whether we're in vblank or not while
12415          * we're on that particular line. We must still set scanline_offset
12416          * to 1 so that the vblank timestamps come out correct when we query
12417          * the scanline counter from within the vblank interrupt handler.
12418          * However if queried just before the start of vblank we'll get an
12419          * answer that's slightly in the future.
12420          */
12421         if (IS_GEN2(dev_priv)) {
12422                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12423                 int vtotal;
12424
12425                 vtotal = adjusted_mode->crtc_vtotal;
12426                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12427                         vtotal /= 2;
12428
12429                 crtc->scanline_offset = vtotal - 1;
12430         } else if (HAS_DDI(dev_priv) &&
12431                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12432                 crtc->scanline_offset = 2;
12433         } else
12434                 crtc->scanline_offset = 1;
12435 }
12436
12437 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12438 {
12439         struct drm_device *dev = state->dev;
12440         struct drm_i915_private *dev_priv = to_i915(dev);
12441         struct drm_crtc *crtc;
12442         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12443         int i;
12444
12445         if (!dev_priv->display.crtc_compute_clock)
12446                 return;
12447
12448         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12449                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12450                 struct intel_shared_dpll *old_dpll =
12451                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12452
12453                 if (!needs_modeset(new_crtc_state))
12454                         continue;
12455
12456                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12457
12458                 if (!old_dpll)
12459                         continue;
12460
12461                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12462         }
12463 }
12464
12465 /*
12466  * This implements the workaround described in the "notes" section of the mode
12467  * set sequence documentation. When going from no pipes or single pipe to
12468  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12469  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12470  */
12471 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12472 {
12473         struct drm_crtc_state *crtc_state;
12474         struct intel_crtc *intel_crtc;
12475         struct drm_crtc *crtc;
12476         struct intel_crtc_state *first_crtc_state = NULL;
12477         struct intel_crtc_state *other_crtc_state = NULL;
12478         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12479         int i;
12480
12481         /* look at all crtc's that are going to be enabled in during modeset */
12482         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12483                 intel_crtc = to_intel_crtc(crtc);
12484
12485                 if (!crtc_state->active || !needs_modeset(crtc_state))
12486                         continue;
12487
12488                 if (first_crtc_state) {
12489                         other_crtc_state = to_intel_crtc_state(crtc_state);
12490                         break;
12491                 } else {
12492                         first_crtc_state = to_intel_crtc_state(crtc_state);
12493                         first_pipe = intel_crtc->pipe;
12494                 }
12495         }
12496
12497         /* No workaround needed? */
12498         if (!first_crtc_state)
12499                 return 0;
12500
12501         /* w/a possibly needed, check how many crtc's are already enabled. */
12502         for_each_intel_crtc(state->dev, intel_crtc) {
12503                 struct intel_crtc_state *pipe_config;
12504
12505                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12506                 if (IS_ERR(pipe_config))
12507                         return PTR_ERR(pipe_config);
12508
12509                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12510
12511                 if (!pipe_config->base.active ||
12512                     needs_modeset(&pipe_config->base))
12513                         continue;
12514
12515                 /* 2 or more enabled crtcs means no need for w/a */
12516                 if (enabled_pipe != INVALID_PIPE)
12517                         return 0;
12518
12519                 enabled_pipe = intel_crtc->pipe;
12520         }
12521
12522         if (enabled_pipe != INVALID_PIPE)
12523                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12524         else if (other_crtc_state)
12525                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12526
12527         return 0;
12528 }
12529
12530 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12531 {
12532         struct drm_crtc *crtc;
12533
12534         /* Add all pipes to the state */
12535         for_each_crtc(state->dev, crtc) {
12536                 struct drm_crtc_state *crtc_state;
12537
12538                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12539                 if (IS_ERR(crtc_state))
12540                         return PTR_ERR(crtc_state);
12541         }
12542
12543         return 0;
12544 }
12545
12546 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12547 {
12548         struct drm_crtc *crtc;
12549
12550         /*
12551          * Add all pipes to the state, and force
12552          * a modeset on all the active ones.
12553          */
12554         for_each_crtc(state->dev, crtc) {
12555                 struct drm_crtc_state *crtc_state;
12556                 int ret;
12557
12558                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12559                 if (IS_ERR(crtc_state))
12560                         return PTR_ERR(crtc_state);
12561
12562                 if (!crtc_state->active || needs_modeset(crtc_state))
12563                         continue;
12564
12565                 crtc_state->mode_changed = true;
12566
12567                 ret = drm_atomic_add_affected_connectors(state, crtc);
12568                 if (ret)
12569                         return ret;
12570
12571                 ret = drm_atomic_add_affected_planes(state, crtc);
12572                 if (ret)
12573                         return ret;
12574         }
12575
12576         return 0;
12577 }
12578
12579 static int intel_modeset_checks(struct drm_atomic_state *state)
12580 {
12581         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12582         struct drm_i915_private *dev_priv = to_i915(state->dev);
12583         struct drm_crtc *crtc;
12584         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12585         int ret = 0, i;
12586
12587         if (!check_digital_port_conflicts(state)) {
12588                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12589                 return -EINVAL;
12590         }
12591
12592         intel_state->modeset = true;
12593         intel_state->active_crtcs = dev_priv->active_crtcs;
12594         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12595         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12596
12597         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12598                 if (new_crtc_state->active)
12599                         intel_state->active_crtcs |= 1 << i;
12600                 else
12601                         intel_state->active_crtcs &= ~(1 << i);
12602
12603                 if (old_crtc_state->active != new_crtc_state->active)
12604                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12605         }
12606
12607         /*
12608          * See if the config requires any additional preparation, e.g.
12609          * to adjust global state with pipes off.  We need to do this
12610          * here so we can get the modeset_pipe updated config for the new
12611          * mode set on this crtc.  For other crtcs we need to use the
12612          * adjusted_mode bits in the crtc directly.
12613          */
12614         if (dev_priv->display.modeset_calc_cdclk) {
12615                 ret = dev_priv->display.modeset_calc_cdclk(state);
12616                 if (ret < 0)
12617                         return ret;
12618
12619                 /*
12620                  * Writes to dev_priv->cdclk.logical must protected by
12621                  * holding all the crtc locks, even if we don't end up
12622                  * touching the hardware
12623                  */
12624                 if (!intel_cdclk_state_compare(&dev_priv->cdclk.logical,
12625                                                &intel_state->cdclk.logical)) {
12626                         ret = intel_lock_all_pipes(state);
12627                         if (ret < 0)
12628                                 return ret;
12629                 }
12630
12631                 /* All pipes must be switched off while we change the cdclk. */
12632                 if (!intel_cdclk_state_compare(&dev_priv->cdclk.actual,
12633                                                &intel_state->cdclk.actual)) {
12634                         ret = intel_modeset_all_pipes(state);
12635                         if (ret < 0)
12636                                 return ret;
12637                 }
12638
12639                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12640                               intel_state->cdclk.logical.cdclk,
12641                               intel_state->cdclk.actual.cdclk);
12642         } else {
12643                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12644         }
12645
12646         intel_modeset_clear_plls(state);
12647
12648         if (IS_HASWELL(dev_priv))
12649                 return haswell_mode_set_planes_workaround(state);
12650
12651         return 0;
12652 }
12653
12654 /*
12655  * Handle calculation of various watermark data at the end of the atomic check
12656  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12657  * handlers to ensure that all derived state has been updated.
12658  */
12659 static int calc_watermark_data(struct drm_atomic_state *state)
12660 {
12661         struct drm_device *dev = state->dev;
12662         struct drm_i915_private *dev_priv = to_i915(dev);
12663
12664         /* Is there platform-specific watermark information to calculate? */
12665         if (dev_priv->display.compute_global_watermarks)
12666                 return dev_priv->display.compute_global_watermarks(state);
12667
12668         return 0;
12669 }
12670
12671 /**
12672  * intel_atomic_check - validate state object
12673  * @dev: drm device
12674  * @state: state to validate
12675  */
12676 static int intel_atomic_check(struct drm_device *dev,
12677                               struct drm_atomic_state *state)
12678 {
12679         struct drm_i915_private *dev_priv = to_i915(dev);
12680         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12681         struct drm_crtc *crtc;
12682         struct drm_crtc_state *old_crtc_state, *crtc_state;
12683         int ret, i;
12684         bool any_ms = false;
12685
12686         ret = drm_atomic_helper_check_modeset(dev, state);
12687         if (ret)
12688                 return ret;
12689
12690         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12691                 struct intel_crtc_state *pipe_config =
12692                         to_intel_crtc_state(crtc_state);
12693
12694                 /* Catch I915_MODE_FLAG_INHERITED */
12695                 if (crtc_state->mode.private_flags != old_crtc_state->mode.private_flags)
12696                         crtc_state->mode_changed = true;
12697
12698                 if (!needs_modeset(crtc_state))
12699                         continue;
12700
12701                 if (!crtc_state->enable) {
12702                         any_ms = true;
12703                         continue;
12704                 }
12705
12706                 /* FIXME: For only active_changed we shouldn't need to do any
12707                  * state recomputation at all. */
12708
12709                 ret = drm_atomic_add_affected_connectors(state, crtc);
12710                 if (ret)
12711                         return ret;
12712
12713                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12714                 if (ret) {
12715                         intel_dump_pipe_config(to_intel_crtc(crtc),
12716                                                pipe_config, "[failed]");
12717                         return ret;
12718                 }
12719
12720                 if (i915.fastboot &&
12721                     intel_pipe_config_compare(dev_priv,
12722                                         to_intel_crtc_state(old_crtc_state),
12723                                         pipe_config, true)) {
12724                         crtc_state->mode_changed = false;
12725                         pipe_config->update_pipe = true;
12726                 }
12727
12728                 if (needs_modeset(crtc_state))
12729                         any_ms = true;
12730
12731                 ret = drm_atomic_add_affected_planes(state, crtc);
12732                 if (ret)
12733                         return ret;
12734
12735                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12736                                        needs_modeset(crtc_state) ?
12737                                        "[modeset]" : "[fastset]");
12738         }
12739
12740         if (any_ms) {
12741                 ret = intel_modeset_checks(state);
12742
12743                 if (ret)
12744                         return ret;
12745         } else {
12746                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12747         }
12748
12749         ret = drm_atomic_helper_check_planes(dev, state);
12750         if (ret)
12751                 return ret;
12752
12753         intel_fbc_choose_crtc(dev_priv, state);
12754         return calc_watermark_data(state);
12755 }
12756
12757 static int intel_atomic_prepare_commit(struct drm_device *dev,
12758                                        struct drm_atomic_state *state)
12759 {
12760         struct drm_i915_private *dev_priv = to_i915(dev);
12761         struct drm_crtc_state *crtc_state;
12762         struct drm_crtc *crtc;
12763         int i, ret;
12764
12765         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12766                 if (state->legacy_cursor_update)
12767                         continue;
12768
12769                 ret = intel_crtc_wait_for_pending_flips(crtc);
12770                 if (ret)
12771                         return ret;
12772
12773                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
12774                         flush_workqueue(dev_priv->wq);
12775         }
12776
12777         ret = mutex_lock_interruptible(&dev->struct_mutex);
12778         if (ret)
12779                 return ret;
12780
12781         ret = drm_atomic_helper_prepare_planes(dev, state);
12782         mutex_unlock(&dev->struct_mutex);
12783
12784         return ret;
12785 }
12786
12787 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12788 {
12789         struct drm_device *dev = crtc->base.dev;
12790
12791         if (!dev->max_vblank_count)
12792                 return drm_accurate_vblank_count(&crtc->base);
12793
12794         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12795 }
12796
12797 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
12798                                           struct drm_i915_private *dev_priv,
12799                                           unsigned crtc_mask)
12800 {
12801         unsigned last_vblank_count[I915_MAX_PIPES];
12802         enum pipe pipe;
12803         int ret;
12804
12805         if (!crtc_mask)
12806                 return;
12807
12808         for_each_pipe(dev_priv, pipe) {
12809                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
12810                                                                   pipe);
12811
12812                 if (!((1 << pipe) & crtc_mask))
12813                         continue;
12814
12815                 ret = drm_crtc_vblank_get(&crtc->base);
12816                 if (WARN_ON(ret != 0)) {
12817                         crtc_mask &= ~(1 << pipe);
12818                         continue;
12819                 }
12820
12821                 last_vblank_count[pipe] = drm_crtc_vblank_count(&crtc->base);
12822         }
12823
12824         for_each_pipe(dev_priv, pipe) {
12825                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
12826                                                                   pipe);
12827                 long lret;
12828
12829                 if (!((1 << pipe) & crtc_mask))
12830                         continue;
12831
12832                 lret = wait_event_timeout(dev->vblank[pipe].queue,
12833                                 last_vblank_count[pipe] !=
12834                                         drm_crtc_vblank_count(&crtc->base),
12835                                 msecs_to_jiffies(50));
12836
12837                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
12838
12839                 drm_crtc_vblank_put(&crtc->base);
12840         }
12841 }
12842
12843 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
12844 {
12845         /* fb updated, need to unpin old fb */
12846         if (crtc_state->fb_changed)
12847                 return true;
12848
12849         /* wm changes, need vblank before final wm's */
12850         if (crtc_state->update_wm_post)
12851                 return true;
12852
12853         if (crtc_state->wm.need_postvbl_update)
12854                 return true;
12855
12856         return false;
12857 }
12858
12859 static void intel_update_crtc(struct drm_crtc *crtc,
12860                               struct drm_atomic_state *state,
12861                               struct drm_crtc_state *old_crtc_state,
12862                               struct drm_crtc_state *new_crtc_state,
12863                               unsigned int *crtc_vblank_mask)
12864 {
12865         struct drm_device *dev = crtc->dev;
12866         struct drm_i915_private *dev_priv = to_i915(dev);
12867         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12868         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12869         bool modeset = needs_modeset(new_crtc_state);
12870
12871         if (modeset) {
12872                 update_scanline_offset(intel_crtc);
12873                 dev_priv->display.crtc_enable(pipe_config, state);
12874         } else {
12875                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12876                                        pipe_config);
12877         }
12878
12879         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12880                 intel_fbc_enable(
12881                     intel_crtc, pipe_config,
12882                     to_intel_plane_state(crtc->primary->state));
12883         }
12884
12885         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12886
12887         if (needs_vblank_wait(pipe_config))
12888                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
12889 }
12890
12891 static void intel_update_crtcs(struct drm_atomic_state *state,
12892                                unsigned int *crtc_vblank_mask)
12893 {
12894         struct drm_crtc *crtc;
12895         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12896         int i;
12897
12898         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12899                 if (!new_crtc_state->active)
12900                         continue;
12901
12902                 intel_update_crtc(crtc, state, old_crtc_state,
12903                                   new_crtc_state, crtc_vblank_mask);
12904         }
12905 }
12906
12907 static void skl_update_crtcs(struct drm_atomic_state *state,
12908                              unsigned int *crtc_vblank_mask)
12909 {
12910         struct drm_i915_private *dev_priv = to_i915(state->dev);
12911         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12912         struct drm_crtc *crtc;
12913         struct intel_crtc *intel_crtc;
12914         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12915         struct intel_crtc_state *cstate;
12916         unsigned int updated = 0;
12917         bool progress;
12918         enum pipe pipe;
12919         int i;
12920
12921         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12922
12923         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12924                 /* ignore allocations for crtc's that have been turned off. */
12925                 if (new_crtc_state->active)
12926                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12927
12928         /*
12929          * Whenever the number of active pipes changes, we need to make sure we
12930          * update the pipes in the right order so that their ddb allocations
12931          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12932          * cause pipe underruns and other bad stuff.
12933          */
12934         do {
12935                 progress = false;
12936
12937                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12938                         bool vbl_wait = false;
12939                         unsigned int cmask = drm_crtc_mask(crtc);
12940
12941                         intel_crtc = to_intel_crtc(crtc);
12942                         cstate = to_intel_crtc_state(crtc->state);
12943                         pipe = intel_crtc->pipe;
12944
12945                         if (updated & cmask || !cstate->base.active)
12946                                 continue;
12947
12948                         if (skl_ddb_allocation_overlaps(entries, &cstate->wm.skl.ddb, i))
12949                                 continue;
12950
12951                         updated |= cmask;
12952                         entries[i] = &cstate->wm.skl.ddb;
12953
12954                         /*
12955                          * If this is an already active pipe, it's DDB changed,
12956                          * and this isn't the last pipe that needs updating
12957                          * then we need to wait for a vblank to pass for the
12958                          * new ddb allocation to take effect.
12959                          */
12960                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12961                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12962                             !new_crtc_state->active_changed &&
12963                             intel_state->wm_results.dirty_pipes != updated)
12964                                 vbl_wait = true;
12965
12966                         intel_update_crtc(crtc, state, old_crtc_state,
12967                                           new_crtc_state, crtc_vblank_mask);
12968
12969                         if (vbl_wait)
12970                                 intel_wait_for_vblank(dev_priv, pipe);
12971
12972                         progress = true;
12973                 }
12974         } while (progress);
12975 }
12976
12977 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12978 {
12979         struct intel_atomic_state *state, *next;
12980         struct llist_node *freed;
12981
12982         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12983         llist_for_each_entry_safe(state, next, freed, freed)
12984                 drm_atomic_state_put(&state->base);
12985 }
12986
12987 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12988 {
12989         struct drm_i915_private *dev_priv =
12990                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12991
12992         intel_atomic_helper_free_state(dev_priv);
12993 }
12994
12995 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12996 {
12997         struct drm_device *dev = state->dev;
12998         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12999         struct drm_i915_private *dev_priv = to_i915(dev);
13000         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13001         struct drm_crtc *crtc;
13002         struct intel_crtc_state *intel_cstate;
13003         bool hw_check = intel_state->modeset;
13004         u64 put_domains[I915_MAX_PIPES] = {};
13005         unsigned crtc_vblank_mask = 0;
13006         int i;
13007
13008         drm_atomic_helper_wait_for_dependencies(state);
13009
13010         if (intel_state->modeset)
13011                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13012
13013         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13014                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13015
13016                 if (needs_modeset(new_crtc_state) ||
13017                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13018                         hw_check = true;
13019
13020                         put_domains[to_intel_crtc(crtc)->pipe] =
13021                                 modeset_get_crtc_power_domains(crtc,
13022                                         to_intel_crtc_state(new_crtc_state));
13023                 }
13024
13025                 if (!needs_modeset(new_crtc_state))
13026                         continue;
13027
13028                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
13029                                        to_intel_crtc_state(new_crtc_state));
13030
13031                 if (old_crtc_state->active) {
13032                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13033                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
13034                         intel_crtc->active = false;
13035                         intel_fbc_disable(intel_crtc);
13036                         intel_disable_shared_dpll(intel_crtc);
13037
13038                         /*
13039                          * Underruns don't always raise
13040                          * interrupts, so check manually.
13041                          */
13042                         intel_check_cpu_fifo_underruns(dev_priv);
13043                         intel_check_pch_fifo_underruns(dev_priv);
13044
13045                         if (!crtc->state->active) {
13046                                 /*
13047                                  * Make sure we don't call initial_watermarks
13048                                  * for ILK-style watermark updates.
13049                                  *
13050                                  * No clue what this is supposed to achieve.
13051                                  */
13052                                 if (INTEL_GEN(dev_priv) >= 9)
13053                                         dev_priv->display.initial_watermarks(intel_state,
13054                                                                              to_intel_crtc_state(crtc->state));
13055                         }
13056                 }
13057         }
13058
13059         /* Only after disabling all output pipelines that will be changed can we
13060          * update the the output configuration. */
13061         intel_modeset_update_crtc_state(state);
13062
13063         if (intel_state->modeset) {
13064                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13065
13066                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
13067
13068                 /*
13069                  * SKL workaround: bspec recommends we disable the SAGV when we
13070                  * have more then one pipe enabled
13071                  */
13072                 if (!intel_can_enable_sagv(state))
13073                         intel_disable_sagv(dev_priv);
13074
13075                 intel_modeset_verify_disabled(dev, state);
13076         }
13077
13078         /* Complete the events for pipes that have now been disabled */
13079         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13080                 bool modeset = needs_modeset(new_crtc_state);
13081
13082                 /* Complete events for now disable pipes here. */
13083                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13084                         spin_lock_irq(&dev->event_lock);
13085                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13086                         spin_unlock_irq(&dev->event_lock);
13087
13088                         new_crtc_state->event = NULL;
13089                 }
13090         }
13091
13092         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13093         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
13094
13095         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13096          * already, but still need the state for the delayed optimization. To
13097          * fix this:
13098          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13099          * - schedule that vblank worker _before_ calling hw_done
13100          * - at the start of commit_tail, cancel it _synchrously
13101          * - switch over to the vblank wait helper in the core after that since
13102          *   we don't need out special handling any more.
13103          */
13104         if (!state->legacy_cursor_update)
13105                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13106
13107         /*
13108          * Now that the vblank has passed, we can go ahead and program the
13109          * optimal watermarks on platforms that need two-step watermark
13110          * programming.
13111          *
13112          * TODO: Move this (and other cleanup) to an async worker eventually.
13113          */
13114         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13115                 intel_cstate = to_intel_crtc_state(new_crtc_state);
13116
13117                 if (dev_priv->display.optimize_watermarks)
13118                         dev_priv->display.optimize_watermarks(intel_state,
13119                                                               intel_cstate);
13120         }
13121
13122         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13123                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13124
13125                 if (put_domains[i])
13126                         modeset_put_power_domains(dev_priv, put_domains[i]);
13127
13128                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13129         }
13130
13131         if (intel_state->modeset && intel_can_enable_sagv(state))
13132                 intel_enable_sagv(dev_priv);
13133
13134         drm_atomic_helper_commit_hw_done(state);
13135
13136         if (intel_state->modeset) {
13137                 /* As one of the primary mmio accessors, KMS has a high
13138                  * likelihood of triggering bugs in unclaimed access. After we
13139                  * finish modesetting, see if an error has been flagged, and if
13140                  * so enable debugging for the next modeset - and hope we catch
13141                  * the culprit.
13142                  */
13143                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13144                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13145         }
13146
13147         mutex_lock(&dev->struct_mutex);
13148         drm_atomic_helper_cleanup_planes(dev, state);
13149         mutex_unlock(&dev->struct_mutex);
13150
13151         drm_atomic_helper_commit_cleanup_done(state);
13152
13153         drm_atomic_state_put(state);
13154
13155         intel_atomic_helper_free_state(dev_priv);
13156 }
13157
13158 static void intel_atomic_commit_work(struct work_struct *work)
13159 {
13160         struct drm_atomic_state *state =
13161                 container_of(work, struct drm_atomic_state, commit_work);
13162
13163         intel_atomic_commit_tail(state);
13164 }
13165
13166 static int __i915_sw_fence_call
13167 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13168                           enum i915_sw_fence_notify notify)
13169 {
13170         struct intel_atomic_state *state =
13171                 container_of(fence, struct intel_atomic_state, commit_ready);
13172
13173         switch (notify) {
13174         case FENCE_COMPLETE:
13175                 if (state->base.commit_work.func)
13176                         queue_work(system_unbound_wq, &state->base.commit_work);
13177                 break;
13178
13179         case FENCE_FREE:
13180                 {
13181                         struct intel_atomic_helper *helper =
13182                                 &to_i915(state->base.dev)->atomic_helper;
13183
13184                         if (llist_add(&state->freed, &helper->free_list))
13185                                 schedule_work(&helper->free_work);
13186                         break;
13187                 }
13188         }
13189
13190         return NOTIFY_DONE;
13191 }
13192
13193 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13194 {
13195         struct drm_plane_state *old_plane_state, *new_plane_state;
13196         struct drm_plane *plane;
13197         int i;
13198
13199         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13200                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13201                                   intel_fb_obj(new_plane_state->fb),
13202                                   to_intel_plane(plane)->frontbuffer_bit);
13203 }
13204
13205 /**
13206  * intel_atomic_commit - commit validated state object
13207  * @dev: DRM device
13208  * @state: the top-level driver state object
13209  * @nonblock: nonblocking commit
13210  *
13211  * This function commits a top-level state object that has been validated
13212  * with drm_atomic_helper_check().
13213  *
13214  * RETURNS
13215  * Zero for success or -errno.
13216  */
13217 static int intel_atomic_commit(struct drm_device *dev,
13218                                struct drm_atomic_state *state,
13219                                bool nonblock)
13220 {
13221         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13222         struct drm_i915_private *dev_priv = to_i915(dev);
13223         int ret = 0;
13224
13225         ret = drm_atomic_helper_setup_commit(state, nonblock);
13226         if (ret)
13227                 return ret;
13228
13229         drm_atomic_state_get(state);
13230         i915_sw_fence_init(&intel_state->commit_ready,
13231                            intel_atomic_commit_ready);
13232
13233         ret = intel_atomic_prepare_commit(dev, state);
13234         if (ret) {
13235                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13236                 i915_sw_fence_commit(&intel_state->commit_ready);
13237                 return ret;
13238         }
13239
13240         /*
13241          * The intel_legacy_cursor_update() fast path takes care
13242          * of avoiding the vblank waits for simple cursor
13243          * movement and flips. For cursor on/off and size changes,
13244          * we want to perform the vblank waits so that watermark
13245          * updates happen during the correct frames. Gen9+ have
13246          * double buffered watermarks and so shouldn't need this.
13247          *
13248          * Do this after drm_atomic_helper_setup_commit() and
13249          * intel_atomic_prepare_commit() because we still want
13250          * to skip the flip and fb cleanup waits. Although that
13251          * does risk yanking the mapping from under the display
13252          * engine.
13253          *
13254          * FIXME doing watermarks and fb cleanup from a vblank worker
13255          * (assuming we had any) would solve these problems.
13256          */
13257         if (INTEL_GEN(dev_priv) < 9)
13258                 state->legacy_cursor_update = false;
13259
13260         drm_atomic_helper_swap_state(state, true);
13261         dev_priv->wm.distrust_bios_wm = false;
13262         intel_shared_dpll_swap_state(state);
13263         intel_atomic_track_fbs(state);
13264
13265         if (intel_state->modeset) {
13266                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13267                        sizeof(intel_state->min_pixclk));
13268                 dev_priv->active_crtcs = intel_state->active_crtcs;
13269                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
13270                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
13271         }
13272
13273         drm_atomic_state_get(state);
13274         INIT_WORK(&state->commit_work,
13275                   nonblock ? intel_atomic_commit_work : NULL);
13276
13277         i915_sw_fence_commit(&intel_state->commit_ready);
13278         if (!nonblock) {
13279                 i915_sw_fence_wait(&intel_state->commit_ready);
13280                 intel_atomic_commit_tail(state);
13281         }
13282
13283         return 0;
13284 }
13285
13286 static const struct drm_crtc_funcs intel_crtc_funcs = {
13287         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13288         .set_config = drm_atomic_helper_set_config,
13289         .set_property = drm_atomic_helper_crtc_set_property,
13290         .destroy = intel_crtc_destroy,
13291         .page_flip = drm_atomic_helper_page_flip,
13292         .atomic_duplicate_state = intel_crtc_duplicate_state,
13293         .atomic_destroy_state = intel_crtc_destroy_state,
13294         .set_crc_source = intel_crtc_set_crc_source,
13295 };
13296
13297 /**
13298  * intel_prepare_plane_fb - Prepare fb for usage on plane
13299  * @plane: drm plane to prepare for
13300  * @fb: framebuffer to prepare for presentation
13301  *
13302  * Prepares a framebuffer for usage on a display plane.  Generally this
13303  * involves pinning the underlying object and updating the frontbuffer tracking
13304  * bits.  Some older platforms need special physical address handling for
13305  * cursor planes.
13306  *
13307  * Must be called with struct_mutex held.
13308  *
13309  * Returns 0 on success, negative error code on failure.
13310  */
13311 int
13312 intel_prepare_plane_fb(struct drm_plane *plane,
13313                        struct drm_plane_state *new_state)
13314 {
13315         struct intel_atomic_state *intel_state =
13316                 to_intel_atomic_state(new_state->state);
13317         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13318         struct drm_framebuffer *fb = new_state->fb;
13319         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13320         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13321         int ret;
13322
13323         if (obj) {
13324                 if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13325                     INTEL_INFO(dev_priv)->cursor_needs_physical) {
13326                         const int align = intel_cursor_alignment(dev_priv);
13327
13328                         ret = i915_gem_object_attach_phys(obj, align);
13329                         if (ret) {
13330                                 DRM_DEBUG_KMS("failed to attach phys object\n");
13331                                 return ret;
13332                         }
13333                 } else {
13334                         struct i915_vma *vma;
13335
13336                         vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13337                         if (IS_ERR(vma)) {
13338                                 DRM_DEBUG_KMS("failed to pin object\n");
13339                                 return PTR_ERR(vma);
13340                         }
13341
13342                         to_intel_plane_state(new_state)->vma = vma;
13343                 }
13344         }
13345
13346         if (!obj && !old_obj)
13347                 return 0;
13348
13349         if (old_obj) {
13350                 struct drm_crtc_state *crtc_state =
13351                         drm_atomic_get_existing_crtc_state(new_state->state,
13352                                                            plane->state->crtc);
13353
13354                 /* Big Hammer, we also need to ensure that any pending
13355                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13356                  * current scanout is retired before unpinning the old
13357                  * framebuffer. Note that we rely on userspace rendering
13358                  * into the buffer attached to the pipe they are waiting
13359                  * on. If not, userspace generates a GPU hang with IPEHR
13360                  * point to the MI_WAIT_FOR_EVENT.
13361                  *
13362                  * This should only fail upon a hung GPU, in which case we
13363                  * can safely continue.
13364                  */
13365                 if (needs_modeset(crtc_state)) {
13366                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13367                                                               old_obj->resv, NULL,
13368                                                               false, 0,
13369                                                               GFP_KERNEL);
13370                         if (ret < 0)
13371                                 return ret;
13372                 }
13373         }
13374
13375         if (new_state->fence) { /* explicit fencing */
13376                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13377                                                     new_state->fence,
13378                                                     I915_FENCE_TIMEOUT,
13379                                                     GFP_KERNEL);
13380                 if (ret < 0)
13381                         return ret;
13382         }
13383
13384         if (!obj)
13385                 return 0;
13386
13387         if (!new_state->fence) { /* implicit fencing */
13388                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13389                                                       obj->resv, NULL,
13390                                                       false, I915_FENCE_TIMEOUT,
13391                                                       GFP_KERNEL);
13392                 if (ret < 0)
13393                         return ret;
13394
13395                 i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
13396         }
13397
13398         return 0;
13399 }
13400
13401 /**
13402  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13403  * @plane: drm plane to clean up for
13404  * @fb: old framebuffer that was on plane
13405  *
13406  * Cleans up a framebuffer that has just been removed from a plane.
13407  *
13408  * Must be called with struct_mutex held.
13409  */
13410 void
13411 intel_cleanup_plane_fb(struct drm_plane *plane,
13412                        struct drm_plane_state *old_state)
13413 {
13414         struct i915_vma *vma;
13415
13416         /* Should only be called after a successful intel_prepare_plane_fb()! */
13417         vma = fetch_and_zero(&to_intel_plane_state(old_state)->vma);
13418         if (vma)
13419                 intel_unpin_fb_vma(vma);
13420 }
13421
13422 int
13423 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13424 {
13425         struct drm_i915_private *dev_priv;
13426         int max_scale;
13427         int crtc_clock, max_dotclk;
13428
13429         if (!intel_crtc || !crtc_state->base.enable)
13430                 return DRM_PLANE_HELPER_NO_SCALING;
13431
13432         dev_priv = to_i915(intel_crtc->base.dev);
13433
13434         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13435         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13436
13437         if (IS_GEMINILAKE(dev_priv))
13438                 max_dotclk *= 2;
13439
13440         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13441                 return DRM_PLANE_HELPER_NO_SCALING;
13442
13443         /*
13444          * skl max scale is lower of:
13445          *    close to 3 but not 3, -1 is for that purpose
13446          *            or
13447          *    cdclk/crtc_clock
13448          */
13449         max_scale = min((1 << 16) * 3 - 1,
13450                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
13451
13452         return max_scale;
13453 }
13454
13455 static int
13456 intel_check_primary_plane(struct intel_plane *plane,
13457                           struct intel_crtc_state *crtc_state,
13458                           struct intel_plane_state *state)
13459 {
13460         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13461         struct drm_crtc *crtc = state->base.crtc;
13462         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13463         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13464         bool can_position = false;
13465         int ret;
13466
13467         if (INTEL_GEN(dev_priv) >= 9) {
13468                 /* use scaler when colorkey is not required */
13469                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13470                         min_scale = 1;
13471                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13472                 }
13473                 can_position = true;
13474         }
13475
13476         ret = drm_plane_helper_check_state(&state->base,
13477                                            &state->clip,
13478                                            min_scale, max_scale,
13479                                            can_position, true);
13480         if (ret)
13481                 return ret;
13482
13483         if (!state->base.fb)
13484                 return 0;
13485
13486         if (INTEL_GEN(dev_priv) >= 9) {
13487                 ret = skl_check_plane_surface(state);
13488                 if (ret)
13489                         return ret;
13490
13491                 state->ctl = skl_plane_ctl(crtc_state, state);
13492         } else {
13493                 ret = i9xx_check_plane_surface(state);
13494                 if (ret)
13495                         return ret;
13496
13497                 state->ctl = i9xx_plane_ctl(crtc_state, state);
13498         }
13499
13500         return 0;
13501 }
13502
13503 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13504                                     struct drm_crtc_state *old_crtc_state)
13505 {
13506         struct drm_device *dev = crtc->dev;
13507         struct drm_i915_private *dev_priv = to_i915(dev);
13508         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13509         struct intel_crtc_state *intel_cstate =
13510                 to_intel_crtc_state(crtc->state);
13511         struct intel_crtc_state *old_intel_cstate =
13512                 to_intel_crtc_state(old_crtc_state);
13513         struct intel_atomic_state *old_intel_state =
13514                 to_intel_atomic_state(old_crtc_state->state);
13515         bool modeset = needs_modeset(crtc->state);
13516
13517         if (!modeset &&
13518             (intel_cstate->base.color_mgmt_changed ||
13519              intel_cstate->update_pipe)) {
13520                 intel_color_set_csc(crtc->state);
13521                 intel_color_load_luts(crtc->state);
13522         }
13523
13524         /* Perform vblank evasion around commit operation */
13525         intel_pipe_update_start(intel_crtc);
13526
13527         if (modeset)
13528                 goto out;
13529
13530         if (intel_cstate->update_pipe)
13531                 intel_update_pipe_config(intel_crtc, old_intel_cstate);
13532         else if (INTEL_GEN(dev_priv) >= 9)
13533                 skl_detach_scalers(intel_crtc);
13534
13535 out:
13536         if (dev_priv->display.atomic_update_watermarks)
13537                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13538                                                            intel_cstate);
13539 }
13540
13541 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13542                                      struct drm_crtc_state *old_crtc_state)
13543 {
13544         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13545
13546         intel_pipe_update_end(intel_crtc, NULL);
13547 }
13548
13549 /**
13550  * intel_plane_destroy - destroy a plane
13551  * @plane: plane to destroy
13552  *
13553  * Common destruction function for all types of planes (primary, cursor,
13554  * sprite).
13555  */
13556 void intel_plane_destroy(struct drm_plane *plane)
13557 {
13558         drm_plane_cleanup(plane);
13559         kfree(to_intel_plane(plane));
13560 }
13561
13562 const struct drm_plane_funcs intel_plane_funcs = {
13563         .update_plane = drm_atomic_helper_update_plane,
13564         .disable_plane = drm_atomic_helper_disable_plane,
13565         .destroy = intel_plane_destroy,
13566         .set_property = drm_atomic_helper_plane_set_property,
13567         .atomic_get_property = intel_plane_atomic_get_property,
13568         .atomic_set_property = intel_plane_atomic_set_property,
13569         .atomic_duplicate_state = intel_plane_duplicate_state,
13570         .atomic_destroy_state = intel_plane_destroy_state,
13571 };
13572
13573 static int
13574 intel_legacy_cursor_update(struct drm_plane *plane,
13575                            struct drm_crtc *crtc,
13576                            struct drm_framebuffer *fb,
13577                            int crtc_x, int crtc_y,
13578                            unsigned int crtc_w, unsigned int crtc_h,
13579                            uint32_t src_x, uint32_t src_y,
13580                            uint32_t src_w, uint32_t src_h,
13581                            struct drm_modeset_acquire_ctx *ctx)
13582 {
13583         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13584         int ret;
13585         struct drm_plane_state *old_plane_state, *new_plane_state;
13586         struct intel_plane *intel_plane = to_intel_plane(plane);
13587         struct drm_framebuffer *old_fb;
13588         struct drm_crtc_state *crtc_state = crtc->state;
13589         struct i915_vma *old_vma;
13590
13591         /*
13592          * When crtc is inactive or there is a modeset pending,
13593          * wait for it to complete in the slowpath
13594          */
13595         if (!crtc_state->active || needs_modeset(crtc_state) ||
13596             to_intel_crtc_state(crtc_state)->update_pipe)
13597                 goto slow;
13598
13599         old_plane_state = plane->state;
13600
13601         /*
13602          * If any parameters change that may affect watermarks,
13603          * take the slowpath. Only changing fb or position should be
13604          * in the fastpath.
13605          */
13606         if (old_plane_state->crtc != crtc ||
13607             old_plane_state->src_w != src_w ||
13608             old_plane_state->src_h != src_h ||
13609             old_plane_state->crtc_w != crtc_w ||
13610             old_plane_state->crtc_h != crtc_h ||
13611             !old_plane_state->fb != !fb)
13612                 goto slow;
13613
13614         new_plane_state = intel_plane_duplicate_state(plane);
13615         if (!new_plane_state)
13616                 return -ENOMEM;
13617
13618         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13619
13620         new_plane_state->src_x = src_x;
13621         new_plane_state->src_y = src_y;
13622         new_plane_state->src_w = src_w;
13623         new_plane_state->src_h = src_h;
13624         new_plane_state->crtc_x = crtc_x;
13625         new_plane_state->crtc_y = crtc_y;
13626         new_plane_state->crtc_w = crtc_w;
13627         new_plane_state->crtc_h = crtc_h;
13628
13629         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13630                                                   to_intel_plane_state(new_plane_state));
13631         if (ret)
13632                 goto out_free;
13633
13634         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13635         if (ret)
13636                 goto out_free;
13637
13638         if (INTEL_INFO(dev_priv)->cursor_needs_physical) {
13639                 int align = intel_cursor_alignment(dev_priv);
13640
13641                 ret = i915_gem_object_attach_phys(intel_fb_obj(fb), align);
13642                 if (ret) {
13643                         DRM_DEBUG_KMS("failed to attach phys object\n");
13644                         goto out_unlock;
13645                 }
13646         } else {
13647                 struct i915_vma *vma;
13648
13649                 vma = intel_pin_and_fence_fb_obj(fb, new_plane_state->rotation);
13650                 if (IS_ERR(vma)) {
13651                         DRM_DEBUG_KMS("failed to pin object\n");
13652
13653                         ret = PTR_ERR(vma);
13654                         goto out_unlock;
13655                 }
13656
13657                 to_intel_plane_state(new_plane_state)->vma = vma;
13658         }
13659
13660         old_fb = old_plane_state->fb;
13661         old_vma = to_intel_plane_state(old_plane_state)->vma;
13662
13663         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13664                           intel_plane->frontbuffer_bit);
13665
13666         /* Swap plane state */
13667         new_plane_state->fence = old_plane_state->fence;
13668         *to_intel_plane_state(old_plane_state) = *to_intel_plane_state(new_plane_state);
13669         new_plane_state->fence = NULL;
13670         new_plane_state->fb = old_fb;
13671         to_intel_plane_state(new_plane_state)->vma = old_vma;
13672
13673         if (plane->state->visible) {
13674                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13675                 intel_plane->update_plane(intel_plane,
13676                                           to_intel_crtc_state(crtc->state),
13677                                           to_intel_plane_state(plane->state));
13678         } else {
13679                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13680                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13681         }
13682
13683         intel_cleanup_plane_fb(plane, new_plane_state);
13684
13685 out_unlock:
13686         mutex_unlock(&dev_priv->drm.struct_mutex);
13687 out_free:
13688         intel_plane_destroy_state(plane, new_plane_state);
13689         return ret;
13690
13691 slow:
13692         return drm_atomic_helper_update_plane(plane, crtc, fb,
13693                                               crtc_x, crtc_y, crtc_w, crtc_h,
13694                                               src_x, src_y, src_w, src_h, ctx);
13695 }
13696
13697 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13698         .update_plane = intel_legacy_cursor_update,
13699         .disable_plane = drm_atomic_helper_disable_plane,
13700         .destroy = intel_plane_destroy,
13701         .set_property = drm_atomic_helper_plane_set_property,
13702         .atomic_get_property = intel_plane_atomic_get_property,
13703         .atomic_set_property = intel_plane_atomic_set_property,
13704         .atomic_duplicate_state = intel_plane_duplicate_state,
13705         .atomic_destroy_state = intel_plane_destroy_state,
13706 };
13707
13708 static struct intel_plane *
13709 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13710 {
13711         struct intel_plane *primary = NULL;
13712         struct intel_plane_state *state = NULL;
13713         const uint32_t *intel_primary_formats;
13714         unsigned int supported_rotations;
13715         unsigned int num_formats;
13716         int ret;
13717
13718         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13719         if (!primary) {
13720                 ret = -ENOMEM;
13721                 goto fail;
13722         }
13723
13724         state = intel_create_plane_state(&primary->base);
13725         if (!state) {
13726                 ret = -ENOMEM;
13727                 goto fail;
13728         }
13729
13730         primary->base.state = &state->base;
13731
13732         primary->can_scale = false;
13733         primary->max_downscale = 1;
13734         if (INTEL_GEN(dev_priv) >= 9) {
13735                 primary->can_scale = true;
13736                 state->scaler_id = -1;
13737         }
13738         primary->pipe = pipe;
13739         /*
13740          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13741          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13742          */
13743         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13744                 primary->plane = (enum plane) !pipe;
13745         else
13746                 primary->plane = (enum plane) pipe;
13747         primary->id = PLANE_PRIMARY;
13748         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13749         primary->check_plane = intel_check_primary_plane;
13750
13751         if (INTEL_GEN(dev_priv) >= 9) {
13752                 intel_primary_formats = skl_primary_formats;
13753                 num_formats = ARRAY_SIZE(skl_primary_formats);
13754
13755                 primary->update_plane = skylake_update_primary_plane;
13756                 primary->disable_plane = skylake_disable_primary_plane;
13757         } else if (INTEL_GEN(dev_priv) >= 4) {
13758                 intel_primary_formats = i965_primary_formats;
13759                 num_formats = ARRAY_SIZE(i965_primary_formats);
13760
13761                 primary->update_plane = i9xx_update_primary_plane;
13762                 primary->disable_plane = i9xx_disable_primary_plane;
13763         } else {
13764                 intel_primary_formats = i8xx_primary_formats;
13765                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13766
13767                 primary->update_plane = i9xx_update_primary_plane;
13768                 primary->disable_plane = i9xx_disable_primary_plane;
13769         }
13770
13771         if (INTEL_GEN(dev_priv) >= 9)
13772                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13773                                                0, &intel_plane_funcs,
13774                                                intel_primary_formats, num_formats,
13775                                                DRM_PLANE_TYPE_PRIMARY,
13776                                                "plane 1%c", pipe_name(pipe));
13777         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13778                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13779                                                0, &intel_plane_funcs,
13780                                                intel_primary_formats, num_formats,
13781                                                DRM_PLANE_TYPE_PRIMARY,
13782                                                "primary %c", pipe_name(pipe));
13783         else
13784                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13785                                                0, &intel_plane_funcs,
13786                                                intel_primary_formats, num_formats,
13787                                                DRM_PLANE_TYPE_PRIMARY,
13788                                                "plane %c", plane_name(primary->plane));
13789         if (ret)
13790                 goto fail;
13791
13792         if (INTEL_GEN(dev_priv) >= 9) {
13793                 supported_rotations =
13794                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13795                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13796         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13797                 supported_rotations =
13798                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13799                         DRM_MODE_REFLECT_X;
13800         } else if (INTEL_GEN(dev_priv) >= 4) {
13801                 supported_rotations =
13802                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13803         } else {
13804                 supported_rotations = DRM_MODE_ROTATE_0;
13805         }
13806
13807         if (INTEL_GEN(dev_priv) >= 4)
13808                 drm_plane_create_rotation_property(&primary->base,
13809                                                    DRM_MODE_ROTATE_0,
13810                                                    supported_rotations);
13811
13812         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13813
13814         return primary;
13815
13816 fail:
13817         kfree(state);
13818         kfree(primary);
13819
13820         return ERR_PTR(ret);
13821 }
13822
13823 static struct intel_plane *
13824 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13825                           enum pipe pipe)
13826 {
13827         struct intel_plane *cursor = NULL;
13828         struct intel_plane_state *state = NULL;
13829         int ret;
13830
13831         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13832         if (!cursor) {
13833                 ret = -ENOMEM;
13834                 goto fail;
13835         }
13836
13837         state = intel_create_plane_state(&cursor->base);
13838         if (!state) {
13839                 ret = -ENOMEM;
13840                 goto fail;
13841         }
13842
13843         cursor->base.state = &state->base;
13844
13845         cursor->can_scale = false;
13846         cursor->max_downscale = 1;
13847         cursor->pipe = pipe;
13848         cursor->plane = pipe;
13849         cursor->id = PLANE_CURSOR;
13850         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13851
13852         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13853                 cursor->update_plane = i845_update_cursor;
13854                 cursor->disable_plane = i845_disable_cursor;
13855                 cursor->check_plane = i845_check_cursor;
13856         } else {
13857                 cursor->update_plane = i9xx_update_cursor;
13858                 cursor->disable_plane = i9xx_disable_cursor;
13859                 cursor->check_plane = i9xx_check_cursor;
13860         }
13861
13862         cursor->cursor.base = ~0;
13863         cursor->cursor.cntl = ~0;
13864
13865         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13866                 cursor->cursor.size = ~0;
13867
13868         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13869                                        0, &intel_cursor_plane_funcs,
13870                                        intel_cursor_formats,
13871                                        ARRAY_SIZE(intel_cursor_formats),
13872                                        DRM_PLANE_TYPE_CURSOR,
13873                                        "cursor %c", pipe_name(pipe));
13874         if (ret)
13875                 goto fail;
13876
13877         if (INTEL_GEN(dev_priv) >= 4)
13878                 drm_plane_create_rotation_property(&cursor->base,
13879                                                    DRM_MODE_ROTATE_0,
13880                                                    DRM_MODE_ROTATE_0 |
13881                                                    DRM_MODE_ROTATE_180);
13882
13883         if (INTEL_GEN(dev_priv) >= 9)
13884                 state->scaler_id = -1;
13885
13886         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13887
13888         return cursor;
13889
13890 fail:
13891         kfree(state);
13892         kfree(cursor);
13893
13894         return ERR_PTR(ret);
13895 }
13896
13897 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13898                                     struct intel_crtc_state *crtc_state)
13899 {
13900         struct intel_crtc_scaler_state *scaler_state =
13901                 &crtc_state->scaler_state;
13902         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13903         int i;
13904
13905         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13906         if (!crtc->num_scalers)
13907                 return;
13908
13909         for (i = 0; i < crtc->num_scalers; i++) {
13910                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13911
13912                 scaler->in_use = 0;
13913                 scaler->mode = PS_SCALER_MODE_DYN;
13914         }
13915
13916         scaler_state->scaler_id = -1;
13917 }
13918
13919 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13920 {
13921         struct intel_crtc *intel_crtc;
13922         struct intel_crtc_state *crtc_state = NULL;
13923         struct intel_plane *primary = NULL;
13924         struct intel_plane *cursor = NULL;
13925         int sprite, ret;
13926
13927         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13928         if (!intel_crtc)
13929                 return -ENOMEM;
13930
13931         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13932         if (!crtc_state) {
13933                 ret = -ENOMEM;
13934                 goto fail;
13935         }
13936         intel_crtc->config = crtc_state;
13937         intel_crtc->base.state = &crtc_state->base;
13938         crtc_state->base.crtc = &intel_crtc->base;
13939
13940         primary = intel_primary_plane_create(dev_priv, pipe);
13941         if (IS_ERR(primary)) {
13942                 ret = PTR_ERR(primary);
13943                 goto fail;
13944         }
13945         intel_crtc->plane_ids_mask |= BIT(primary->id);
13946
13947         for_each_sprite(dev_priv, pipe, sprite) {
13948                 struct intel_plane *plane;
13949
13950                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13951                 if (IS_ERR(plane)) {
13952                         ret = PTR_ERR(plane);
13953                         goto fail;
13954                 }
13955                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13956         }
13957
13958         cursor = intel_cursor_plane_create(dev_priv, pipe);
13959         if (IS_ERR(cursor)) {
13960                 ret = PTR_ERR(cursor);
13961                 goto fail;
13962         }
13963         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13964
13965         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13966                                         &primary->base, &cursor->base,
13967                                         &intel_crtc_funcs,
13968                                         "pipe %c", pipe_name(pipe));
13969         if (ret)
13970                 goto fail;
13971
13972         intel_crtc->pipe = pipe;
13973         intel_crtc->plane = primary->plane;
13974
13975         /* initialize shared scalers */
13976         intel_crtc_init_scalers(intel_crtc, crtc_state);
13977
13978         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13979                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13980         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = intel_crtc;
13981         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
13982
13983         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13984
13985         intel_color_init(&intel_crtc->base);
13986
13987         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13988
13989         return 0;
13990
13991 fail:
13992         /*
13993          * drm_mode_config_cleanup() will free up any
13994          * crtcs/planes already initialized.
13995          */
13996         kfree(crtc_state);
13997         kfree(intel_crtc);
13998
13999         return ret;
14000 }
14001
14002 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14003 {
14004         struct drm_device *dev = connector->base.dev;
14005
14006         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14007
14008         if (!connector->base.state->crtc)
14009                 return INVALID_PIPE;
14010
14011         return to_intel_crtc(connector->base.state->crtc)->pipe;
14012 }
14013
14014 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14015                                 struct drm_file *file)
14016 {
14017         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14018         struct drm_crtc *drmmode_crtc;
14019         struct intel_crtc *crtc;
14020
14021         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14022         if (!drmmode_crtc)
14023                 return -ENOENT;
14024
14025         crtc = to_intel_crtc(drmmode_crtc);
14026         pipe_from_crtc_id->pipe = crtc->pipe;
14027
14028         return 0;
14029 }
14030
14031 static int intel_encoder_clones(struct intel_encoder *encoder)
14032 {
14033         struct drm_device *dev = encoder->base.dev;
14034         struct intel_encoder *source_encoder;
14035         int index_mask = 0;
14036         int entry = 0;
14037
14038         for_each_intel_encoder(dev, source_encoder) {
14039                 if (encoders_cloneable(encoder, source_encoder))
14040                         index_mask |= (1 << entry);
14041
14042                 entry++;
14043         }
14044
14045         return index_mask;
14046 }
14047
14048 static bool has_edp_a(struct drm_i915_private *dev_priv)
14049 {
14050         if (!IS_MOBILE(dev_priv))
14051                 return false;
14052
14053         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14054                 return false;
14055
14056         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14057                 return false;
14058
14059         return true;
14060 }
14061
14062 static bool intel_crt_present(struct drm_i915_private *dev_priv)
14063 {
14064         if (INTEL_GEN(dev_priv) >= 9)
14065                 return false;
14066
14067         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14068                 return false;
14069
14070         if (IS_CHERRYVIEW(dev_priv))
14071                 return false;
14072
14073         if (HAS_PCH_LPT_H(dev_priv) &&
14074             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14075                 return false;
14076
14077         /* DDI E can't be used if DDI A requires 4 lanes */
14078         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14079                 return false;
14080
14081         if (!dev_priv->vbt.int_crt_support)
14082                 return false;
14083
14084         return true;
14085 }
14086
14087 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14088 {
14089         int pps_num;
14090         int pps_idx;
14091
14092         if (HAS_DDI(dev_priv))
14093                 return;
14094         /*
14095          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14096          * everywhere where registers can be write protected.
14097          */
14098         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14099                 pps_num = 2;
14100         else
14101                 pps_num = 1;
14102
14103         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14104                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14105
14106                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14107                 I915_WRITE(PP_CONTROL(pps_idx), val);
14108         }
14109 }
14110
14111 static void intel_pps_init(struct drm_i915_private *dev_priv)
14112 {
14113         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14114                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14115         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14116                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14117         else
14118                 dev_priv->pps_mmio_base = PPS_BASE;
14119
14120         intel_pps_unlock_regs_wa(dev_priv);
14121 }
14122
14123 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14124 {
14125         struct intel_encoder *encoder;
14126         bool dpd_is_edp = false;
14127
14128         intel_pps_init(dev_priv);
14129
14130         /*
14131          * intel_edp_init_connector() depends on this completing first, to
14132          * prevent the registeration of both eDP and LVDS and the incorrect
14133          * sharing of the PPS.
14134          */
14135         intel_lvds_init(dev_priv);
14136
14137         if (intel_crt_present(dev_priv))
14138                 intel_crt_init(dev_priv);
14139
14140         if (IS_GEN9_LP(dev_priv)) {
14141                 /*
14142                  * FIXME: Broxton doesn't support port detection via the
14143                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14144                  * detect the ports.
14145                  */
14146                 intel_ddi_init(dev_priv, PORT_A);
14147                 intel_ddi_init(dev_priv, PORT_B);
14148                 intel_ddi_init(dev_priv, PORT_C);
14149
14150                 intel_dsi_init(dev_priv);
14151         } else if (HAS_DDI(dev_priv)) {
14152                 int found;
14153
14154                 /*
14155                  * Haswell uses DDI functions to detect digital outputs.
14156                  * On SKL pre-D0 the strap isn't connected, so we assume
14157                  * it's there.
14158                  */
14159                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14160                 /* WaIgnoreDDIAStrap: skl */
14161                 if (found || IS_GEN9_BC(dev_priv))
14162                         intel_ddi_init(dev_priv, PORT_A);
14163
14164                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14165                  * register */
14166                 found = I915_READ(SFUSE_STRAP);
14167
14168                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14169                         intel_ddi_init(dev_priv, PORT_B);
14170                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14171                         intel_ddi_init(dev_priv, PORT_C);
14172                 if (found & SFUSE_STRAP_DDID_DETECTED)
14173                         intel_ddi_init(dev_priv, PORT_D);
14174                 /*
14175                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14176                  */
14177                 if (IS_GEN9_BC(dev_priv) &&
14178                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14179                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14180                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14181                         intel_ddi_init(dev_priv, PORT_E);
14182
14183         } else if (HAS_PCH_SPLIT(dev_priv)) {
14184                 int found;
14185                 dpd_is_edp = intel_dp_is_edp(dev_priv, PORT_D);
14186
14187                 if (has_edp_a(dev_priv))
14188                         intel_dp_init(dev_priv, DP_A, PORT_A);
14189
14190                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14191                         /* PCH SDVOB multiplex with HDMIB */
14192                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14193                         if (!found)
14194                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14195                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14196                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14197                 }
14198
14199                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14200                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14201
14202                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14203                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14204
14205                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14206                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14207
14208                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14209                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14210         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14211                 bool has_edp, has_port;
14212
14213                 /*
14214                  * The DP_DETECTED bit is the latched state of the DDC
14215                  * SDA pin at boot. However since eDP doesn't require DDC
14216                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14217                  * eDP ports may have been muxed to an alternate function.
14218                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14219                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14220                  * detect eDP ports.
14221                  *
14222                  * Sadly the straps seem to be missing sometimes even for HDMI
14223                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14224                  * and VBT for the presence of the port. Additionally we can't
14225                  * trust the port type the VBT declares as we've seen at least
14226                  * HDMI ports that the VBT claim are DP or eDP.
14227                  */
14228                 has_edp = intel_dp_is_edp(dev_priv, PORT_B);
14229                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14230                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14231                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14232                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14233                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14234
14235                 has_edp = intel_dp_is_edp(dev_priv, PORT_C);
14236                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14237                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14238                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14239                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14240                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14241
14242                 if (IS_CHERRYVIEW(dev_priv)) {
14243                         /*
14244                          * eDP not supported on port D,
14245                          * so no need to worry about it
14246                          */
14247                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14248                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14249                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14250                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14251                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14252                 }
14253
14254                 intel_dsi_init(dev_priv);
14255         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14256                 bool found = false;
14257
14258                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14259                         DRM_DEBUG_KMS("probing SDVOB\n");
14260                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14261                         if (!found && IS_G4X(dev_priv)) {
14262                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14263                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14264                         }
14265
14266                         if (!found && IS_G4X(dev_priv))
14267                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14268                 }
14269
14270                 /* Before G4X SDVOC doesn't have its own detect register */
14271
14272                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14273                         DRM_DEBUG_KMS("probing SDVOC\n");
14274                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14275                 }
14276
14277                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14278
14279                         if (IS_G4X(dev_priv)) {
14280                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14281                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14282                         }
14283                         if (IS_G4X(dev_priv))
14284                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14285                 }
14286
14287                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14288                         intel_dp_init(dev_priv, DP_D, PORT_D);
14289         } else if (IS_GEN2(dev_priv))
14290                 intel_dvo_init(dev_priv);
14291
14292         if (SUPPORTS_TV(dev_priv))
14293                 intel_tv_init(dev_priv);
14294
14295         intel_psr_init(dev_priv);
14296
14297         for_each_intel_encoder(&dev_priv->drm, encoder) {
14298                 encoder->base.possible_crtcs = encoder->crtc_mask;
14299                 encoder->base.possible_clones =
14300                         intel_encoder_clones(encoder);
14301         }
14302
14303         intel_init_pch_refclk(dev_priv);
14304
14305         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14306 }
14307
14308 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14309 {
14310         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14311
14312         drm_framebuffer_cleanup(fb);
14313
14314         i915_gem_object_lock(intel_fb->obj);
14315         WARN_ON(!intel_fb->obj->framebuffer_references--);
14316         i915_gem_object_unlock(intel_fb->obj);
14317
14318         i915_gem_object_put(intel_fb->obj);
14319
14320         kfree(intel_fb);
14321 }
14322
14323 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14324                                                 struct drm_file *file,
14325                                                 unsigned int *handle)
14326 {
14327         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14328         struct drm_i915_gem_object *obj = intel_fb->obj;
14329
14330         if (obj->userptr.mm) {
14331                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14332                 return -EINVAL;
14333         }
14334
14335         return drm_gem_handle_create(file, &obj->base, handle);
14336 }
14337
14338 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14339                                         struct drm_file *file,
14340                                         unsigned flags, unsigned color,
14341                                         struct drm_clip_rect *clips,
14342                                         unsigned num_clips)
14343 {
14344         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14345
14346         i915_gem_object_flush_if_display(obj);
14347         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14348
14349         return 0;
14350 }
14351
14352 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14353         .destroy = intel_user_framebuffer_destroy,
14354         .create_handle = intel_user_framebuffer_create_handle,
14355         .dirty = intel_user_framebuffer_dirty,
14356 };
14357
14358 static
14359 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14360                          uint64_t fb_modifier, uint32_t pixel_format)
14361 {
14362         u32 gen = INTEL_GEN(dev_priv);
14363
14364         if (gen >= 9) {
14365                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14366
14367                 /* "The stride in bytes must not exceed the of the size of 8K
14368                  *  pixels and 32K bytes."
14369                  */
14370                 return min(8192 * cpp, 32768);
14371         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
14372                 return 32*1024;
14373         } else if (gen >= 4) {
14374                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14375                         return 16*1024;
14376                 else
14377                         return 32*1024;
14378         } else if (gen >= 3) {
14379                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14380                         return 8*1024;
14381                 else
14382                         return 16*1024;
14383         } else {
14384                 /* XXX DSPC is limited to 4k tiled */
14385                 return 8*1024;
14386         }
14387 }
14388
14389 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14390                                   struct drm_i915_gem_object *obj,
14391                                   struct drm_mode_fb_cmd2 *mode_cmd)
14392 {
14393         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14394         struct drm_format_name_buf format_name;
14395         u32 pitch_limit, stride_alignment;
14396         unsigned int tiling, stride;
14397         int ret = -EINVAL;
14398
14399         i915_gem_object_lock(obj);
14400         obj->framebuffer_references++;
14401         tiling = i915_gem_object_get_tiling(obj);
14402         stride = i915_gem_object_get_stride(obj);
14403         i915_gem_object_unlock(obj);
14404
14405         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14406                 /*
14407                  * If there's a fence, enforce that
14408                  * the fb modifier and tiling mode match.
14409                  */
14410                 if (tiling != I915_TILING_NONE &&
14411                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14412                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14413                         goto err;
14414                 }
14415         } else {
14416                 if (tiling == I915_TILING_X) {
14417                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14418                 } else if (tiling == I915_TILING_Y) {
14419                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14420                         goto err;
14421                 }
14422         }
14423
14424         /* Passed in modifier sanity checking. */
14425         switch (mode_cmd->modifier[0]) {
14426         case I915_FORMAT_MOD_Y_TILED:
14427         case I915_FORMAT_MOD_Yf_TILED:
14428                 if (INTEL_GEN(dev_priv) < 9) {
14429                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14430                                       mode_cmd->modifier[0]);
14431                         goto err;
14432                 }
14433         case DRM_FORMAT_MOD_LINEAR:
14434         case I915_FORMAT_MOD_X_TILED:
14435                 break;
14436         default:
14437                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14438                               mode_cmd->modifier[0]);
14439                 goto err;
14440         }
14441
14442         /*
14443          * gen2/3 display engine uses the fence if present,
14444          * so the tiling mode must match the fb modifier exactly.
14445          */
14446         if (INTEL_INFO(dev_priv)->gen < 4 &&
14447             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14448                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14449                 goto err;
14450         }
14451
14452         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14453                                            mode_cmd->pixel_format);
14454         if (mode_cmd->pitches[0] > pitch_limit) {
14455                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14456                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14457                               "tiled" : "linear",
14458                               mode_cmd->pitches[0], pitch_limit);
14459                 goto err;
14460         }
14461
14462         /*
14463          * If there's a fence, enforce that
14464          * the fb pitch and fence stride match.
14465          */
14466         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14467                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14468                               mode_cmd->pitches[0], stride);
14469                 goto err;
14470         }
14471
14472         /* Reject formats not supported by any plane early. */
14473         switch (mode_cmd->pixel_format) {
14474         case DRM_FORMAT_C8:
14475         case DRM_FORMAT_RGB565:
14476         case DRM_FORMAT_XRGB8888:
14477         case DRM_FORMAT_ARGB8888:
14478                 break;
14479         case DRM_FORMAT_XRGB1555:
14480                 if (INTEL_GEN(dev_priv) > 3) {
14481                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14482                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14483                         goto err;
14484                 }
14485                 break;
14486         case DRM_FORMAT_ABGR8888:
14487                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14488                     INTEL_GEN(dev_priv) < 9) {
14489                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14490                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14491                         goto err;
14492                 }
14493                 break;
14494         case DRM_FORMAT_XBGR8888:
14495         case DRM_FORMAT_XRGB2101010:
14496         case DRM_FORMAT_XBGR2101010:
14497                 if (INTEL_GEN(dev_priv) < 4) {
14498                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14499                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14500                         goto err;
14501                 }
14502                 break;
14503         case DRM_FORMAT_ABGR2101010:
14504                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
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_YUYV:
14511         case DRM_FORMAT_UYVY:
14512         case DRM_FORMAT_YVYU:
14513         case DRM_FORMAT_VYUY:
14514                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14515                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14516                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14517                         goto err;
14518                 }
14519                 break;
14520         default:
14521                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14522                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14523                 goto err;
14524         }
14525
14526         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14527         if (mode_cmd->offsets[0] != 0)
14528                 goto err;
14529
14530         drm_helper_mode_fill_fb_struct(&dev_priv->drm,
14531                                        &intel_fb->base, mode_cmd);
14532
14533         stride_alignment = intel_fb_stride_alignment(&intel_fb->base, 0);
14534         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14535                 DRM_DEBUG_KMS("pitch (%d) must be at least %u byte aligned\n",
14536                               mode_cmd->pitches[0], stride_alignment);
14537                 goto err;
14538         }
14539
14540         intel_fb->obj = obj;
14541
14542         ret = intel_fill_fb_info(dev_priv, &intel_fb->base);
14543         if (ret)
14544                 goto err;
14545
14546         ret = drm_framebuffer_init(obj->base.dev,
14547                                    &intel_fb->base,
14548                                    &intel_fb_funcs);
14549         if (ret) {
14550                 DRM_ERROR("framebuffer init failed %d\n", ret);
14551                 goto err;
14552         }
14553
14554         return 0;
14555
14556 err:
14557         i915_gem_object_lock(obj);
14558         obj->framebuffer_references--;
14559         i915_gem_object_unlock(obj);
14560         return ret;
14561 }
14562
14563 static struct drm_framebuffer *
14564 intel_user_framebuffer_create(struct drm_device *dev,
14565                               struct drm_file *filp,
14566                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14567 {
14568         struct drm_framebuffer *fb;
14569         struct drm_i915_gem_object *obj;
14570         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14571
14572         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14573         if (!obj)
14574                 return ERR_PTR(-ENOENT);
14575
14576         fb = intel_framebuffer_create(obj, &mode_cmd);
14577         if (IS_ERR(fb))
14578                 i915_gem_object_put(obj);
14579
14580         return fb;
14581 }
14582
14583 static void intel_atomic_state_free(struct drm_atomic_state *state)
14584 {
14585         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14586
14587         drm_atomic_state_default_release(state);
14588
14589         i915_sw_fence_fini(&intel_state->commit_ready);
14590
14591         kfree(state);
14592 }
14593
14594 static const struct drm_mode_config_funcs intel_mode_funcs = {
14595         .fb_create = intel_user_framebuffer_create,
14596         .output_poll_changed = intel_fbdev_output_poll_changed,
14597         .atomic_check = intel_atomic_check,
14598         .atomic_commit = intel_atomic_commit,
14599         .atomic_state_alloc = intel_atomic_state_alloc,
14600         .atomic_state_clear = intel_atomic_state_clear,
14601         .atomic_state_free = intel_atomic_state_free,
14602 };
14603
14604 /**
14605  * intel_init_display_hooks - initialize the display modesetting hooks
14606  * @dev_priv: device private
14607  */
14608 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14609 {
14610         intel_init_cdclk_hooks(dev_priv);
14611
14612         if (INTEL_INFO(dev_priv)->gen >= 9) {
14613                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14614                 dev_priv->display.get_initial_plane_config =
14615                         skylake_get_initial_plane_config;
14616                 dev_priv->display.crtc_compute_clock =
14617                         haswell_crtc_compute_clock;
14618                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14619                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14620         } else if (HAS_DDI(dev_priv)) {
14621                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14622                 dev_priv->display.get_initial_plane_config =
14623                         ironlake_get_initial_plane_config;
14624                 dev_priv->display.crtc_compute_clock =
14625                         haswell_crtc_compute_clock;
14626                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14627                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14628         } else if (HAS_PCH_SPLIT(dev_priv)) {
14629                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14630                 dev_priv->display.get_initial_plane_config =
14631                         ironlake_get_initial_plane_config;
14632                 dev_priv->display.crtc_compute_clock =
14633                         ironlake_crtc_compute_clock;
14634                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14635                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14636         } else if (IS_CHERRYVIEW(dev_priv)) {
14637                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14638                 dev_priv->display.get_initial_plane_config =
14639                         i9xx_get_initial_plane_config;
14640                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14641                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14642                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14643         } else if (IS_VALLEYVIEW(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 = vlv_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_G4X(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 = g4x_crtc_compute_clock;
14655                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14656                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14657         } else if (IS_PINEVIEW(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 = pnv_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_GEN2(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 = i9xx_crtc_compute_clock;
14669                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14670                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14671         } else {
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 = i8xx_crtc_compute_clock;
14676                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14677                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14678         }
14679
14680         if (IS_GEN5(dev_priv)) {
14681                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14682         } else if (IS_GEN6(dev_priv)) {
14683                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14684         } else if (IS_IVYBRIDGE(dev_priv)) {
14685                 /* FIXME: detect B0+ stepping and use auto training */
14686                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14687         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14688                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14689         }
14690
14691         if (dev_priv->info.gen >= 9)
14692                 dev_priv->display.update_crtcs = skl_update_crtcs;
14693         else
14694                 dev_priv->display.update_crtcs = intel_update_crtcs;
14695
14696         switch (INTEL_INFO(dev_priv)->gen) {
14697         case 2:
14698                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14699                 break;
14700
14701         case 3:
14702                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14703                 break;
14704
14705         case 4:
14706         case 5:
14707                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14708                 break;
14709
14710         case 6:
14711                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14712                 break;
14713         case 7:
14714         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14715                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14716                 break;
14717         case 9:
14718                 /* Drop through - unsupported since execlist only. */
14719         default:
14720                 /* Default just returns -ENODEV to indicate unsupported */
14721                 dev_priv->display.queue_flip = intel_default_queue_flip;
14722         }
14723 }
14724
14725 /*
14726  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14727  */
14728 static void quirk_ssc_force_disable(struct drm_device *dev)
14729 {
14730         struct drm_i915_private *dev_priv = to_i915(dev);
14731         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14732         DRM_INFO("applying lvds SSC disable quirk\n");
14733 }
14734
14735 /*
14736  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14737  * brightness value
14738  */
14739 static void quirk_invert_brightness(struct drm_device *dev)
14740 {
14741         struct drm_i915_private *dev_priv = to_i915(dev);
14742         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14743         DRM_INFO("applying inverted panel brightness quirk\n");
14744 }
14745
14746 /* Some VBT's incorrectly indicate no backlight is present */
14747 static void quirk_backlight_present(struct drm_device *dev)
14748 {
14749         struct drm_i915_private *dev_priv = to_i915(dev);
14750         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14751         DRM_INFO("applying backlight present quirk\n");
14752 }
14753
14754 struct intel_quirk {
14755         int device;
14756         int subsystem_vendor;
14757         int subsystem_device;
14758         void (*hook)(struct drm_device *dev);
14759 };
14760
14761 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14762 struct intel_dmi_quirk {
14763         void (*hook)(struct drm_device *dev);
14764         const struct dmi_system_id (*dmi_id_list)[];
14765 };
14766
14767 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14768 {
14769         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14770         return 1;
14771 }
14772
14773 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14774         {
14775                 .dmi_id_list = &(const struct dmi_system_id[]) {
14776                         {
14777                                 .callback = intel_dmi_reverse_brightness,
14778                                 .ident = "NCR Corporation",
14779                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14780                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14781                                 },
14782                         },
14783                         { }  /* terminating entry */
14784                 },
14785                 .hook = quirk_invert_brightness,
14786         },
14787 };
14788
14789 static struct intel_quirk intel_quirks[] = {
14790         /* Lenovo U160 cannot use SSC on LVDS */
14791         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14792
14793         /* Sony Vaio Y cannot use SSC on LVDS */
14794         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14795
14796         /* Acer Aspire 5734Z must invert backlight brightness */
14797         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14798
14799         /* Acer/eMachines G725 */
14800         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14801
14802         /* Acer/eMachines e725 */
14803         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14804
14805         /* Acer/Packard Bell NCL20 */
14806         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14807
14808         /* Acer Aspire 4736Z */
14809         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14810
14811         /* Acer Aspire 5336 */
14812         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14813
14814         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14815         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14816
14817         /* Acer C720 Chromebook (Core i3 4005U) */
14818         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14819
14820         /* Apple Macbook 2,1 (Core 2 T7400) */
14821         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14822
14823         /* Apple Macbook 4,1 */
14824         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14825
14826         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14827         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14828
14829         /* HP Chromebook 14 (Celeron 2955U) */
14830         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14831
14832         /* Dell Chromebook 11 */
14833         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14834
14835         /* Dell Chromebook 11 (2015 version) */
14836         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14837 };
14838
14839 static void intel_init_quirks(struct drm_device *dev)
14840 {
14841         struct pci_dev *d = dev->pdev;
14842         int i;
14843
14844         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14845                 struct intel_quirk *q = &intel_quirks[i];
14846
14847                 if (d->device == q->device &&
14848                     (d->subsystem_vendor == q->subsystem_vendor ||
14849                      q->subsystem_vendor == PCI_ANY_ID) &&
14850                     (d->subsystem_device == q->subsystem_device ||
14851                      q->subsystem_device == PCI_ANY_ID))
14852                         q->hook(dev);
14853         }
14854         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14855                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14856                         intel_dmi_quirks[i].hook(dev);
14857         }
14858 }
14859
14860 /* Disable the VGA plane that we never use */
14861 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14862 {
14863         struct pci_dev *pdev = dev_priv->drm.pdev;
14864         u8 sr1;
14865         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14866
14867         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14868         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14869         outb(SR01, VGA_SR_INDEX);
14870         sr1 = inb(VGA_SR_DATA);
14871         outb(sr1 | 1<<5, VGA_SR_DATA);
14872         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14873         udelay(300);
14874
14875         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14876         POSTING_READ(vga_reg);
14877 }
14878
14879 void intel_modeset_init_hw(struct drm_device *dev)
14880 {
14881         struct drm_i915_private *dev_priv = to_i915(dev);
14882
14883         intel_update_cdclk(dev_priv);
14884         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14885
14886         intel_init_clock_gating(dev_priv);
14887 }
14888
14889 /*
14890  * Calculate what we think the watermarks should be for the state we've read
14891  * out of the hardware and then immediately program those watermarks so that
14892  * we ensure the hardware settings match our internal state.
14893  *
14894  * We can calculate what we think WM's should be by creating a duplicate of the
14895  * current state (which was constructed during hardware readout) and running it
14896  * through the atomic check code to calculate new watermark values in the
14897  * state object.
14898  */
14899 static void sanitize_watermarks(struct drm_device *dev)
14900 {
14901         struct drm_i915_private *dev_priv = to_i915(dev);
14902         struct drm_atomic_state *state;
14903         struct intel_atomic_state *intel_state;
14904         struct drm_crtc *crtc;
14905         struct drm_crtc_state *cstate;
14906         struct drm_modeset_acquire_ctx ctx;
14907         int ret;
14908         int i;
14909
14910         /* Only supported on platforms that use atomic watermark design */
14911         if (!dev_priv->display.optimize_watermarks)
14912                 return;
14913
14914         /*
14915          * We need to hold connection_mutex before calling duplicate_state so
14916          * that the connector loop is protected.
14917          */
14918         drm_modeset_acquire_init(&ctx, 0);
14919 retry:
14920         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14921         if (ret == -EDEADLK) {
14922                 drm_modeset_backoff(&ctx);
14923                 goto retry;
14924         } else if (WARN_ON(ret)) {
14925                 goto fail;
14926         }
14927
14928         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14929         if (WARN_ON(IS_ERR(state)))
14930                 goto fail;
14931
14932         intel_state = to_intel_atomic_state(state);
14933
14934         /*
14935          * Hardware readout is the only time we don't want to calculate
14936          * intermediate watermarks (since we don't trust the current
14937          * watermarks).
14938          */
14939         if (!HAS_GMCH_DISPLAY(dev_priv))
14940                 intel_state->skip_intermediate_wm = true;
14941
14942         ret = intel_atomic_check(dev, state);
14943         if (ret) {
14944                 /*
14945                  * If we fail here, it means that the hardware appears to be
14946                  * programmed in a way that shouldn't be possible, given our
14947                  * understanding of watermark requirements.  This might mean a
14948                  * mistake in the hardware readout code or a mistake in the
14949                  * watermark calculations for a given platform.  Raise a WARN
14950                  * so that this is noticeable.
14951                  *
14952                  * If this actually happens, we'll have to just leave the
14953                  * BIOS-programmed watermarks untouched and hope for the best.
14954                  */
14955                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14956                 goto put_state;
14957         }
14958
14959         /* Write calculated watermark values back */
14960         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14961                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14962
14963                 cs->wm.need_postvbl_update = true;
14964                 dev_priv->display.optimize_watermarks(intel_state, cs);
14965         }
14966
14967 put_state:
14968         drm_atomic_state_put(state);
14969 fail:
14970         drm_modeset_drop_locks(&ctx);
14971         drm_modeset_acquire_fini(&ctx);
14972 }
14973
14974 int intel_modeset_init(struct drm_device *dev)
14975 {
14976         struct drm_i915_private *dev_priv = to_i915(dev);
14977         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14978         enum pipe pipe;
14979         struct intel_crtc *crtc;
14980
14981         drm_mode_config_init(dev);
14982
14983         dev->mode_config.min_width = 0;
14984         dev->mode_config.min_height = 0;
14985
14986         dev->mode_config.preferred_depth = 24;
14987         dev->mode_config.prefer_shadow = 1;
14988
14989         dev->mode_config.allow_fb_modifiers = true;
14990
14991         dev->mode_config.funcs = &intel_mode_funcs;
14992
14993         init_llist_head(&dev_priv->atomic_helper.free_list);
14994         INIT_WORK(&dev_priv->atomic_helper.free_work,
14995                   intel_atomic_helper_free_state_worker);
14996
14997         intel_init_quirks(dev);
14998
14999         intel_init_pm(dev_priv);
15000
15001         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15002                 return 0;
15003
15004         /*
15005          * There may be no VBT; and if the BIOS enabled SSC we can
15006          * just keep using it to avoid unnecessary flicker.  Whereas if the
15007          * BIOS isn't using it, don't assume it will work even if the VBT
15008          * indicates as much.
15009          */
15010         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15011                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15012                                             DREF_SSC1_ENABLE);
15013
15014                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15015                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15016                                      bios_lvds_use_ssc ? "en" : "dis",
15017                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15018                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15019                 }
15020         }
15021
15022         if (IS_GEN2(dev_priv)) {
15023                 dev->mode_config.max_width = 2048;
15024                 dev->mode_config.max_height = 2048;
15025         } else if (IS_GEN3(dev_priv)) {
15026                 dev->mode_config.max_width = 4096;
15027                 dev->mode_config.max_height = 4096;
15028         } else {
15029                 dev->mode_config.max_width = 8192;
15030                 dev->mode_config.max_height = 8192;
15031         }
15032
15033         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15034                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15035                 dev->mode_config.cursor_height = 1023;
15036         } else if (IS_GEN2(dev_priv)) {
15037                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15038                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15039         } else {
15040                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15041                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15042         }
15043
15044         dev->mode_config.fb_base = ggtt->mappable_base;
15045
15046         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15047                       INTEL_INFO(dev_priv)->num_pipes,
15048                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15049
15050         for_each_pipe(dev_priv, pipe) {
15051                 int ret;
15052
15053                 ret = intel_crtc_init(dev_priv, pipe);
15054                 if (ret) {
15055                         drm_mode_config_cleanup(dev);
15056                         return ret;
15057                 }
15058         }
15059
15060         intel_shared_dpll_init(dev);
15061
15062         intel_update_czclk(dev_priv);
15063         intel_modeset_init_hw(dev);
15064
15065         if (dev_priv->max_cdclk_freq == 0)
15066                 intel_update_max_cdclk(dev_priv);
15067
15068         /* Just disable it once at startup */
15069         i915_disable_vga(dev_priv);
15070         intel_setup_outputs(dev_priv);
15071
15072         drm_modeset_lock_all(dev);
15073         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15074         drm_modeset_unlock_all(dev);
15075
15076         for_each_intel_crtc(dev, crtc) {
15077                 struct intel_initial_plane_config plane_config = {};
15078
15079                 if (!crtc->active)
15080                         continue;
15081
15082                 /*
15083                  * Note that reserving the BIOS fb up front prevents us
15084                  * from stuffing other stolen allocations like the ring
15085                  * on top.  This prevents some ugliness at boot time, and
15086                  * can even allow for smooth boot transitions if the BIOS
15087                  * fb is large enough for the active pipe configuration.
15088                  */
15089                 dev_priv->display.get_initial_plane_config(crtc,
15090                                                            &plane_config);
15091
15092                 /*
15093                  * If the fb is shared between multiple heads, we'll
15094                  * just get the first one.
15095                  */
15096                 intel_find_initial_plane_obj(crtc, &plane_config);
15097         }
15098
15099         /*
15100          * Make sure hardware watermarks really match the state we read out.
15101          * Note that we need to do this after reconstructing the BIOS fb's
15102          * since the watermark calculation done here will use pstate->fb.
15103          */
15104         if (!HAS_GMCH_DISPLAY(dev_priv))
15105                 sanitize_watermarks(dev);
15106
15107         return 0;
15108 }
15109
15110 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15111 {
15112         /* 640x480@60Hz, ~25175 kHz */
15113         struct dpll clock = {
15114                 .m1 = 18,
15115                 .m2 = 7,
15116                 .p1 = 13,
15117                 .p2 = 4,
15118                 .n = 2,
15119         };
15120         u32 dpll, fp;
15121         int i;
15122
15123         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15124
15125         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15126                       pipe_name(pipe), clock.vco, clock.dot);
15127
15128         fp = i9xx_dpll_compute_fp(&clock);
15129         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15130                 DPLL_VGA_MODE_DIS |
15131                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15132                 PLL_P2_DIVIDE_BY_4 |
15133                 PLL_REF_INPUT_DREFCLK |
15134                 DPLL_VCO_ENABLE;
15135
15136         I915_WRITE(FP0(pipe), fp);
15137         I915_WRITE(FP1(pipe), fp);
15138
15139         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15140         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15141         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15142         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15143         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15144         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15145         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15146
15147         /*
15148          * Apparently we need to have VGA mode enabled prior to changing
15149          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15150          * dividers, even though the register value does change.
15151          */
15152         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15153         I915_WRITE(DPLL(pipe), dpll);
15154
15155         /* Wait for the clocks to stabilize. */
15156         POSTING_READ(DPLL(pipe));
15157         udelay(150);
15158
15159         /* The pixel multiplier can only be updated once the
15160          * DPLL is enabled and the clocks are stable.
15161          *
15162          * So write it again.
15163          */
15164         I915_WRITE(DPLL(pipe), dpll);
15165
15166         /* We do this three times for luck */
15167         for (i = 0; i < 3 ; i++) {
15168                 I915_WRITE(DPLL(pipe), dpll);
15169                 POSTING_READ(DPLL(pipe));
15170                 udelay(150); /* wait for warmup */
15171         }
15172
15173         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15174         POSTING_READ(PIPECONF(pipe));
15175 }
15176
15177 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15178 {
15179         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15180                       pipe_name(pipe));
15181
15182         assert_plane_disabled(dev_priv, PLANE_A);
15183         assert_plane_disabled(dev_priv, PLANE_B);
15184
15185         I915_WRITE(PIPECONF(pipe), 0);
15186         POSTING_READ(PIPECONF(pipe));
15187
15188         if (wait_for(pipe_dsl_stopped(dev_priv, pipe), 100))
15189                 DRM_ERROR("pipe %c off wait timed out\n", pipe_name(pipe));
15190
15191         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15192         POSTING_READ(DPLL(pipe));
15193 }
15194
15195 static bool
15196 intel_check_plane_mapping(struct intel_crtc *crtc)
15197 {
15198         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15199         u32 val;
15200
15201         if (INTEL_INFO(dev_priv)->num_pipes == 1)
15202                 return true;
15203
15204         val = I915_READ(DSPCNTR(!crtc->plane));
15205
15206         if ((val & DISPLAY_PLANE_ENABLE) &&
15207             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15208                 return false;
15209
15210         return true;
15211 }
15212
15213 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15214 {
15215         struct drm_device *dev = crtc->base.dev;
15216         struct intel_encoder *encoder;
15217
15218         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15219                 return true;
15220
15221         return false;
15222 }
15223
15224 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15225 {
15226         struct drm_device *dev = encoder->base.dev;
15227         struct intel_connector *connector;
15228
15229         for_each_connector_on_encoder(dev, &encoder->base, connector)
15230                 return connector;
15231
15232         return NULL;
15233 }
15234
15235 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15236                               enum transcoder pch_transcoder)
15237 {
15238         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15239                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
15240 }
15241
15242 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15243                                 struct drm_modeset_acquire_ctx *ctx)
15244 {
15245         struct drm_device *dev = crtc->base.dev;
15246         struct drm_i915_private *dev_priv = to_i915(dev);
15247         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15248
15249         /* Clear any frame start delays used for debugging left by the BIOS */
15250         if (!transcoder_is_dsi(cpu_transcoder)) {
15251                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15252
15253                 I915_WRITE(reg,
15254                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15255         }
15256
15257         /* restore vblank interrupts to correct state */
15258         drm_crtc_vblank_reset(&crtc->base);
15259         if (crtc->active) {
15260                 struct intel_plane *plane;
15261
15262                 drm_crtc_vblank_on(&crtc->base);
15263
15264                 /* Disable everything but the primary plane */
15265                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15266                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15267                                 continue;
15268
15269                         trace_intel_disable_plane(&plane->base, crtc);
15270                         plane->disable_plane(plane, crtc);
15271                 }
15272         }
15273
15274         /* We need to sanitize the plane -> pipe mapping first because this will
15275          * disable the crtc (and hence change the state) if it is wrong. Note
15276          * that gen4+ has a fixed plane -> pipe mapping.  */
15277         if (INTEL_GEN(dev_priv) < 4 && !intel_check_plane_mapping(crtc)) {
15278                 bool plane;
15279
15280                 DRM_DEBUG_KMS("[CRTC:%d:%s] wrong plane connection detected!\n",
15281                               crtc->base.base.id, crtc->base.name);
15282
15283                 /* Pipe has the wrong plane attached and the plane is active.
15284                  * Temporarily change the plane mapping and disable everything
15285                  * ...  */
15286                 plane = crtc->plane;
15287                 crtc->base.primary->state->visible = true;
15288                 crtc->plane = !plane;
15289                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15290                 crtc->plane = plane;
15291         }
15292
15293         /* Adjust the state of the output pipe according to whether we
15294          * have active connectors/encoders. */
15295         if (crtc->active && !intel_crtc_has_encoders(crtc))
15296                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15297
15298         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15299                 /*
15300                  * We start out with underrun reporting disabled to avoid races.
15301                  * For correct bookkeeping mark this on active crtcs.
15302                  *
15303                  * Also on gmch platforms we dont have any hardware bits to
15304                  * disable the underrun reporting. Which means we need to start
15305                  * out with underrun reporting disabled also on inactive pipes,
15306                  * since otherwise we'll complain about the garbage we read when
15307                  * e.g. coming up after runtime pm.
15308                  *
15309                  * No protection against concurrent access is required - at
15310                  * worst a fifo underrun happens which also sets this to false.
15311                  */
15312                 crtc->cpu_fifo_underrun_disabled = true;
15313                 /*
15314                  * We track the PCH trancoder underrun reporting state
15315                  * within the crtc. With crtc for pipe A housing the underrun
15316                  * reporting state for PCH transcoder A, crtc for pipe B housing
15317                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15318                  * and marking underrun reporting as disabled for the non-existing
15319                  * PCH transcoders B and C would prevent enabling the south
15320                  * error interrupt (see cpt_can_enable_serr_int()).
15321                  */
15322                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
15323                         crtc->pch_fifo_underrun_disabled = true;
15324         }
15325 }
15326
15327 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15328 {
15329         struct intel_connector *connector;
15330
15331         /* We need to check both for a crtc link (meaning that the
15332          * encoder is active and trying to read from a pipe) and the
15333          * pipe itself being active. */
15334         bool has_active_crtc = encoder->base.crtc &&
15335                 to_intel_crtc(encoder->base.crtc)->active;
15336
15337         connector = intel_encoder_find_connector(encoder);
15338         if (connector && !has_active_crtc) {
15339                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15340                               encoder->base.base.id,
15341                               encoder->base.name);
15342
15343                 /* Connector is active, but has no active pipe. This is
15344                  * fallout from our resume register restoring. Disable
15345                  * the encoder manually again. */
15346                 if (encoder->base.crtc) {
15347                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15348
15349                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15350                                       encoder->base.base.id,
15351                                       encoder->base.name);
15352                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15353                         if (encoder->post_disable)
15354                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15355                 }
15356                 encoder->base.crtc = NULL;
15357
15358                 /* Inconsistent output/port/pipe state happens presumably due to
15359                  * a bug in one of the get_hw_state functions. Or someplace else
15360                  * in our code, like the register restore mess on resume. Clamp
15361                  * things to off as a safer default. */
15362
15363                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15364                 connector->base.encoder = NULL;
15365         }
15366         /* Enabled encoders without active connectors will be fixed in
15367          * the crtc fixup. */
15368 }
15369
15370 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15371 {
15372         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15373
15374         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15375                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15376                 i915_disable_vga(dev_priv);
15377         }
15378 }
15379
15380 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15381 {
15382         /* This function can be called both from intel_modeset_setup_hw_state or
15383          * at a very early point in our resume sequence, where the power well
15384          * structures are not yet restored. Since this function is at a very
15385          * paranoid "someone might have enabled VGA while we were not looking"
15386          * level, just check if the power well is enabled instead of trying to
15387          * follow the "don't touch the power well if we don't need it" policy
15388          * the rest of the driver uses. */
15389         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15390                 return;
15391
15392         i915_redisable_vga_power_on(dev_priv);
15393
15394         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15395 }
15396
15397 static bool primary_get_hw_state(struct intel_plane *plane)
15398 {
15399         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15400
15401         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15402 }
15403
15404 /* FIXME read out full plane state for all planes */
15405 static void readout_plane_state(struct intel_crtc *crtc)
15406 {
15407         struct intel_plane *primary = to_intel_plane(crtc->base.primary);
15408         bool visible;
15409
15410         visible = crtc->active && primary_get_hw_state(primary);
15411
15412         intel_set_plane_visible(to_intel_crtc_state(crtc->base.state),
15413                                 to_intel_plane_state(primary->base.state),
15414                                 visible);
15415 }
15416
15417 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15418 {
15419         struct drm_i915_private *dev_priv = to_i915(dev);
15420         enum pipe pipe;
15421         struct intel_crtc *crtc;
15422         struct intel_encoder *encoder;
15423         struct intel_connector *connector;
15424         struct drm_connector_list_iter conn_iter;
15425         int i;
15426
15427         dev_priv->active_crtcs = 0;
15428
15429         for_each_intel_crtc(dev, crtc) {
15430                 struct intel_crtc_state *crtc_state =
15431                         to_intel_crtc_state(crtc->base.state);
15432
15433                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15434                 memset(crtc_state, 0, sizeof(*crtc_state));
15435                 crtc_state->base.crtc = &crtc->base;
15436
15437                 crtc_state->base.active = crtc_state->base.enable =
15438                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15439
15440                 crtc->base.enabled = crtc_state->base.enable;
15441                 crtc->active = crtc_state->base.active;
15442
15443                 if (crtc_state->base.active)
15444                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15445
15446                 readout_plane_state(crtc);
15447
15448                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15449                               crtc->base.base.id, crtc->base.name,
15450                               enableddisabled(crtc_state->base.active));
15451         }
15452
15453         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15454                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15455
15456                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15457                                                   &pll->state.hw_state);
15458                 pll->state.crtc_mask = 0;
15459                 for_each_intel_crtc(dev, crtc) {
15460                         struct intel_crtc_state *crtc_state =
15461                                 to_intel_crtc_state(crtc->base.state);
15462
15463                         if (crtc_state->base.active &&
15464                             crtc_state->shared_dpll == pll)
15465                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15466                 }
15467                 pll->active_mask = pll->state.crtc_mask;
15468
15469                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15470                               pll->name, pll->state.crtc_mask, pll->on);
15471         }
15472
15473         for_each_intel_encoder(dev, encoder) {
15474                 pipe = 0;
15475
15476                 if (encoder->get_hw_state(encoder, &pipe)) {
15477                         struct intel_crtc_state *crtc_state;
15478
15479                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15480                         crtc_state = to_intel_crtc_state(crtc->base.state);
15481
15482                         encoder->base.crtc = &crtc->base;
15483                         crtc_state->output_types |= 1 << encoder->type;
15484                         encoder->get_config(encoder, crtc_state);
15485                 } else {
15486                         encoder->base.crtc = NULL;
15487                 }
15488
15489                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15490                               encoder->base.base.id, encoder->base.name,
15491                               enableddisabled(encoder->base.crtc),
15492                               pipe_name(pipe));
15493         }
15494
15495         drm_connector_list_iter_begin(dev, &conn_iter);
15496         for_each_intel_connector_iter(connector, &conn_iter) {
15497                 if (connector->get_hw_state(connector)) {
15498                         connector->base.dpms = DRM_MODE_DPMS_ON;
15499
15500                         encoder = connector->encoder;
15501                         connector->base.encoder = &encoder->base;
15502
15503                         if (encoder->base.crtc &&
15504                             encoder->base.crtc->state->active) {
15505                                 /*
15506                                  * This has to be done during hardware readout
15507                                  * because anything calling .crtc_disable may
15508                                  * rely on the connector_mask being accurate.
15509                                  */
15510                                 encoder->base.crtc->state->connector_mask |=
15511                                         1 << drm_connector_index(&connector->base);
15512                                 encoder->base.crtc->state->encoder_mask |=
15513                                         1 << drm_encoder_index(&encoder->base);
15514                         }
15515
15516                 } else {
15517                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15518                         connector->base.encoder = NULL;
15519                 }
15520                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15521                               connector->base.base.id, connector->base.name,
15522                               enableddisabled(connector->base.encoder));
15523         }
15524         drm_connector_list_iter_end(&conn_iter);
15525
15526         for_each_intel_crtc(dev, crtc) {
15527                 struct intel_crtc_state *crtc_state =
15528                         to_intel_crtc_state(crtc->base.state);
15529                 int pixclk = 0;
15530
15531                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15532                 if (crtc_state->base.active) {
15533                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15534                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15535                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15536
15537                         /*
15538                          * The initial mode needs to be set in order to keep
15539                          * the atomic core happy. It wants a valid mode if the
15540                          * crtc's enabled, so we do the above call.
15541                          *
15542                          * But we don't set all the derived state fully, hence
15543                          * set a flag to indicate that a full recalculation is
15544                          * needed on the next commit.
15545                          */
15546                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15547
15548                         intel_crtc_compute_pixel_rate(crtc_state);
15549
15550                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv) ||
15551                             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15552                                 pixclk = crtc_state->pixel_rate;
15553                         else
15554                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15555
15556                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15557                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
15558                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15559
15560                         drm_calc_timestamping_constants(&crtc->base,
15561                                                         &crtc_state->base.adjusted_mode);
15562                         update_scanline_offset(crtc);
15563                 }
15564
15565                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15566
15567                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15568         }
15569 }
15570
15571 static void
15572 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15573 {
15574         struct intel_encoder *encoder;
15575
15576         for_each_intel_encoder(&dev_priv->drm, encoder) {
15577                 u64 get_domains;
15578                 enum intel_display_power_domain domain;
15579
15580                 if (!encoder->get_power_domains)
15581                         continue;
15582
15583                 get_domains = encoder->get_power_domains(encoder);
15584                 for_each_power_domain(domain, get_domains)
15585                         intel_display_power_get(dev_priv, domain);
15586         }
15587 }
15588
15589 /* Scan out the current hw modeset state,
15590  * and sanitizes it to the current state
15591  */
15592 static void
15593 intel_modeset_setup_hw_state(struct drm_device *dev,
15594                              struct drm_modeset_acquire_ctx *ctx)
15595 {
15596         struct drm_i915_private *dev_priv = to_i915(dev);
15597         enum pipe pipe;
15598         struct intel_crtc *crtc;
15599         struct intel_encoder *encoder;
15600         int i;
15601
15602         intel_modeset_readout_hw_state(dev);
15603
15604         /* HW state is read out, now we need to sanitize this mess. */
15605         get_encoder_power_domains(dev_priv);
15606
15607         for_each_intel_encoder(dev, encoder) {
15608                 intel_sanitize_encoder(encoder);
15609         }
15610
15611         for_each_pipe(dev_priv, pipe) {
15612                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15613
15614                 intel_sanitize_crtc(crtc, ctx);
15615                 intel_dump_pipe_config(crtc, crtc->config,
15616                                        "[setup_hw_state]");
15617         }
15618
15619         intel_modeset_update_connector_atomic_state(dev);
15620
15621         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15622                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15623
15624                 if (!pll->on || pll->active_mask)
15625                         continue;
15626
15627                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15628
15629                 pll->funcs.disable(dev_priv, pll);
15630                 pll->on = false;
15631         }
15632
15633         if (IS_G4X(dev_priv)) {
15634                 g4x_wm_get_hw_state(dev);
15635                 g4x_wm_sanitize(dev_priv);
15636         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15637                 vlv_wm_get_hw_state(dev);
15638                 vlv_wm_sanitize(dev_priv);
15639         } else if (IS_GEN9(dev_priv)) {
15640                 skl_wm_get_hw_state(dev);
15641         } else if (HAS_PCH_SPLIT(dev_priv)) {
15642                 ilk_wm_get_hw_state(dev);
15643         }
15644
15645         for_each_intel_crtc(dev, crtc) {
15646                 u64 put_domains;
15647
15648                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15649                 if (WARN_ON(put_domains))
15650                         modeset_put_power_domains(dev_priv, put_domains);
15651         }
15652         intel_display_set_init_power(dev_priv, false);
15653
15654         intel_power_domains_verify_state(dev_priv);
15655
15656         intel_fbc_init_pipe_state(dev_priv);
15657 }
15658
15659 void intel_display_resume(struct drm_device *dev)
15660 {
15661         struct drm_i915_private *dev_priv = to_i915(dev);
15662         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15663         struct drm_modeset_acquire_ctx ctx;
15664         int ret;
15665
15666         dev_priv->modeset_restore_state = NULL;
15667         if (state)
15668                 state->acquire_ctx = &ctx;
15669
15670         drm_modeset_acquire_init(&ctx, 0);
15671
15672         while (1) {
15673                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15674                 if (ret != -EDEADLK)
15675                         break;
15676
15677                 drm_modeset_backoff(&ctx);
15678         }
15679
15680         if (!ret)
15681                 ret = __intel_display_resume(dev, state, &ctx);
15682
15683         drm_modeset_drop_locks(&ctx);
15684         drm_modeset_acquire_fini(&ctx);
15685
15686         if (ret)
15687                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15688         if (state)
15689                 drm_atomic_state_put(state);
15690 }
15691
15692 void intel_modeset_gem_init(struct drm_device *dev)
15693 {
15694         struct drm_i915_private *dev_priv = to_i915(dev);
15695
15696         intel_init_gt_powersave(dev_priv);
15697
15698         intel_setup_overlay(dev_priv);
15699 }
15700
15701 int intel_connector_register(struct drm_connector *connector)
15702 {
15703         struct intel_connector *intel_connector = to_intel_connector(connector);
15704         int ret;
15705
15706         ret = intel_backlight_device_register(intel_connector);
15707         if (ret)
15708                 goto err;
15709
15710         return 0;
15711
15712 err:
15713         return ret;
15714 }
15715
15716 void intel_connector_unregister(struct drm_connector *connector)
15717 {
15718         struct intel_connector *intel_connector = to_intel_connector(connector);
15719
15720         intel_backlight_device_unregister(intel_connector);
15721         intel_panel_destroy_backlight(connector);
15722 }
15723
15724 void intel_modeset_cleanup(struct drm_device *dev)
15725 {
15726         struct drm_i915_private *dev_priv = to_i915(dev);
15727
15728         flush_work(&dev_priv->atomic_helper.free_work);
15729         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15730
15731         intel_disable_gt_powersave(dev_priv);
15732
15733         /*
15734          * Interrupts and polling as the first thing to avoid creating havoc.
15735          * Too much stuff here (turning of connectors, ...) would
15736          * experience fancy races otherwise.
15737          */
15738         intel_irq_uninstall(dev_priv);
15739
15740         /*
15741          * Due to the hpd irq storm handling the hotplug work can re-arm the
15742          * poll handlers. Hence disable polling after hpd handling is shut down.
15743          */
15744         drm_kms_helper_poll_fini(dev);
15745
15746         intel_unregister_dsm_handler();
15747
15748         intel_fbc_global_disable(dev_priv);
15749
15750         /* flush any delayed tasks or pending work */
15751         flush_scheduled_work();
15752
15753         drm_mode_config_cleanup(dev);
15754
15755         intel_cleanup_overlay(dev_priv);
15756
15757         intel_cleanup_gt_powersave(dev_priv);
15758
15759         intel_teardown_gmbus(dev_priv);
15760 }
15761
15762 void intel_connector_attach_encoder(struct intel_connector *connector,
15763                                     struct intel_encoder *encoder)
15764 {
15765         connector->encoder = encoder;
15766         drm_mode_connector_attach_encoder(&connector->base,
15767                                           &encoder->base);
15768 }
15769
15770 /*
15771  * set vga decode state - true == enable VGA decode
15772  */
15773 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15774 {
15775         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15776         u16 gmch_ctrl;
15777
15778         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15779                 DRM_ERROR("failed to read control word\n");
15780                 return -EIO;
15781         }
15782
15783         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15784                 return 0;
15785
15786         if (state)
15787                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15788         else
15789                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15790
15791         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15792                 DRM_ERROR("failed to write control word\n");
15793                 return -EIO;
15794         }
15795
15796         return 0;
15797 }
15798
15799 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15800
15801 struct intel_display_error_state {
15802
15803         u32 power_well_driver;
15804
15805         int num_transcoders;
15806
15807         struct intel_cursor_error_state {
15808                 u32 control;
15809                 u32 position;
15810                 u32 base;
15811                 u32 size;
15812         } cursor[I915_MAX_PIPES];
15813
15814         struct intel_pipe_error_state {
15815                 bool power_domain_on;
15816                 u32 source;
15817                 u32 stat;
15818         } pipe[I915_MAX_PIPES];
15819
15820         struct intel_plane_error_state {
15821                 u32 control;
15822                 u32 stride;
15823                 u32 size;
15824                 u32 pos;
15825                 u32 addr;
15826                 u32 surface;
15827                 u32 tile_offset;
15828         } plane[I915_MAX_PIPES];
15829
15830         struct intel_transcoder_error_state {
15831                 bool power_domain_on;
15832                 enum transcoder cpu_transcoder;
15833
15834                 u32 conf;
15835
15836                 u32 htotal;
15837                 u32 hblank;
15838                 u32 hsync;
15839                 u32 vtotal;
15840                 u32 vblank;
15841                 u32 vsync;
15842         } transcoder[4];
15843 };
15844
15845 struct intel_display_error_state *
15846 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15847 {
15848         struct intel_display_error_state *error;
15849         int transcoders[] = {
15850                 TRANSCODER_A,
15851                 TRANSCODER_B,
15852                 TRANSCODER_C,
15853                 TRANSCODER_EDP,
15854         };
15855         int i;
15856
15857         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15858                 return NULL;
15859
15860         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15861         if (error == NULL)
15862                 return NULL;
15863
15864         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15865                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
15866
15867         for_each_pipe(dev_priv, i) {
15868                 error->pipe[i].power_domain_on =
15869                         __intel_display_power_is_enabled(dev_priv,
15870                                                          POWER_DOMAIN_PIPE(i));
15871                 if (!error->pipe[i].power_domain_on)
15872                         continue;
15873
15874                 error->cursor[i].control = I915_READ(CURCNTR(i));
15875                 error->cursor[i].position = I915_READ(CURPOS(i));
15876                 error->cursor[i].base = I915_READ(CURBASE(i));
15877
15878                 error->plane[i].control = I915_READ(DSPCNTR(i));
15879                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15880                 if (INTEL_GEN(dev_priv) <= 3) {
15881                         error->plane[i].size = I915_READ(DSPSIZE(i));
15882                         error->plane[i].pos = I915_READ(DSPPOS(i));
15883                 }
15884                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15885                         error->plane[i].addr = I915_READ(DSPADDR(i));
15886                 if (INTEL_GEN(dev_priv) >= 4) {
15887                         error->plane[i].surface = I915_READ(DSPSURF(i));
15888                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15889                 }
15890
15891                 error->pipe[i].source = I915_READ(PIPESRC(i));
15892
15893                 if (HAS_GMCH_DISPLAY(dev_priv))
15894                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15895         }
15896
15897         /* Note: this does not include DSI transcoders. */
15898         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15899         if (HAS_DDI(dev_priv))
15900                 error->num_transcoders++; /* Account for eDP. */
15901
15902         for (i = 0; i < error->num_transcoders; i++) {
15903                 enum transcoder cpu_transcoder = transcoders[i];
15904
15905                 error->transcoder[i].power_domain_on =
15906                         __intel_display_power_is_enabled(dev_priv,
15907                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15908                 if (!error->transcoder[i].power_domain_on)
15909                         continue;
15910
15911                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15912
15913                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15914                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15915                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15916                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15917                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15918                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15919                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15920         }
15921
15922         return error;
15923 }
15924
15925 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15926
15927 void
15928 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15929                                 struct intel_display_error_state *error)
15930 {
15931         struct drm_i915_private *dev_priv = m->i915;
15932         int i;
15933
15934         if (!error)
15935                 return;
15936
15937         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15938         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15939                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15940                            error->power_well_driver);
15941         for_each_pipe(dev_priv, i) {
15942                 err_printf(m, "Pipe [%d]:\n", i);
15943                 err_printf(m, "  Power: %s\n",
15944                            onoff(error->pipe[i].power_domain_on));
15945                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15946                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15947
15948                 err_printf(m, "Plane [%d]:\n", i);
15949                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15950                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15951                 if (INTEL_GEN(dev_priv) <= 3) {
15952                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15953                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15954                 }
15955                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15956                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15957                 if (INTEL_GEN(dev_priv) >= 4) {
15958                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15959                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15960                 }
15961
15962                 err_printf(m, "Cursor [%d]:\n", i);
15963                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15964                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15965                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15966         }
15967
15968         for (i = 0; i < error->num_transcoders; i++) {
15969                 err_printf(m, "CPU transcoder: %s\n",
15970                            transcoder_name(error->transcoder[i].cpu_transcoder));
15971                 err_printf(m, "  Power: %s\n",
15972                            onoff(error->transcoder[i].power_domain_on));
15973                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15974                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15975                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15976                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15977                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15978                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15979                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15980         }
15981 }
15982
15983 #endif