drm/i915: Make HW readout mark CRTC scaler as in use.
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/module.h>
28 #include <linux/input.h>
29 #include <linux/i2c.h>
30 #include <linux/kernel.h>
31 #include <linux/slab.h>
32 #include <linux/vgaarb.h>
33 #include <drm/drm_edid.h>
34 #include <drm/i915_drm.h>
35 #include <drm/drm_atomic.h>
36 #include <drm/drm_atomic_helper.h>
37 #include <drm/drm_dp_helper.h>
38 #include <drm/drm_crtc_helper.h>
39 #include <drm/drm_plane_helper.h>
40 #include <drm/drm_rect.h>
41 #include <drm/drm_atomic_uapi.h>
42 #include <linux/intel-iommu.h>
43 #include <linux/reservation.h>
44
45 #include "intel_drv.h"
46 #include "intel_dsi.h"
47 #include "intel_frontbuffer.h"
48
49 #include "i915_drv.h"
50 #include "i915_gem_clflush.h"
51 #include "i915_reset.h"
52 #include "i915_trace.h"
53
54 /* Primary plane formats for gen <= 3 */
55 static const u32 i8xx_primary_formats[] = {
56         DRM_FORMAT_C8,
57         DRM_FORMAT_RGB565,
58         DRM_FORMAT_XRGB1555,
59         DRM_FORMAT_XRGB8888,
60 };
61
62 /* Primary plane formats for gen >= 4 */
63 static const u32 i965_primary_formats[] = {
64         DRM_FORMAT_C8,
65         DRM_FORMAT_RGB565,
66         DRM_FORMAT_XRGB8888,
67         DRM_FORMAT_XBGR8888,
68         DRM_FORMAT_XRGB2101010,
69         DRM_FORMAT_XBGR2101010,
70 };
71
72 static const u64 i9xx_format_modifiers[] = {
73         I915_FORMAT_MOD_X_TILED,
74         DRM_FORMAT_MOD_LINEAR,
75         DRM_FORMAT_MOD_INVALID
76 };
77
78 /* Cursor formats */
79 static const u32 intel_cursor_formats[] = {
80         DRM_FORMAT_ARGB8888,
81 };
82
83 static const u64 cursor_format_modifiers[] = {
84         DRM_FORMAT_MOD_LINEAR,
85         DRM_FORMAT_MOD_INVALID
86 };
87
88 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
89                                 struct intel_crtc_state *pipe_config);
90 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
91                                    struct intel_crtc_state *pipe_config);
92
93 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
94                                   struct drm_i915_gem_object *obj,
95                                   struct drm_mode_fb_cmd2 *mode_cmd);
96 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state);
97 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state);
98 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
99                                          const struct intel_link_m_n *m_n,
100                                          const struct intel_link_m_n *m2_n2);
101 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state);
102 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state);
103 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state);
104 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state);
105 static void vlv_prepare_pll(struct intel_crtc *crtc,
106                             const struct intel_crtc_state *pipe_config);
107 static void chv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
110 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
111 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
112                                     struct intel_crtc_state *crtc_state);
113 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state);
114 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state);
115 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state);
116 static void intel_modeset_setup_hw_state(struct drm_device *dev,
117                                          struct drm_modeset_acquire_ctx *ctx);
118 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
119
120 struct intel_limit {
121         struct {
122                 int min, max;
123         } dot, vco, n, m, m1, m2, p, p1;
124
125         struct {
126                 int dot_limit;
127                 int p2_slow, p2_fast;
128         } p2;
129 };
130
131 /* returns HPLL frequency in kHz */
132 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
133 {
134         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
135
136         /* Obtain SKU information */
137         mutex_lock(&dev_priv->sb_lock);
138         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
139                 CCK_FUSE_HPLL_FREQ_MASK;
140         mutex_unlock(&dev_priv->sb_lock);
141
142         return vco_freq[hpll_freq] * 1000;
143 }
144
145 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
146                       const char *name, u32 reg, int ref_freq)
147 {
148         u32 val;
149         int divider;
150
151         mutex_lock(&dev_priv->sb_lock);
152         val = vlv_cck_read(dev_priv, reg);
153         mutex_unlock(&dev_priv->sb_lock);
154
155         divider = val & CCK_FREQUENCY_VALUES;
156
157         WARN((val & CCK_FREQUENCY_STATUS) !=
158              (divider << CCK_FREQUENCY_STATUS_SHIFT),
159              "%s change in progress\n", name);
160
161         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
162 }
163
164 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
165                            const char *name, u32 reg)
166 {
167         if (dev_priv->hpll_freq == 0)
168                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
169
170         return vlv_get_cck_clock(dev_priv, name, reg,
171                                  dev_priv->hpll_freq);
172 }
173
174 static void intel_update_czclk(struct drm_i915_private *dev_priv)
175 {
176         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
177                 return;
178
179         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
180                                                       CCK_CZ_CLOCK_CONTROL);
181
182         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
183 }
184
185 static inline u32 /* units of 100MHz */
186 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
187                     const struct intel_crtc_state *pipe_config)
188 {
189         if (HAS_DDI(dev_priv))
190                 return pipe_config->port_clock; /* SPLL */
191         else
192                 return dev_priv->fdi_pll_freq;
193 }
194
195 static const struct intel_limit intel_limits_i8xx_dac = {
196         .dot = { .min = 25000, .max = 350000 },
197         .vco = { .min = 908000, .max = 1512000 },
198         .n = { .min = 2, .max = 16 },
199         .m = { .min = 96, .max = 140 },
200         .m1 = { .min = 18, .max = 26 },
201         .m2 = { .min = 6, .max = 16 },
202         .p = { .min = 4, .max = 128 },
203         .p1 = { .min = 2, .max = 33 },
204         .p2 = { .dot_limit = 165000,
205                 .p2_slow = 4, .p2_fast = 2 },
206 };
207
208 static const struct intel_limit intel_limits_i8xx_dvo = {
209         .dot = { .min = 25000, .max = 350000 },
210         .vco = { .min = 908000, .max = 1512000 },
211         .n = { .min = 2, .max = 16 },
212         .m = { .min = 96, .max = 140 },
213         .m1 = { .min = 18, .max = 26 },
214         .m2 = { .min = 6, .max = 16 },
215         .p = { .min = 4, .max = 128 },
216         .p1 = { .min = 2, .max = 33 },
217         .p2 = { .dot_limit = 165000,
218                 .p2_slow = 4, .p2_fast = 4 },
219 };
220
221 static const struct intel_limit intel_limits_i8xx_lvds = {
222         .dot = { .min = 25000, .max = 350000 },
223         .vco = { .min = 908000, .max = 1512000 },
224         .n = { .min = 2, .max = 16 },
225         .m = { .min = 96, .max = 140 },
226         .m1 = { .min = 18, .max = 26 },
227         .m2 = { .min = 6, .max = 16 },
228         .p = { .min = 4, .max = 128 },
229         .p1 = { .min = 1, .max = 6 },
230         .p2 = { .dot_limit = 165000,
231                 .p2_slow = 14, .p2_fast = 7 },
232 };
233
234 static const struct intel_limit intel_limits_i9xx_sdvo = {
235         .dot = { .min = 20000, .max = 400000 },
236         .vco = { .min = 1400000, .max = 2800000 },
237         .n = { .min = 1, .max = 6 },
238         .m = { .min = 70, .max = 120 },
239         .m1 = { .min = 8, .max = 18 },
240         .m2 = { .min = 3, .max = 7 },
241         .p = { .min = 5, .max = 80 },
242         .p1 = { .min = 1, .max = 8 },
243         .p2 = { .dot_limit = 200000,
244                 .p2_slow = 10, .p2_fast = 5 },
245 };
246
247 static const struct intel_limit intel_limits_i9xx_lvds = {
248         .dot = { .min = 20000, .max = 400000 },
249         .vco = { .min = 1400000, .max = 2800000 },
250         .n = { .min = 1, .max = 6 },
251         .m = { .min = 70, .max = 120 },
252         .m1 = { .min = 8, .max = 18 },
253         .m2 = { .min = 3, .max = 7 },
254         .p = { .min = 7, .max = 98 },
255         .p1 = { .min = 1, .max = 8 },
256         .p2 = { .dot_limit = 112000,
257                 .p2_slow = 14, .p2_fast = 7 },
258 };
259
260
261 static const struct intel_limit intel_limits_g4x_sdvo = {
262         .dot = { .min = 25000, .max = 270000 },
263         .vco = { .min = 1750000, .max = 3500000},
264         .n = { .min = 1, .max = 4 },
265         .m = { .min = 104, .max = 138 },
266         .m1 = { .min = 17, .max = 23 },
267         .m2 = { .min = 5, .max = 11 },
268         .p = { .min = 10, .max = 30 },
269         .p1 = { .min = 1, .max = 3},
270         .p2 = { .dot_limit = 270000,
271                 .p2_slow = 10,
272                 .p2_fast = 10
273         },
274 };
275
276 static const struct intel_limit intel_limits_g4x_hdmi = {
277         .dot = { .min = 22000, .max = 400000 },
278         .vco = { .min = 1750000, .max = 3500000},
279         .n = { .min = 1, .max = 4 },
280         .m = { .min = 104, .max = 138 },
281         .m1 = { .min = 16, .max = 23 },
282         .m2 = { .min = 5, .max = 11 },
283         .p = { .min = 5, .max = 80 },
284         .p1 = { .min = 1, .max = 8},
285         .p2 = { .dot_limit = 165000,
286                 .p2_slow = 10, .p2_fast = 5 },
287 };
288
289 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
290         .dot = { .min = 20000, .max = 115000 },
291         .vco = { .min = 1750000, .max = 3500000 },
292         .n = { .min = 1, .max = 3 },
293         .m = { .min = 104, .max = 138 },
294         .m1 = { .min = 17, .max = 23 },
295         .m2 = { .min = 5, .max = 11 },
296         .p = { .min = 28, .max = 112 },
297         .p1 = { .min = 2, .max = 8 },
298         .p2 = { .dot_limit = 0,
299                 .p2_slow = 14, .p2_fast = 14
300         },
301 };
302
303 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
304         .dot = { .min = 80000, .max = 224000 },
305         .vco = { .min = 1750000, .max = 3500000 },
306         .n = { .min = 1, .max = 3 },
307         .m = { .min = 104, .max = 138 },
308         .m1 = { .min = 17, .max = 23 },
309         .m2 = { .min = 5, .max = 11 },
310         .p = { .min = 14, .max = 42 },
311         .p1 = { .min = 2, .max = 6 },
312         .p2 = { .dot_limit = 0,
313                 .p2_slow = 7, .p2_fast = 7
314         },
315 };
316
317 static const struct intel_limit intel_limits_pineview_sdvo = {
318         .dot = { .min = 20000, .max = 400000},
319         .vco = { .min = 1700000, .max = 3500000 },
320         /* Pineview's Ncounter is a ring counter */
321         .n = { .min = 3, .max = 6 },
322         .m = { .min = 2, .max = 256 },
323         /* Pineview only has one combined m divider, which we treat as m2. */
324         .m1 = { .min = 0, .max = 0 },
325         .m2 = { .min = 0, .max = 254 },
326         .p = { .min = 5, .max = 80 },
327         .p1 = { .min = 1, .max = 8 },
328         .p2 = { .dot_limit = 200000,
329                 .p2_slow = 10, .p2_fast = 5 },
330 };
331
332 static const struct intel_limit intel_limits_pineview_lvds = {
333         .dot = { .min = 20000, .max = 400000 },
334         .vco = { .min = 1700000, .max = 3500000 },
335         .n = { .min = 3, .max = 6 },
336         .m = { .min = 2, .max = 256 },
337         .m1 = { .min = 0, .max = 0 },
338         .m2 = { .min = 0, .max = 254 },
339         .p = { .min = 7, .max = 112 },
340         .p1 = { .min = 1, .max = 8 },
341         .p2 = { .dot_limit = 112000,
342                 .p2_slow = 14, .p2_fast = 14 },
343 };
344
345 /* Ironlake / Sandybridge
346  *
347  * We calculate clock using (register_value + 2) for N/M1/M2, so here
348  * the range value for them is (actual_value - 2).
349  */
350 static const struct intel_limit intel_limits_ironlake_dac = {
351         .dot = { .min = 25000, .max = 350000 },
352         .vco = { .min = 1760000, .max = 3510000 },
353         .n = { .min = 1, .max = 5 },
354         .m = { .min = 79, .max = 127 },
355         .m1 = { .min = 12, .max = 22 },
356         .m2 = { .min = 5, .max = 9 },
357         .p = { .min = 5, .max = 80 },
358         .p1 = { .min = 1, .max = 8 },
359         .p2 = { .dot_limit = 225000,
360                 .p2_slow = 10, .p2_fast = 5 },
361 };
362
363 static const struct intel_limit intel_limits_ironlake_single_lvds = {
364         .dot = { .min = 25000, .max = 350000 },
365         .vco = { .min = 1760000, .max = 3510000 },
366         .n = { .min = 1, .max = 3 },
367         .m = { .min = 79, .max = 118 },
368         .m1 = { .min = 12, .max = 22 },
369         .m2 = { .min = 5, .max = 9 },
370         .p = { .min = 28, .max = 112 },
371         .p1 = { .min = 2, .max = 8 },
372         .p2 = { .dot_limit = 225000,
373                 .p2_slow = 14, .p2_fast = 14 },
374 };
375
376 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
377         .dot = { .min = 25000, .max = 350000 },
378         .vco = { .min = 1760000, .max = 3510000 },
379         .n = { .min = 1, .max = 3 },
380         .m = { .min = 79, .max = 127 },
381         .m1 = { .min = 12, .max = 22 },
382         .m2 = { .min = 5, .max = 9 },
383         .p = { .min = 14, .max = 56 },
384         .p1 = { .min = 2, .max = 8 },
385         .p2 = { .dot_limit = 225000,
386                 .p2_slow = 7, .p2_fast = 7 },
387 };
388
389 /* LVDS 100mhz refclk limits. */
390 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
391         .dot = { .min = 25000, .max = 350000 },
392         .vco = { .min = 1760000, .max = 3510000 },
393         .n = { .min = 1, .max = 2 },
394         .m = { .min = 79, .max = 126 },
395         .m1 = { .min = 12, .max = 22 },
396         .m2 = { .min = 5, .max = 9 },
397         .p = { .min = 28, .max = 112 },
398         .p1 = { .min = 2, .max = 8 },
399         .p2 = { .dot_limit = 225000,
400                 .p2_slow = 14, .p2_fast = 14 },
401 };
402
403 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
404         .dot = { .min = 25000, .max = 350000 },
405         .vco = { .min = 1760000, .max = 3510000 },
406         .n = { .min = 1, .max = 3 },
407         .m = { .min = 79, .max = 126 },
408         .m1 = { .min = 12, .max = 22 },
409         .m2 = { .min = 5, .max = 9 },
410         .p = { .min = 14, .max = 42 },
411         .p1 = { .min = 2, .max = 6 },
412         .p2 = { .dot_limit = 225000,
413                 .p2_slow = 7, .p2_fast = 7 },
414 };
415
416 static const struct intel_limit intel_limits_vlv = {
417          /*
418           * These are the data rate limits (measured in fast clocks)
419           * since those are the strictest limits we have. The fast
420           * clock and actual rate limits are more relaxed, so checking
421           * them would make no difference.
422           */
423         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
424         .vco = { .min = 4000000, .max = 6000000 },
425         .n = { .min = 1, .max = 7 },
426         .m1 = { .min = 2, .max = 3 },
427         .m2 = { .min = 11, .max = 156 },
428         .p1 = { .min = 2, .max = 3 },
429         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
430 };
431
432 static const struct intel_limit intel_limits_chv = {
433         /*
434          * These are the data rate limits (measured in fast clocks)
435          * since those are the strictest limits we have.  The fast
436          * clock and actual rate limits are more relaxed, so checking
437          * them would make no difference.
438          */
439         .dot = { .min = 25000 * 5, .max = 540000 * 5},
440         .vco = { .min = 4800000, .max = 6480000 },
441         .n = { .min = 1, .max = 1 },
442         .m1 = { .min = 2, .max = 2 },
443         .m2 = { .min = 24 << 22, .max = 175 << 22 },
444         .p1 = { .min = 2, .max = 4 },
445         .p2 = { .p2_slow = 1, .p2_fast = 14 },
446 };
447
448 static const struct intel_limit intel_limits_bxt = {
449         /* FIXME: find real dot limits */
450         .dot = { .min = 0, .max = INT_MAX },
451         .vco = { .min = 4800000, .max = 6700000 },
452         .n = { .min = 1, .max = 1 },
453         .m1 = { .min = 2, .max = 2 },
454         /* FIXME: find real m2 limits */
455         .m2 = { .min = 2 << 22, .max = 255 << 22 },
456         .p1 = { .min = 2, .max = 4 },
457         .p2 = { .p2_slow = 1, .p2_fast = 20 },
458 };
459
460 static void
461 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
462 {
463         if (enable)
464                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
465                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
466         else
467                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
468                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
469                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
470 }
471
472 static bool
473 needs_modeset(const struct drm_crtc_state *state)
474 {
475         return drm_atomic_crtc_needs_modeset(state);
476 }
477
478 /*
479  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
480  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
481  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
482  * The helpers' return value is the rate of the clock that is fed to the
483  * display engine's pipe which can be the above fast dot clock rate or a
484  * divided-down version of it.
485  */
486 /* m1 is reserved as 0 in Pineview, n is a ring counter */
487 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
488 {
489         clock->m = clock->m2 + 2;
490         clock->p = clock->p1 * clock->p2;
491         if (WARN_ON(clock->n == 0 || clock->p == 0))
492                 return 0;
493         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
494         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
495
496         return clock->dot;
497 }
498
499 static u32 i9xx_dpll_compute_m(struct dpll *dpll)
500 {
501         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
502 }
503
504 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
505 {
506         clock->m = i9xx_dpll_compute_m(clock);
507         clock->p = clock->p1 * clock->p2;
508         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
509                 return 0;
510         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
511         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
512
513         return clock->dot;
514 }
515
516 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
517 {
518         clock->m = clock->m1 * clock->m2;
519         clock->p = clock->p1 * clock->p2;
520         if (WARN_ON(clock->n == 0 || clock->p == 0))
521                 return 0;
522         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
523         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
524
525         return clock->dot / 5;
526 }
527
528 int chv_calc_dpll_params(int refclk, struct dpll *clock)
529 {
530         clock->m = clock->m1 * clock->m2;
531         clock->p = clock->p1 * clock->p2;
532         if (WARN_ON(clock->n == 0 || clock->p == 0))
533                 return 0;
534         clock->vco = DIV_ROUND_CLOSEST_ULL((u64)refclk * clock->m,
535                                            clock->n << 22);
536         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
537
538         return clock->dot / 5;
539 }
540
541 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
542
543 /*
544  * Returns whether the given set of divisors are valid for a given refclk with
545  * the given connectors.
546  */
547 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
548                                const struct intel_limit *limit,
549                                const struct dpll *clock)
550 {
551         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
552                 INTELPllInvalid("n out of range\n");
553         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
554                 INTELPllInvalid("p1 out of range\n");
555         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
556                 INTELPllInvalid("m2 out of range\n");
557         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
558                 INTELPllInvalid("m1 out of range\n");
559
560         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
561             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
562                 if (clock->m1 <= clock->m2)
563                         INTELPllInvalid("m1 <= m2\n");
564
565         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
566             !IS_GEN9_LP(dev_priv)) {
567                 if (clock->p < limit->p.min || limit->p.max < clock->p)
568                         INTELPllInvalid("p out of range\n");
569                 if (clock->m < limit->m.min || limit->m.max < clock->m)
570                         INTELPllInvalid("m out of range\n");
571         }
572
573         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
574                 INTELPllInvalid("vco out of range\n");
575         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
576          * connector, etc., rather than just a single range.
577          */
578         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
579                 INTELPllInvalid("dot out of range\n");
580
581         return true;
582 }
583
584 static int
585 i9xx_select_p2_div(const struct intel_limit *limit,
586                    const struct intel_crtc_state *crtc_state,
587                    int target)
588 {
589         struct drm_device *dev = crtc_state->base.crtc->dev;
590
591         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
592                 /*
593                  * For LVDS just rely on its current settings for dual-channel.
594                  * We haven't figured out how to reliably set up different
595                  * single/dual channel state, if we even can.
596                  */
597                 if (intel_is_dual_link_lvds(dev))
598                         return limit->p2.p2_fast;
599                 else
600                         return limit->p2.p2_slow;
601         } else {
602                 if (target < limit->p2.dot_limit)
603                         return limit->p2.p2_slow;
604                 else
605                         return limit->p2.p2_fast;
606         }
607 }
608
609 /*
610  * Returns a set of divisors for the desired target clock with the given
611  * refclk, or FALSE.  The returned values represent the clock equation:
612  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
613  *
614  * Target and reference clocks are specified in kHz.
615  *
616  * If match_clock is provided, then best_clock P divider must match the P
617  * divider from @match_clock used for LVDS downclocking.
618  */
619 static bool
620 i9xx_find_best_dpll(const struct intel_limit *limit,
621                     struct intel_crtc_state *crtc_state,
622                     int target, int refclk, struct dpll *match_clock,
623                     struct dpll *best_clock)
624 {
625         struct drm_device *dev = crtc_state->base.crtc->dev;
626         struct dpll clock;
627         int err = target;
628
629         memset(best_clock, 0, sizeof(*best_clock));
630
631         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
632
633         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
634              clock.m1++) {
635                 for (clock.m2 = limit->m2.min;
636                      clock.m2 <= limit->m2.max; clock.m2++) {
637                         if (clock.m2 >= clock.m1)
638                                 break;
639                         for (clock.n = limit->n.min;
640                              clock.n <= limit->n.max; clock.n++) {
641                                 for (clock.p1 = limit->p1.min;
642                                         clock.p1 <= limit->p1.max; clock.p1++) {
643                                         int this_err;
644
645                                         i9xx_calc_dpll_params(refclk, &clock);
646                                         if (!intel_PLL_is_valid(to_i915(dev),
647                                                                 limit,
648                                                                 &clock))
649                                                 continue;
650                                         if (match_clock &&
651                                             clock.p != match_clock->p)
652                                                 continue;
653
654                                         this_err = abs(clock.dot - target);
655                                         if (this_err < err) {
656                                                 *best_clock = clock;
657                                                 err = this_err;
658                                         }
659                                 }
660                         }
661                 }
662         }
663
664         return (err != target);
665 }
666
667 /*
668  * Returns a set of divisors for the desired target clock with the given
669  * refclk, or FALSE.  The returned values represent the clock equation:
670  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
671  *
672  * Target and reference clocks are specified in kHz.
673  *
674  * If match_clock is provided, then best_clock P divider must match the P
675  * divider from @match_clock used for LVDS downclocking.
676  */
677 static bool
678 pnv_find_best_dpll(const struct intel_limit *limit,
679                    struct intel_crtc_state *crtc_state,
680                    int target, int refclk, struct dpll *match_clock,
681                    struct dpll *best_clock)
682 {
683         struct drm_device *dev = crtc_state->base.crtc->dev;
684         struct dpll clock;
685         int err = target;
686
687         memset(best_clock, 0, sizeof(*best_clock));
688
689         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
690
691         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
692              clock.m1++) {
693                 for (clock.m2 = limit->m2.min;
694                      clock.m2 <= limit->m2.max; clock.m2++) {
695                         for (clock.n = limit->n.min;
696                              clock.n <= limit->n.max; clock.n++) {
697                                 for (clock.p1 = limit->p1.min;
698                                         clock.p1 <= limit->p1.max; clock.p1++) {
699                                         int this_err;
700
701                                         pnv_calc_dpll_params(refclk, &clock);
702                                         if (!intel_PLL_is_valid(to_i915(dev),
703                                                                 limit,
704                                                                 &clock))
705                                                 continue;
706                                         if (match_clock &&
707                                             clock.p != match_clock->p)
708                                                 continue;
709
710                                         this_err = abs(clock.dot - target);
711                                         if (this_err < err) {
712                                                 *best_clock = clock;
713                                                 err = this_err;
714                                         }
715                                 }
716                         }
717                 }
718         }
719
720         return (err != target);
721 }
722
723 /*
724  * Returns a set of divisors for the desired target clock with the given
725  * refclk, or FALSE.  The returned values represent the clock equation:
726  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
727  *
728  * Target and reference clocks are specified in kHz.
729  *
730  * If match_clock is provided, then best_clock P divider must match the P
731  * divider from @match_clock used for LVDS downclocking.
732  */
733 static bool
734 g4x_find_best_dpll(const struct intel_limit *limit,
735                    struct intel_crtc_state *crtc_state,
736                    int target, int refclk, struct dpll *match_clock,
737                    struct dpll *best_clock)
738 {
739         struct drm_device *dev = crtc_state->base.crtc->dev;
740         struct dpll clock;
741         int max_n;
742         bool found = false;
743         /* approximately equals target * 0.00585 */
744         int err_most = (target >> 8) + (target >> 9);
745
746         memset(best_clock, 0, sizeof(*best_clock));
747
748         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
749
750         max_n = limit->n.max;
751         /* based on hardware requirement, prefer smaller n to precision */
752         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
753                 /* based on hardware requirement, prefere larger m1,m2 */
754                 for (clock.m1 = limit->m1.max;
755                      clock.m1 >= limit->m1.min; clock.m1--) {
756                         for (clock.m2 = limit->m2.max;
757                              clock.m2 >= limit->m2.min; clock.m2--) {
758                                 for (clock.p1 = limit->p1.max;
759                                      clock.p1 >= limit->p1.min; clock.p1--) {
760                                         int this_err;
761
762                                         i9xx_calc_dpll_params(refclk, &clock);
763                                         if (!intel_PLL_is_valid(to_i915(dev),
764                                                                 limit,
765                                                                 &clock))
766                                                 continue;
767
768                                         this_err = abs(clock.dot - target);
769                                         if (this_err < err_most) {
770                                                 *best_clock = clock;
771                                                 err_most = this_err;
772                                                 max_n = clock.n;
773                                                 found = true;
774                                         }
775                                 }
776                         }
777                 }
778         }
779         return found;
780 }
781
782 /*
783  * Check if the calculated PLL configuration is more optimal compared to the
784  * best configuration and error found so far. Return the calculated error.
785  */
786 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
787                                const struct dpll *calculated_clock,
788                                const struct dpll *best_clock,
789                                unsigned int best_error_ppm,
790                                unsigned int *error_ppm)
791 {
792         /*
793          * For CHV ignore the error and consider only the P value.
794          * Prefer a bigger P value based on HW requirements.
795          */
796         if (IS_CHERRYVIEW(to_i915(dev))) {
797                 *error_ppm = 0;
798
799                 return calculated_clock->p > best_clock->p;
800         }
801
802         if (WARN_ON_ONCE(!target_freq))
803                 return false;
804
805         *error_ppm = div_u64(1000000ULL *
806                                 abs(target_freq - calculated_clock->dot),
807                              target_freq);
808         /*
809          * Prefer a better P value over a better (smaller) error if the error
810          * is small. Ensure this preference for future configurations too by
811          * setting the error to 0.
812          */
813         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
814                 *error_ppm = 0;
815
816                 return true;
817         }
818
819         return *error_ppm + 10 < best_error_ppm;
820 }
821
822 /*
823  * Returns a set of divisors for the desired target clock with the given
824  * refclk, or FALSE.  The returned values represent the clock equation:
825  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
826  */
827 static bool
828 vlv_find_best_dpll(const struct intel_limit *limit,
829                    struct intel_crtc_state *crtc_state,
830                    int target, int refclk, struct dpll *match_clock,
831                    struct dpll *best_clock)
832 {
833         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
834         struct drm_device *dev = crtc->base.dev;
835         struct dpll clock;
836         unsigned int bestppm = 1000000;
837         /* min update 19.2 MHz */
838         int max_n = min(limit->n.max, refclk / 19200);
839         bool found = false;
840
841         target *= 5; /* fast clock */
842
843         memset(best_clock, 0, sizeof(*best_clock));
844
845         /* based on hardware requirement, prefer smaller n to precision */
846         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
847                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
848                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
849                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
850                                 clock.p = clock.p1 * clock.p2;
851                                 /* based on hardware requirement, prefer bigger m1,m2 values */
852                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
853                                         unsigned int ppm;
854
855                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
856                                                                      refclk * clock.m1);
857
858                                         vlv_calc_dpll_params(refclk, &clock);
859
860                                         if (!intel_PLL_is_valid(to_i915(dev),
861                                                                 limit,
862                                                                 &clock))
863                                                 continue;
864
865                                         if (!vlv_PLL_is_optimal(dev, target,
866                                                                 &clock,
867                                                                 best_clock,
868                                                                 bestppm, &ppm))
869                                                 continue;
870
871                                         *best_clock = clock;
872                                         bestppm = ppm;
873                                         found = true;
874                                 }
875                         }
876                 }
877         }
878
879         return found;
880 }
881
882 /*
883  * Returns a set of divisors for the desired target clock with the given
884  * refclk, or FALSE.  The returned values represent the clock equation:
885  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
886  */
887 static bool
888 chv_find_best_dpll(const struct intel_limit *limit,
889                    struct intel_crtc_state *crtc_state,
890                    int target, int refclk, struct dpll *match_clock,
891                    struct dpll *best_clock)
892 {
893         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
894         struct drm_device *dev = crtc->base.dev;
895         unsigned int best_error_ppm;
896         struct dpll clock;
897         u64 m2;
898         int found = false;
899
900         memset(best_clock, 0, sizeof(*best_clock));
901         best_error_ppm = 1000000;
902
903         /*
904          * Based on hardware doc, the n always set to 1, and m1 always
905          * set to 2.  If requires to support 200Mhz refclk, we need to
906          * revisit this because n may not 1 anymore.
907          */
908         clock.n = 1, clock.m1 = 2;
909         target *= 5;    /* fast clock */
910
911         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
912                 for (clock.p2 = limit->p2.p2_fast;
913                                 clock.p2 >= limit->p2.p2_slow;
914                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
915                         unsigned int error_ppm;
916
917                         clock.p = clock.p1 * clock.p2;
918
919                         m2 = DIV_ROUND_CLOSEST_ULL(((u64)target * clock.p *
920                                         clock.n) << 22, refclk * clock.m1);
921
922                         if (m2 > INT_MAX/clock.m1)
923                                 continue;
924
925                         clock.m2 = m2;
926
927                         chv_calc_dpll_params(refclk, &clock);
928
929                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
930                                 continue;
931
932                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
933                                                 best_error_ppm, &error_ppm))
934                                 continue;
935
936                         *best_clock = clock;
937                         best_error_ppm = error_ppm;
938                         found = true;
939                 }
940         }
941
942         return found;
943 }
944
945 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
946                         struct dpll *best_clock)
947 {
948         int refclk = 100000;
949         const struct intel_limit *limit = &intel_limits_bxt;
950
951         return chv_find_best_dpll(limit, crtc_state,
952                                   target_clock, refclk, NULL, best_clock);
953 }
954
955 bool intel_crtc_active(struct intel_crtc *crtc)
956 {
957         /* Be paranoid as we can arrive here with only partial
958          * state retrieved from the hardware during setup.
959          *
960          * We can ditch the adjusted_mode.crtc_clock check as soon
961          * as Haswell has gained clock readout/fastboot support.
962          *
963          * We can ditch the crtc->primary->state->fb check as soon as we can
964          * properly reconstruct framebuffers.
965          *
966          * FIXME: The intel_crtc->active here should be switched to
967          * crtc->state->active once we have proper CRTC states wired up
968          * for atomic.
969          */
970         return crtc->active && crtc->base.primary->state->fb &&
971                 crtc->config->base.adjusted_mode.crtc_clock;
972 }
973
974 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
975                                              enum pipe pipe)
976 {
977         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
978
979         return crtc->config->cpu_transcoder;
980 }
981
982 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
983                                     enum pipe pipe)
984 {
985         i915_reg_t reg = PIPEDSL(pipe);
986         u32 line1, line2;
987         u32 line_mask;
988
989         if (IS_GEN(dev_priv, 2))
990                 line_mask = DSL_LINEMASK_GEN2;
991         else
992                 line_mask = DSL_LINEMASK_GEN3;
993
994         line1 = I915_READ(reg) & line_mask;
995         msleep(5);
996         line2 = I915_READ(reg) & line_mask;
997
998         return line1 != line2;
999 }
1000
1001 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1002 {
1003         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1004         enum pipe pipe = crtc->pipe;
1005
1006         /* Wait for the display line to settle/start moving */
1007         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1008                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1009                           pipe_name(pipe), onoff(state));
1010 }
1011
1012 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1013 {
1014         wait_for_pipe_scanline_moving(crtc, false);
1015 }
1016
1017 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1018 {
1019         wait_for_pipe_scanline_moving(crtc, true);
1020 }
1021
1022 static void
1023 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1024 {
1025         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1026         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1027
1028         if (INTEL_GEN(dev_priv) >= 4) {
1029                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1030                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1031
1032                 /* Wait for the Pipe State to go off */
1033                 if (intel_wait_for_register(dev_priv,
1034                                             reg, I965_PIPECONF_ACTIVE, 0,
1035                                             100))
1036                         WARN(1, "pipe_off wait timed out\n");
1037         } else {
1038                 intel_wait_for_pipe_scanline_stopped(crtc);
1039         }
1040 }
1041
1042 /* Only for pre-ILK configs */
1043 void assert_pll(struct drm_i915_private *dev_priv,
1044                 enum pipe pipe, bool state)
1045 {
1046         u32 val;
1047         bool cur_state;
1048
1049         val = I915_READ(DPLL(pipe));
1050         cur_state = !!(val & DPLL_VCO_ENABLE);
1051         I915_STATE_WARN(cur_state != state,
1052              "PLL state assertion failure (expected %s, current %s)\n",
1053                         onoff(state), onoff(cur_state));
1054 }
1055
1056 /* XXX: the dsi pll is shared between MIPI DSI ports */
1057 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1058 {
1059         u32 val;
1060         bool cur_state;
1061
1062         mutex_lock(&dev_priv->sb_lock);
1063         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1064         mutex_unlock(&dev_priv->sb_lock);
1065
1066         cur_state = val & DSI_PLL_VCO_EN;
1067         I915_STATE_WARN(cur_state != state,
1068              "DSI PLL state assertion failure (expected %s, current %s)\n",
1069                         onoff(state), onoff(cur_state));
1070 }
1071
1072 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1073                           enum pipe pipe, bool state)
1074 {
1075         bool cur_state;
1076         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1077                                                                       pipe);
1078
1079         if (HAS_DDI(dev_priv)) {
1080                 /* DDI does not have a specific FDI_TX register */
1081                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1082                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1083         } else {
1084                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1085                 cur_state = !!(val & FDI_TX_ENABLE);
1086         }
1087         I915_STATE_WARN(cur_state != state,
1088              "FDI TX state assertion failure (expected %s, current %s)\n",
1089                         onoff(state), onoff(cur_state));
1090 }
1091 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1092 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1093
1094 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1095                           enum pipe pipe, bool state)
1096 {
1097         u32 val;
1098         bool cur_state;
1099
1100         val = I915_READ(FDI_RX_CTL(pipe));
1101         cur_state = !!(val & FDI_RX_ENABLE);
1102         I915_STATE_WARN(cur_state != state,
1103              "FDI RX state assertion failure (expected %s, current %s)\n",
1104                         onoff(state), onoff(cur_state));
1105 }
1106 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1107 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1108
1109 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1110                                       enum pipe pipe)
1111 {
1112         u32 val;
1113
1114         /* ILK FDI PLL is always enabled */
1115         if (IS_GEN(dev_priv, 5))
1116                 return;
1117
1118         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1119         if (HAS_DDI(dev_priv))
1120                 return;
1121
1122         val = I915_READ(FDI_TX_CTL(pipe));
1123         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1124 }
1125
1126 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1127                        enum pipe pipe, bool state)
1128 {
1129         u32 val;
1130         bool cur_state;
1131
1132         val = I915_READ(FDI_RX_CTL(pipe));
1133         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1134         I915_STATE_WARN(cur_state != state,
1135              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1136                         onoff(state), onoff(cur_state));
1137 }
1138
1139 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1140 {
1141         i915_reg_t pp_reg;
1142         u32 val;
1143         enum pipe panel_pipe = INVALID_PIPE;
1144         bool locked = true;
1145
1146         if (WARN_ON(HAS_DDI(dev_priv)))
1147                 return;
1148
1149         if (HAS_PCH_SPLIT(dev_priv)) {
1150                 u32 port_sel;
1151
1152                 pp_reg = PP_CONTROL(0);
1153                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1154
1155                 switch (port_sel) {
1156                 case PANEL_PORT_SELECT_LVDS:
1157                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1158                         break;
1159                 case PANEL_PORT_SELECT_DPA:
1160                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1161                         break;
1162                 case PANEL_PORT_SELECT_DPC:
1163                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1164                         break;
1165                 case PANEL_PORT_SELECT_DPD:
1166                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1167                         break;
1168                 default:
1169                         MISSING_CASE(port_sel);
1170                         break;
1171                 }
1172         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1173                 /* presumably write lock depends on pipe, not port select */
1174                 pp_reg = PP_CONTROL(pipe);
1175                 panel_pipe = pipe;
1176         } else {
1177                 u32 port_sel;
1178
1179                 pp_reg = PP_CONTROL(0);
1180                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1181
1182                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1183                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1184         }
1185
1186         val = I915_READ(pp_reg);
1187         if (!(val & PANEL_POWER_ON) ||
1188             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1189                 locked = false;
1190
1191         I915_STATE_WARN(panel_pipe == pipe && locked,
1192              "panel assertion failure, pipe %c regs locked\n",
1193              pipe_name(pipe));
1194 }
1195
1196 void assert_pipe(struct drm_i915_private *dev_priv,
1197                  enum pipe pipe, bool state)
1198 {
1199         bool cur_state;
1200         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1201                                                                       pipe);
1202         enum intel_display_power_domain power_domain;
1203         intel_wakeref_t wakeref;
1204
1205         /* we keep both pipes enabled on 830 */
1206         if (IS_I830(dev_priv))
1207                 state = true;
1208
1209         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1210         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
1211         if (wakeref) {
1212                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1213                 cur_state = !!(val & PIPECONF_ENABLE);
1214
1215                 intel_display_power_put(dev_priv, power_domain, wakeref);
1216         } else {
1217                 cur_state = false;
1218         }
1219
1220         I915_STATE_WARN(cur_state != state,
1221              "pipe %c assertion failure (expected %s, current %s)\n",
1222                         pipe_name(pipe), onoff(state), onoff(cur_state));
1223 }
1224
1225 static void assert_plane(struct intel_plane *plane, bool state)
1226 {
1227         enum pipe pipe;
1228         bool cur_state;
1229
1230         cur_state = plane->get_hw_state(plane, &pipe);
1231
1232         I915_STATE_WARN(cur_state != state,
1233                         "%s assertion failure (expected %s, current %s)\n",
1234                         plane->base.name, onoff(state), onoff(cur_state));
1235 }
1236
1237 #define assert_plane_enabled(p) assert_plane(p, true)
1238 #define assert_plane_disabled(p) assert_plane(p, false)
1239
1240 static void assert_planes_disabled(struct intel_crtc *crtc)
1241 {
1242         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1243         struct intel_plane *plane;
1244
1245         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1246                 assert_plane_disabled(plane);
1247 }
1248
1249 static void assert_vblank_disabled(struct drm_crtc *crtc)
1250 {
1251         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1252                 drm_crtc_vblank_put(crtc);
1253 }
1254
1255 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1256                                     enum pipe pipe)
1257 {
1258         u32 val;
1259         bool enabled;
1260
1261         val = I915_READ(PCH_TRANSCONF(pipe));
1262         enabled = !!(val & TRANS_ENABLE);
1263         I915_STATE_WARN(enabled,
1264              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1265              pipe_name(pipe));
1266 }
1267
1268 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1269                                    enum pipe pipe, enum port port,
1270                                    i915_reg_t dp_reg)
1271 {
1272         enum pipe port_pipe;
1273         bool state;
1274
1275         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1276
1277         I915_STATE_WARN(state && port_pipe == pipe,
1278                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1279                         port_name(port), pipe_name(pipe));
1280
1281         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1282                         "IBX PCH DP %c still using transcoder B\n",
1283                         port_name(port));
1284 }
1285
1286 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1287                                      enum pipe pipe, enum port port,
1288                                      i915_reg_t hdmi_reg)
1289 {
1290         enum pipe port_pipe;
1291         bool state;
1292
1293         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1294
1295         I915_STATE_WARN(state && port_pipe == pipe,
1296                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1297                         port_name(port), pipe_name(pipe));
1298
1299         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1300                         "IBX PCH HDMI %c still using transcoder B\n",
1301                         port_name(port));
1302 }
1303
1304 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1305                                       enum pipe pipe)
1306 {
1307         enum pipe port_pipe;
1308
1309         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1310         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1311         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1312
1313         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1314                         port_pipe == pipe,
1315                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1316                         pipe_name(pipe));
1317
1318         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1319                         port_pipe == pipe,
1320                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1321                         pipe_name(pipe));
1322
1323         /* PCH SDVOB multiplex with HDMIB */
1324         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1325         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1326         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1327 }
1328
1329 static void _vlv_enable_pll(struct intel_crtc *crtc,
1330                             const struct intel_crtc_state *pipe_config)
1331 {
1332         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1333         enum pipe pipe = crtc->pipe;
1334
1335         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1336         POSTING_READ(DPLL(pipe));
1337         udelay(150);
1338
1339         if (intel_wait_for_register(dev_priv,
1340                                     DPLL(pipe),
1341                                     DPLL_LOCK_VLV,
1342                                     DPLL_LOCK_VLV,
1343                                     1))
1344                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1345 }
1346
1347 static void vlv_enable_pll(struct intel_crtc *crtc,
1348                            const struct intel_crtc_state *pipe_config)
1349 {
1350         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1351         enum pipe pipe = crtc->pipe;
1352
1353         assert_pipe_disabled(dev_priv, pipe);
1354
1355         /* PLL is protected by panel, make sure we can write it */
1356         assert_panel_unlocked(dev_priv, pipe);
1357
1358         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1359                 _vlv_enable_pll(crtc, pipe_config);
1360
1361         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1362         POSTING_READ(DPLL_MD(pipe));
1363 }
1364
1365
1366 static void _chv_enable_pll(struct intel_crtc *crtc,
1367                             const struct intel_crtc_state *pipe_config)
1368 {
1369         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1370         enum pipe pipe = crtc->pipe;
1371         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1372         u32 tmp;
1373
1374         mutex_lock(&dev_priv->sb_lock);
1375
1376         /* Enable back the 10bit clock to display controller */
1377         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1378         tmp |= DPIO_DCLKP_EN;
1379         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1380
1381         mutex_unlock(&dev_priv->sb_lock);
1382
1383         /*
1384          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1385          */
1386         udelay(1);
1387
1388         /* Enable PLL */
1389         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1390
1391         /* Check PLL is locked */
1392         if (intel_wait_for_register(dev_priv,
1393                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1394                                     1))
1395                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1396 }
1397
1398 static void chv_enable_pll(struct intel_crtc *crtc,
1399                            const struct intel_crtc_state *pipe_config)
1400 {
1401         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1402         enum pipe pipe = crtc->pipe;
1403
1404         assert_pipe_disabled(dev_priv, pipe);
1405
1406         /* PLL is protected by panel, make sure we can write it */
1407         assert_panel_unlocked(dev_priv, pipe);
1408
1409         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1410                 _chv_enable_pll(crtc, pipe_config);
1411
1412         if (pipe != PIPE_A) {
1413                 /*
1414                  * WaPixelRepeatModeFixForC0:chv
1415                  *
1416                  * DPLLCMD is AWOL. Use chicken bits to propagate
1417                  * the value from DPLLBMD to either pipe B or C.
1418                  */
1419                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1420                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1421                 I915_WRITE(CBR4_VLV, 0);
1422                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1423
1424                 /*
1425                  * DPLLB VGA mode also seems to cause problems.
1426                  * We should always have it disabled.
1427                  */
1428                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1429         } else {
1430                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1431                 POSTING_READ(DPLL_MD(pipe));
1432         }
1433 }
1434
1435 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1436 {
1437         struct intel_crtc *crtc;
1438         int count = 0;
1439
1440         for_each_intel_crtc(&dev_priv->drm, crtc) {
1441                 count += crtc->base.state->active &&
1442                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1443         }
1444
1445         return count;
1446 }
1447
1448 static void i9xx_enable_pll(struct intel_crtc *crtc,
1449                             const struct intel_crtc_state *crtc_state)
1450 {
1451         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1452         i915_reg_t reg = DPLL(crtc->pipe);
1453         u32 dpll = crtc_state->dpll_hw_state.dpll;
1454         int i;
1455
1456         assert_pipe_disabled(dev_priv, crtc->pipe);
1457
1458         /* PLL is protected by panel, make sure we can write it */
1459         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1460                 assert_panel_unlocked(dev_priv, crtc->pipe);
1461
1462         /* Enable DVO 2x clock on both PLLs if necessary */
1463         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1464                 /*
1465                  * It appears to be important that we don't enable this
1466                  * for the current pipe before otherwise configuring the
1467                  * PLL. No idea how this should be handled if multiple
1468                  * DVO outputs are enabled simultaneosly.
1469                  */
1470                 dpll |= DPLL_DVO_2X_MODE;
1471                 I915_WRITE(DPLL(!crtc->pipe),
1472                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1473         }
1474
1475         /*
1476          * Apparently we need to have VGA mode enabled prior to changing
1477          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1478          * dividers, even though the register value does change.
1479          */
1480         I915_WRITE(reg, 0);
1481
1482         I915_WRITE(reg, dpll);
1483
1484         /* Wait for the clocks to stabilize. */
1485         POSTING_READ(reg);
1486         udelay(150);
1487
1488         if (INTEL_GEN(dev_priv) >= 4) {
1489                 I915_WRITE(DPLL_MD(crtc->pipe),
1490                            crtc_state->dpll_hw_state.dpll_md);
1491         } else {
1492                 /* The pixel multiplier can only be updated once the
1493                  * DPLL is enabled and the clocks are stable.
1494                  *
1495                  * So write it again.
1496                  */
1497                 I915_WRITE(reg, dpll);
1498         }
1499
1500         /* We do this three times for luck */
1501         for (i = 0; i < 3; i++) {
1502                 I915_WRITE(reg, dpll);
1503                 POSTING_READ(reg);
1504                 udelay(150); /* wait for warmup */
1505         }
1506 }
1507
1508 static void i9xx_disable_pll(const struct intel_crtc_state *crtc_state)
1509 {
1510         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1511         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1512         enum pipe pipe = crtc->pipe;
1513
1514         /* Disable DVO 2x clock on both PLLs if necessary */
1515         if (IS_I830(dev_priv) &&
1516             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO) &&
1517             !intel_num_dvo_pipes(dev_priv)) {
1518                 I915_WRITE(DPLL(PIPE_B),
1519                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1520                 I915_WRITE(DPLL(PIPE_A),
1521                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1522         }
1523
1524         /* Don't disable pipe or pipe PLLs if needed */
1525         if (IS_I830(dev_priv))
1526                 return;
1527
1528         /* Make sure the pipe isn't still relying on us */
1529         assert_pipe_disabled(dev_priv, pipe);
1530
1531         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1532         POSTING_READ(DPLL(pipe));
1533 }
1534
1535 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1536 {
1537         u32 val;
1538
1539         /* Make sure the pipe isn't still relying on us */
1540         assert_pipe_disabled(dev_priv, pipe);
1541
1542         val = DPLL_INTEGRATED_REF_CLK_VLV |
1543                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1544         if (pipe != PIPE_A)
1545                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1546
1547         I915_WRITE(DPLL(pipe), val);
1548         POSTING_READ(DPLL(pipe));
1549 }
1550
1551 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1552 {
1553         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1554         u32 val;
1555
1556         /* Make sure the pipe isn't still relying on us */
1557         assert_pipe_disabled(dev_priv, pipe);
1558
1559         val = DPLL_SSC_REF_CLK_CHV |
1560                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1561         if (pipe != PIPE_A)
1562                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1563
1564         I915_WRITE(DPLL(pipe), val);
1565         POSTING_READ(DPLL(pipe));
1566
1567         mutex_lock(&dev_priv->sb_lock);
1568
1569         /* Disable 10bit clock to display controller */
1570         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1571         val &= ~DPIO_DCLKP_EN;
1572         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1573
1574         mutex_unlock(&dev_priv->sb_lock);
1575 }
1576
1577 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1578                          struct intel_digital_port *dport,
1579                          unsigned int expected_mask)
1580 {
1581         u32 port_mask;
1582         i915_reg_t dpll_reg;
1583
1584         switch (dport->base.port) {
1585         case PORT_B:
1586                 port_mask = DPLL_PORTB_READY_MASK;
1587                 dpll_reg = DPLL(0);
1588                 break;
1589         case PORT_C:
1590                 port_mask = DPLL_PORTC_READY_MASK;
1591                 dpll_reg = DPLL(0);
1592                 expected_mask <<= 4;
1593                 break;
1594         case PORT_D:
1595                 port_mask = DPLL_PORTD_READY_MASK;
1596                 dpll_reg = DPIO_PHY_STATUS;
1597                 break;
1598         default:
1599                 BUG();
1600         }
1601
1602         if (intel_wait_for_register(dev_priv,
1603                                     dpll_reg, port_mask, expected_mask,
1604                                     1000))
1605                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1606                      port_name(dport->base.port),
1607                      I915_READ(dpll_reg) & port_mask, expected_mask);
1608 }
1609
1610 static void ironlake_enable_pch_transcoder(const struct intel_crtc_state *crtc_state)
1611 {
1612         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1613         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1614         enum pipe pipe = crtc->pipe;
1615         i915_reg_t reg;
1616         u32 val, pipeconf_val;
1617
1618         /* Make sure PCH DPLL is enabled */
1619         assert_shared_dpll_enabled(dev_priv, crtc_state->shared_dpll);
1620
1621         /* FDI must be feeding us bits for PCH ports */
1622         assert_fdi_tx_enabled(dev_priv, pipe);
1623         assert_fdi_rx_enabled(dev_priv, pipe);
1624
1625         if (HAS_PCH_CPT(dev_priv)) {
1626                 /* Workaround: Set the timing override bit before enabling the
1627                  * pch transcoder. */
1628                 reg = TRANS_CHICKEN2(pipe);
1629                 val = I915_READ(reg);
1630                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1631                 I915_WRITE(reg, val);
1632         }
1633
1634         reg = PCH_TRANSCONF(pipe);
1635         val = I915_READ(reg);
1636         pipeconf_val = I915_READ(PIPECONF(pipe));
1637
1638         if (HAS_PCH_IBX(dev_priv)) {
1639                 /*
1640                  * Make the BPC in transcoder be consistent with
1641                  * that in pipeconf reg. For HDMI we must use 8bpc
1642                  * here for both 8bpc and 12bpc.
1643                  */
1644                 val &= ~PIPECONF_BPC_MASK;
1645                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
1646                         val |= PIPECONF_8BPC;
1647                 else
1648                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1649         }
1650
1651         val &= ~TRANS_INTERLACE_MASK;
1652         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1653                 if (HAS_PCH_IBX(dev_priv) &&
1654                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
1655                         val |= TRANS_LEGACY_INTERLACED_ILK;
1656                 else
1657                         val |= TRANS_INTERLACED;
1658         else
1659                 val |= TRANS_PROGRESSIVE;
1660
1661         I915_WRITE(reg, val | TRANS_ENABLE);
1662         if (intel_wait_for_register(dev_priv,
1663                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1664                                     100))
1665                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1666 }
1667
1668 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1669                                       enum transcoder cpu_transcoder)
1670 {
1671         u32 val, pipeconf_val;
1672
1673         /* FDI must be feeding us bits for PCH ports */
1674         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1675         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1676
1677         /* Workaround: set timing override bit. */
1678         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1679         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1680         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1681
1682         val = TRANS_ENABLE;
1683         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1684
1685         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1686             PIPECONF_INTERLACED_ILK)
1687                 val |= TRANS_INTERLACED;
1688         else
1689                 val |= TRANS_PROGRESSIVE;
1690
1691         I915_WRITE(LPT_TRANSCONF, val);
1692         if (intel_wait_for_register(dev_priv,
1693                                     LPT_TRANSCONF,
1694                                     TRANS_STATE_ENABLE,
1695                                     TRANS_STATE_ENABLE,
1696                                     100))
1697                 DRM_ERROR("Failed to enable PCH transcoder\n");
1698 }
1699
1700 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1701                                             enum pipe pipe)
1702 {
1703         i915_reg_t reg;
1704         u32 val;
1705
1706         /* FDI relies on the transcoder */
1707         assert_fdi_tx_disabled(dev_priv, pipe);
1708         assert_fdi_rx_disabled(dev_priv, pipe);
1709
1710         /* Ports must be off as well */
1711         assert_pch_ports_disabled(dev_priv, pipe);
1712
1713         reg = PCH_TRANSCONF(pipe);
1714         val = I915_READ(reg);
1715         val &= ~TRANS_ENABLE;
1716         I915_WRITE(reg, val);
1717         /* wait for PCH transcoder off, transcoder state */
1718         if (intel_wait_for_register(dev_priv,
1719                                     reg, TRANS_STATE_ENABLE, 0,
1720                                     50))
1721                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1722
1723         if (HAS_PCH_CPT(dev_priv)) {
1724                 /* Workaround: Clear the timing override chicken bit again. */
1725                 reg = TRANS_CHICKEN2(pipe);
1726                 val = I915_READ(reg);
1727                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1728                 I915_WRITE(reg, val);
1729         }
1730 }
1731
1732 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1733 {
1734         u32 val;
1735
1736         val = I915_READ(LPT_TRANSCONF);
1737         val &= ~TRANS_ENABLE;
1738         I915_WRITE(LPT_TRANSCONF, val);
1739         /* wait for PCH transcoder off, transcoder state */
1740         if (intel_wait_for_register(dev_priv,
1741                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1742                                     50))
1743                 DRM_ERROR("Failed to disable PCH transcoder\n");
1744
1745         /* Workaround: clear timing override bit. */
1746         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1747         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1748         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1749 }
1750
1751 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1752 {
1753         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1754
1755         if (HAS_PCH_LPT(dev_priv))
1756                 return PIPE_A;
1757         else
1758                 return crtc->pipe;
1759 }
1760
1761 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1762 {
1763         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1764         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1765         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1766         enum pipe pipe = crtc->pipe;
1767         i915_reg_t reg;
1768         u32 val;
1769
1770         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1771
1772         assert_planes_disabled(crtc);
1773
1774         /*
1775          * A pipe without a PLL won't actually be able to drive bits from
1776          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1777          * need the check.
1778          */
1779         if (HAS_GMCH_DISPLAY(dev_priv)) {
1780                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1781                         assert_dsi_pll_enabled(dev_priv);
1782                 else
1783                         assert_pll_enabled(dev_priv, pipe);
1784         } else {
1785                 if (new_crtc_state->has_pch_encoder) {
1786                         /* if driving the PCH, we need FDI enabled */
1787                         assert_fdi_rx_pll_enabled(dev_priv,
1788                                                   intel_crtc_pch_transcoder(crtc));
1789                         assert_fdi_tx_pll_enabled(dev_priv,
1790                                                   (enum pipe) cpu_transcoder);
1791                 }
1792                 /* FIXME: assert CPU port conditions for SNB+ */
1793         }
1794
1795         reg = PIPECONF(cpu_transcoder);
1796         val = I915_READ(reg);
1797         if (val & PIPECONF_ENABLE) {
1798                 /* we keep both pipes enabled on 830 */
1799                 WARN_ON(!IS_I830(dev_priv));
1800                 return;
1801         }
1802
1803         I915_WRITE(reg, val | PIPECONF_ENABLE);
1804         POSTING_READ(reg);
1805
1806         /*
1807          * Until the pipe starts PIPEDSL reads will return a stale value,
1808          * which causes an apparent vblank timestamp jump when PIPEDSL
1809          * resets to its proper value. That also messes up the frame count
1810          * when it's derived from the timestamps. So let's wait for the
1811          * pipe to start properly before we call drm_crtc_vblank_on()
1812          */
1813         if (dev_priv->drm.max_vblank_count == 0)
1814                 intel_wait_for_pipe_scanline_moving(crtc);
1815 }
1816
1817 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1818 {
1819         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1820         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1821         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1822         enum pipe pipe = crtc->pipe;
1823         i915_reg_t reg;
1824         u32 val;
1825
1826         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1827
1828         /*
1829          * Make sure planes won't keep trying to pump pixels to us,
1830          * or we might hang the display.
1831          */
1832         assert_planes_disabled(crtc);
1833
1834         reg = PIPECONF(cpu_transcoder);
1835         val = I915_READ(reg);
1836         if ((val & PIPECONF_ENABLE) == 0)
1837                 return;
1838
1839         /*
1840          * Double wide has implications for planes
1841          * so best keep it disabled when not needed.
1842          */
1843         if (old_crtc_state->double_wide)
1844                 val &= ~PIPECONF_DOUBLE_WIDE;
1845
1846         /* Don't disable pipe or pipe PLLs if needed */
1847         if (!IS_I830(dev_priv))
1848                 val &= ~PIPECONF_ENABLE;
1849
1850         I915_WRITE(reg, val);
1851         if ((val & PIPECONF_ENABLE) == 0)
1852                 intel_wait_for_pipe_off(old_crtc_state);
1853 }
1854
1855 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1856 {
1857         return IS_GEN(dev_priv, 2) ? 2048 : 4096;
1858 }
1859
1860 static unsigned int
1861 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1862 {
1863         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1864         unsigned int cpp = fb->format->cpp[color_plane];
1865
1866         switch (fb->modifier) {
1867         case DRM_FORMAT_MOD_LINEAR:
1868                 return cpp;
1869         case I915_FORMAT_MOD_X_TILED:
1870                 if (IS_GEN(dev_priv, 2))
1871                         return 128;
1872                 else
1873                         return 512;
1874         case I915_FORMAT_MOD_Y_TILED_CCS:
1875                 if (color_plane == 1)
1876                         return 128;
1877                 /* fall through */
1878         case I915_FORMAT_MOD_Y_TILED:
1879                 if (IS_GEN(dev_priv, 2) || HAS_128_BYTE_Y_TILING(dev_priv))
1880                         return 128;
1881                 else
1882                         return 512;
1883         case I915_FORMAT_MOD_Yf_TILED_CCS:
1884                 if (color_plane == 1)
1885                         return 128;
1886                 /* fall through */
1887         case I915_FORMAT_MOD_Yf_TILED:
1888                 switch (cpp) {
1889                 case 1:
1890                         return 64;
1891                 case 2:
1892                 case 4:
1893                         return 128;
1894                 case 8:
1895                 case 16:
1896                         return 256;
1897                 default:
1898                         MISSING_CASE(cpp);
1899                         return cpp;
1900                 }
1901                 break;
1902         default:
1903                 MISSING_CASE(fb->modifier);
1904                 return cpp;
1905         }
1906 }
1907
1908 static unsigned int
1909 intel_tile_height(const struct drm_framebuffer *fb, int color_plane)
1910 {
1911         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1912                 return 1;
1913         else
1914                 return intel_tile_size(to_i915(fb->dev)) /
1915                         intel_tile_width_bytes(fb, color_plane);
1916 }
1917
1918 /* Return the tile dimensions in pixel units */
1919 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1920                             unsigned int *tile_width,
1921                             unsigned int *tile_height)
1922 {
1923         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1924         unsigned int cpp = fb->format->cpp[color_plane];
1925
1926         *tile_width = tile_width_bytes / cpp;
1927         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1928 }
1929
1930 unsigned int
1931 intel_fb_align_height(const struct drm_framebuffer *fb,
1932                       int color_plane, unsigned int height)
1933 {
1934         unsigned int tile_height = intel_tile_height(fb, color_plane);
1935
1936         return ALIGN(height, tile_height);
1937 }
1938
1939 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1940 {
1941         unsigned int size = 0;
1942         int i;
1943
1944         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1945                 size += rot_info->plane[i].width * rot_info->plane[i].height;
1946
1947         return size;
1948 }
1949
1950 static void
1951 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
1952                         const struct drm_framebuffer *fb,
1953                         unsigned int rotation)
1954 {
1955         view->type = I915_GGTT_VIEW_NORMAL;
1956         if (drm_rotation_90_or_270(rotation)) {
1957                 view->type = I915_GGTT_VIEW_ROTATED;
1958                 view->rotated = to_intel_framebuffer(fb)->rot_info;
1959         }
1960 }
1961
1962 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
1963 {
1964         if (IS_I830(dev_priv))
1965                 return 16 * 1024;
1966         else if (IS_I85X(dev_priv))
1967                 return 256;
1968         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
1969                 return 32;
1970         else
1971                 return 4 * 1024;
1972 }
1973
1974 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
1975 {
1976         if (INTEL_GEN(dev_priv) >= 9)
1977                 return 256 * 1024;
1978         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
1979                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
1980                 return 128 * 1024;
1981         else if (INTEL_GEN(dev_priv) >= 4)
1982                 return 4 * 1024;
1983         else
1984                 return 0;
1985 }
1986
1987 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
1988                                          int color_plane)
1989 {
1990         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1991
1992         /* AUX_DIST needs only 4K alignment */
1993         if (color_plane == 1)
1994                 return 4096;
1995
1996         switch (fb->modifier) {
1997         case DRM_FORMAT_MOD_LINEAR:
1998                 return intel_linear_alignment(dev_priv);
1999         case I915_FORMAT_MOD_X_TILED:
2000                 if (INTEL_GEN(dev_priv) >= 9)
2001                         return 256 * 1024;
2002                 return 0;
2003         case I915_FORMAT_MOD_Y_TILED_CCS:
2004         case I915_FORMAT_MOD_Yf_TILED_CCS:
2005         case I915_FORMAT_MOD_Y_TILED:
2006         case I915_FORMAT_MOD_Yf_TILED:
2007                 return 1 * 1024 * 1024;
2008         default:
2009                 MISSING_CASE(fb->modifier);
2010                 return 0;
2011         }
2012 }
2013
2014 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2015 {
2016         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2017         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2018
2019         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2020 }
2021
2022 struct i915_vma *
2023 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2024                            const struct i915_ggtt_view *view,
2025                            bool uses_fence,
2026                            unsigned long *out_flags)
2027 {
2028         struct drm_device *dev = fb->dev;
2029         struct drm_i915_private *dev_priv = to_i915(dev);
2030         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2031         intel_wakeref_t wakeref;
2032         struct i915_vma *vma;
2033         unsigned int pinctl;
2034         u32 alignment;
2035
2036         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2037
2038         alignment = intel_surf_alignment(fb, 0);
2039
2040         /* Note that the w/a also requires 64 PTE of padding following the
2041          * bo. We currently fill all unused PTE with the shadow page and so
2042          * we should always have valid PTE following the scanout preventing
2043          * the VT-d warning.
2044          */
2045         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2046                 alignment = 256 * 1024;
2047
2048         /*
2049          * Global gtt pte registers are special registers which actually forward
2050          * writes to a chunk of system memory. Which means that there is no risk
2051          * that the register values disappear as soon as we call
2052          * intel_runtime_pm_put(), so it is correct to wrap only the
2053          * pin/unpin/fence and not more.
2054          */
2055         wakeref = intel_runtime_pm_get(dev_priv);
2056
2057         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2058
2059         pinctl = 0;
2060
2061         /* Valleyview is definitely limited to scanning out the first
2062          * 512MiB. Lets presume this behaviour was inherited from the
2063          * g4x display engine and that all earlier gen are similarly
2064          * limited. Testing suggests that it is a little more
2065          * complicated than this. For example, Cherryview appears quite
2066          * happy to scanout from anywhere within its global aperture.
2067          */
2068         if (HAS_GMCH_DISPLAY(dev_priv))
2069                 pinctl |= PIN_MAPPABLE;
2070
2071         vma = i915_gem_object_pin_to_display_plane(obj,
2072                                                    alignment, view, pinctl);
2073         if (IS_ERR(vma))
2074                 goto err;
2075
2076         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2077                 int ret;
2078
2079                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2080                  * fence, whereas 965+ only requires a fence if using
2081                  * framebuffer compression.  For simplicity, we always, when
2082                  * possible, install a fence as the cost is not that onerous.
2083                  *
2084                  * If we fail to fence the tiled scanout, then either the
2085                  * modeset will reject the change (which is highly unlikely as
2086                  * the affected systems, all but one, do not have unmappable
2087                  * space) or we will not be able to enable full powersaving
2088                  * techniques (also likely not to apply due to various limits
2089                  * FBC and the like impose on the size of the buffer, which
2090                  * presumably we violated anyway with this unmappable buffer).
2091                  * Anyway, it is presumably better to stumble onwards with
2092                  * something and try to run the system in a "less than optimal"
2093                  * mode that matches the user configuration.
2094                  */
2095                 ret = i915_vma_pin_fence(vma);
2096                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2097                         i915_gem_object_unpin_from_display_plane(vma);
2098                         vma = ERR_PTR(ret);
2099                         goto err;
2100                 }
2101
2102                 if (ret == 0 && vma->fence)
2103                         *out_flags |= PLANE_HAS_FENCE;
2104         }
2105
2106         i915_vma_get(vma);
2107 err:
2108         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2109
2110         intel_runtime_pm_put(dev_priv, wakeref);
2111         return vma;
2112 }
2113
2114 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2115 {
2116         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2117
2118         if (flags & PLANE_HAS_FENCE)
2119                 i915_vma_unpin_fence(vma);
2120         i915_gem_object_unpin_from_display_plane(vma);
2121         i915_vma_put(vma);
2122 }
2123
2124 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2125                           unsigned int rotation)
2126 {
2127         if (drm_rotation_90_or_270(rotation))
2128                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2129         else
2130                 return fb->pitches[color_plane];
2131 }
2132
2133 /*
2134  * Convert the x/y offsets into a linear offset.
2135  * Only valid with 0/180 degree rotation, which is fine since linear
2136  * offset is only used with linear buffers on pre-hsw and tiled buffers
2137  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2138  */
2139 u32 intel_fb_xy_to_linear(int x, int y,
2140                           const struct intel_plane_state *state,
2141                           int color_plane)
2142 {
2143         const struct drm_framebuffer *fb = state->base.fb;
2144         unsigned int cpp = fb->format->cpp[color_plane];
2145         unsigned int pitch = state->color_plane[color_plane].stride;
2146
2147         return y * pitch + x * cpp;
2148 }
2149
2150 /*
2151  * Add the x/y offsets derived from fb->offsets[] to the user
2152  * specified plane src x/y offsets. The resulting x/y offsets
2153  * specify the start of scanout from the beginning of the gtt mapping.
2154  */
2155 void intel_add_fb_offsets(int *x, int *y,
2156                           const struct intel_plane_state *state,
2157                           int color_plane)
2158
2159 {
2160         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2161         unsigned int rotation = state->base.rotation;
2162
2163         if (drm_rotation_90_or_270(rotation)) {
2164                 *x += intel_fb->rotated[color_plane].x;
2165                 *y += intel_fb->rotated[color_plane].y;
2166         } else {
2167                 *x += intel_fb->normal[color_plane].x;
2168                 *y += intel_fb->normal[color_plane].y;
2169         }
2170 }
2171
2172 static u32 intel_adjust_tile_offset(int *x, int *y,
2173                                     unsigned int tile_width,
2174                                     unsigned int tile_height,
2175                                     unsigned int tile_size,
2176                                     unsigned int pitch_tiles,
2177                                     u32 old_offset,
2178                                     u32 new_offset)
2179 {
2180         unsigned int pitch_pixels = pitch_tiles * tile_width;
2181         unsigned int tiles;
2182
2183         WARN_ON(old_offset & (tile_size - 1));
2184         WARN_ON(new_offset & (tile_size - 1));
2185         WARN_ON(new_offset > old_offset);
2186
2187         tiles = (old_offset - new_offset) / tile_size;
2188
2189         *y += tiles / pitch_tiles * tile_height;
2190         *x += tiles % pitch_tiles * tile_width;
2191
2192         /* minimize x in case it got needlessly big */
2193         *y += *x / pitch_pixels * tile_height;
2194         *x %= pitch_pixels;
2195
2196         return new_offset;
2197 }
2198
2199 static bool is_surface_linear(u64 modifier, int color_plane)
2200 {
2201         return modifier == DRM_FORMAT_MOD_LINEAR;
2202 }
2203
2204 static u32 intel_adjust_aligned_offset(int *x, int *y,
2205                                        const struct drm_framebuffer *fb,
2206                                        int color_plane,
2207                                        unsigned int rotation,
2208                                        unsigned int pitch,
2209                                        u32 old_offset, u32 new_offset)
2210 {
2211         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2212         unsigned int cpp = fb->format->cpp[color_plane];
2213
2214         WARN_ON(new_offset > old_offset);
2215
2216         if (!is_surface_linear(fb->modifier, color_plane)) {
2217                 unsigned int tile_size, tile_width, tile_height;
2218                 unsigned int pitch_tiles;
2219
2220                 tile_size = intel_tile_size(dev_priv);
2221                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2222
2223                 if (drm_rotation_90_or_270(rotation)) {
2224                         pitch_tiles = pitch / tile_height;
2225                         swap(tile_width, tile_height);
2226                 } else {
2227                         pitch_tiles = pitch / (tile_width * cpp);
2228                 }
2229
2230                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2231                                          tile_size, pitch_tiles,
2232                                          old_offset, new_offset);
2233         } else {
2234                 old_offset += *y * pitch + *x * cpp;
2235
2236                 *y = (old_offset - new_offset) / pitch;
2237                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2238         }
2239
2240         return new_offset;
2241 }
2242
2243 /*
2244  * Adjust the tile offset by moving the difference into
2245  * the x/y offsets.
2246  */
2247 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2248                                              const struct intel_plane_state *state,
2249                                              int color_plane,
2250                                              u32 old_offset, u32 new_offset)
2251 {
2252         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2253                                            state->base.rotation,
2254                                            state->color_plane[color_plane].stride,
2255                                            old_offset, new_offset);
2256 }
2257
2258 /*
2259  * Computes the aligned offset to the base tile and adjusts
2260  * x, y. bytes per pixel is assumed to be a power-of-two.
2261  *
2262  * In the 90/270 rotated case, x and y are assumed
2263  * to be already rotated to match the rotated GTT view, and
2264  * pitch is the tile_height aligned framebuffer height.
2265  *
2266  * This function is used when computing the derived information
2267  * under intel_framebuffer, so using any of that information
2268  * here is not allowed. Anything under drm_framebuffer can be
2269  * used. This is why the user has to pass in the pitch since it
2270  * is specified in the rotated orientation.
2271  */
2272 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2273                                         int *x, int *y,
2274                                         const struct drm_framebuffer *fb,
2275                                         int color_plane,
2276                                         unsigned int pitch,
2277                                         unsigned int rotation,
2278                                         u32 alignment)
2279 {
2280         unsigned int cpp = fb->format->cpp[color_plane];
2281         u32 offset, offset_aligned;
2282
2283         if (alignment)
2284                 alignment--;
2285
2286         if (!is_surface_linear(fb->modifier, color_plane)) {
2287                 unsigned int tile_size, tile_width, tile_height;
2288                 unsigned int tile_rows, tiles, pitch_tiles;
2289
2290                 tile_size = intel_tile_size(dev_priv);
2291                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2292
2293                 if (drm_rotation_90_or_270(rotation)) {
2294                         pitch_tiles = pitch / tile_height;
2295                         swap(tile_width, tile_height);
2296                 } else {
2297                         pitch_tiles = pitch / (tile_width * cpp);
2298                 }
2299
2300                 tile_rows = *y / tile_height;
2301                 *y %= tile_height;
2302
2303                 tiles = *x / tile_width;
2304                 *x %= tile_width;
2305
2306                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2307                 offset_aligned = offset & ~alignment;
2308
2309                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2310                                          tile_size, pitch_tiles,
2311                                          offset, offset_aligned);
2312         } else {
2313                 offset = *y * pitch + *x * cpp;
2314                 offset_aligned = offset & ~alignment;
2315
2316                 *y = (offset & alignment) / pitch;
2317                 *x = ((offset & alignment) - *y * pitch) / cpp;
2318         }
2319
2320         return offset_aligned;
2321 }
2322
2323 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2324                                               const struct intel_plane_state *state,
2325                                               int color_plane)
2326 {
2327         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2328         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2329         const struct drm_framebuffer *fb = state->base.fb;
2330         unsigned int rotation = state->base.rotation;
2331         int pitch = state->color_plane[color_plane].stride;
2332         u32 alignment;
2333
2334         if (intel_plane->id == PLANE_CURSOR)
2335                 alignment = intel_cursor_alignment(dev_priv);
2336         else
2337                 alignment = intel_surf_alignment(fb, color_plane);
2338
2339         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2340                                             pitch, rotation, alignment);
2341 }
2342
2343 /* Convert the fb->offset[] into x/y offsets */
2344 static int intel_fb_offset_to_xy(int *x, int *y,
2345                                  const struct drm_framebuffer *fb,
2346                                  int color_plane)
2347 {
2348         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2349         unsigned int height;
2350
2351         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2352             fb->offsets[color_plane] % intel_tile_size(dev_priv)) {
2353                 DRM_DEBUG_KMS("Misaligned offset 0x%08x for color plane %d\n",
2354                               fb->offsets[color_plane], color_plane);
2355                 return -EINVAL;
2356         }
2357
2358         height = drm_framebuffer_plane_height(fb->height, fb, color_plane);
2359         height = ALIGN(height, intel_tile_height(fb, color_plane));
2360
2361         /* Catch potential overflows early */
2362         if (add_overflows_t(u32, mul_u32_u32(height, fb->pitches[color_plane]),
2363                             fb->offsets[color_plane])) {
2364                 DRM_DEBUG_KMS("Bad offset 0x%08x or pitch %d for color plane %d\n",
2365                               fb->offsets[color_plane], fb->pitches[color_plane],
2366                               color_plane);
2367                 return -ERANGE;
2368         }
2369
2370         *x = 0;
2371         *y = 0;
2372
2373         intel_adjust_aligned_offset(x, y,
2374                                     fb, color_plane, DRM_MODE_ROTATE_0,
2375                                     fb->pitches[color_plane],
2376                                     fb->offsets[color_plane], 0);
2377
2378         return 0;
2379 }
2380
2381 static unsigned int intel_fb_modifier_to_tiling(u64 fb_modifier)
2382 {
2383         switch (fb_modifier) {
2384         case I915_FORMAT_MOD_X_TILED:
2385                 return I915_TILING_X;
2386         case I915_FORMAT_MOD_Y_TILED:
2387         case I915_FORMAT_MOD_Y_TILED_CCS:
2388                 return I915_TILING_Y;
2389         default:
2390                 return I915_TILING_NONE;
2391         }
2392 }
2393
2394 /*
2395  * From the Sky Lake PRM:
2396  * "The Color Control Surface (CCS) contains the compression status of
2397  *  the cache-line pairs. The compression state of the cache-line pair
2398  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2399  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2400  *  cache-line-pairs. CCS is always Y tiled."
2401  *
2402  * Since cache line pairs refers to horizontally adjacent cache lines,
2403  * each cache line in the CCS corresponds to an area of 32x16 cache
2404  * lines on the main surface. Since each pixel is 4 bytes, this gives
2405  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2406  * main surface.
2407  */
2408 static const struct drm_format_info ccs_formats[] = {
2409         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2410         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2411         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2412         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2413 };
2414
2415 static const struct drm_format_info *
2416 lookup_format_info(const struct drm_format_info formats[],
2417                    int num_formats, u32 format)
2418 {
2419         int i;
2420
2421         for (i = 0; i < num_formats; i++) {
2422                 if (formats[i].format == format)
2423                         return &formats[i];
2424         }
2425
2426         return NULL;
2427 }
2428
2429 static const struct drm_format_info *
2430 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2431 {
2432         switch (cmd->modifier[0]) {
2433         case I915_FORMAT_MOD_Y_TILED_CCS:
2434         case I915_FORMAT_MOD_Yf_TILED_CCS:
2435                 return lookup_format_info(ccs_formats,
2436                                           ARRAY_SIZE(ccs_formats),
2437                                           cmd->pixel_format);
2438         default:
2439                 return NULL;
2440         }
2441 }
2442
2443 bool is_ccs_modifier(u64 modifier)
2444 {
2445         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2446                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2447 }
2448
2449 static int
2450 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2451                    struct drm_framebuffer *fb)
2452 {
2453         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2454         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2455         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2456         u32 gtt_offset_rotated = 0;
2457         unsigned int max_size = 0;
2458         int i, num_planes = fb->format->num_planes;
2459         unsigned int tile_size = intel_tile_size(dev_priv);
2460
2461         for (i = 0; i < num_planes; i++) {
2462                 unsigned int width, height;
2463                 unsigned int cpp, size;
2464                 u32 offset;
2465                 int x, y;
2466                 int ret;
2467
2468                 cpp = fb->format->cpp[i];
2469                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2470                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2471
2472                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2473                 if (ret) {
2474                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2475                                       i, fb->offsets[i]);
2476                         return ret;
2477                 }
2478
2479                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2480                         int hsub = fb->format->hsub;
2481                         int vsub = fb->format->vsub;
2482                         int tile_width, tile_height;
2483                         int main_x, main_y;
2484                         int ccs_x, ccs_y;
2485
2486                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2487                         tile_width *= hsub;
2488                         tile_height *= vsub;
2489
2490                         ccs_x = (x * hsub) % tile_width;
2491                         ccs_y = (y * vsub) % tile_height;
2492                         main_x = intel_fb->normal[0].x % tile_width;
2493                         main_y = intel_fb->normal[0].y % tile_height;
2494
2495                         /*
2496                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2497                          * x/y offsets must match between CCS and the main surface.
2498                          */
2499                         if (main_x != ccs_x || main_y != ccs_y) {
2500                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2501                                               main_x, main_y,
2502                                               ccs_x, ccs_y,
2503                                               intel_fb->normal[0].x,
2504                                               intel_fb->normal[0].y,
2505                                               x, y);
2506                                 return -EINVAL;
2507                         }
2508                 }
2509
2510                 /*
2511                  * The fence (if used) is aligned to the start of the object
2512                  * so having the framebuffer wrap around across the edge of the
2513                  * fenced region doesn't really work. We have no API to configure
2514                  * the fence start offset within the object (nor could we probably
2515                  * on gen2/3). So it's just easier if we just require that the
2516                  * fb layout agrees with the fence layout. We already check that the
2517                  * fb stride matches the fence stride elsewhere.
2518                  */
2519                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2520                     (x + width) * cpp > fb->pitches[i]) {
2521                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2522                                       i, fb->offsets[i]);
2523                         return -EINVAL;
2524                 }
2525
2526                 /*
2527                  * First pixel of the framebuffer from
2528                  * the start of the normal gtt mapping.
2529                  */
2530                 intel_fb->normal[i].x = x;
2531                 intel_fb->normal[i].y = y;
2532
2533                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2534                                                       fb->pitches[i],
2535                                                       DRM_MODE_ROTATE_0,
2536                                                       tile_size);
2537                 offset /= tile_size;
2538
2539                 if (!is_surface_linear(fb->modifier, i)) {
2540                         unsigned int tile_width, tile_height;
2541                         unsigned int pitch_tiles;
2542                         struct drm_rect r;
2543
2544                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2545
2546                         rot_info->plane[i].offset = offset;
2547                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2548                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2549                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2550
2551                         intel_fb->rotated[i].pitch =
2552                                 rot_info->plane[i].height * tile_height;
2553
2554                         /* how many tiles does this plane need */
2555                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2556                         /*
2557                          * If the plane isn't horizontally tile aligned,
2558                          * we need one more tile.
2559                          */
2560                         if (x != 0)
2561                                 size++;
2562
2563                         /* rotate the x/y offsets to match the GTT view */
2564                         r.x1 = x;
2565                         r.y1 = y;
2566                         r.x2 = x + width;
2567                         r.y2 = y + height;
2568                         drm_rect_rotate(&r,
2569                                         rot_info->plane[i].width * tile_width,
2570                                         rot_info->plane[i].height * tile_height,
2571                                         DRM_MODE_ROTATE_270);
2572                         x = r.x1;
2573                         y = r.y1;
2574
2575                         /* rotate the tile dimensions to match the GTT view */
2576                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2577                         swap(tile_width, tile_height);
2578
2579                         /*
2580                          * We only keep the x/y offsets, so push all of the
2581                          * gtt offset into the x/y offsets.
2582                          */
2583                         intel_adjust_tile_offset(&x, &y,
2584                                                  tile_width, tile_height,
2585                                                  tile_size, pitch_tiles,
2586                                                  gtt_offset_rotated * tile_size, 0);
2587
2588                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2589
2590                         /*
2591                          * First pixel of the framebuffer from
2592                          * the start of the rotated gtt mapping.
2593                          */
2594                         intel_fb->rotated[i].x = x;
2595                         intel_fb->rotated[i].y = y;
2596                 } else {
2597                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2598                                             x * cpp, tile_size);
2599                 }
2600
2601                 /* how many tiles in total needed in the bo */
2602                 max_size = max(max_size, offset + size);
2603         }
2604
2605         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2606                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2607                               mul_u32_u32(max_size, tile_size), obj->base.size);
2608                 return -EINVAL;
2609         }
2610
2611         return 0;
2612 }
2613
2614 static int i9xx_format_to_fourcc(int format)
2615 {
2616         switch (format) {
2617         case DISPPLANE_8BPP:
2618                 return DRM_FORMAT_C8;
2619         case DISPPLANE_BGRX555:
2620                 return DRM_FORMAT_XRGB1555;
2621         case DISPPLANE_BGRX565:
2622                 return DRM_FORMAT_RGB565;
2623         default:
2624         case DISPPLANE_BGRX888:
2625                 return DRM_FORMAT_XRGB8888;
2626         case DISPPLANE_RGBX888:
2627                 return DRM_FORMAT_XBGR8888;
2628         case DISPPLANE_BGRX101010:
2629                 return DRM_FORMAT_XRGB2101010;
2630         case DISPPLANE_RGBX101010:
2631                 return DRM_FORMAT_XBGR2101010;
2632         }
2633 }
2634
2635 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2636 {
2637         switch (format) {
2638         case PLANE_CTL_FORMAT_RGB_565:
2639                 return DRM_FORMAT_RGB565;
2640         case PLANE_CTL_FORMAT_NV12:
2641                 return DRM_FORMAT_NV12;
2642         default:
2643         case PLANE_CTL_FORMAT_XRGB_8888:
2644                 if (rgb_order) {
2645                         if (alpha)
2646                                 return DRM_FORMAT_ABGR8888;
2647                         else
2648                                 return DRM_FORMAT_XBGR8888;
2649                 } else {
2650                         if (alpha)
2651                                 return DRM_FORMAT_ARGB8888;
2652                         else
2653                                 return DRM_FORMAT_XRGB8888;
2654                 }
2655         case PLANE_CTL_FORMAT_XRGB_2101010:
2656                 if (rgb_order)
2657                         return DRM_FORMAT_XBGR2101010;
2658                 else
2659                         return DRM_FORMAT_XRGB2101010;
2660         }
2661 }
2662
2663 static bool
2664 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2665                               struct intel_initial_plane_config *plane_config)
2666 {
2667         struct drm_device *dev = crtc->base.dev;
2668         struct drm_i915_private *dev_priv = to_i915(dev);
2669         struct drm_i915_gem_object *obj = NULL;
2670         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2671         struct drm_framebuffer *fb = &plane_config->fb->base;
2672         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2673         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2674                                     PAGE_SIZE);
2675
2676         size_aligned -= base_aligned;
2677
2678         if (plane_config->size == 0)
2679                 return false;
2680
2681         /* If the FB is too big, just don't use it since fbdev is not very
2682          * important and we should probably use that space with FBC or other
2683          * features. */
2684         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2685                 return false;
2686
2687         switch (fb->modifier) {
2688         case DRM_FORMAT_MOD_LINEAR:
2689         case I915_FORMAT_MOD_X_TILED:
2690         case I915_FORMAT_MOD_Y_TILED:
2691                 break;
2692         default:
2693                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
2694                                  fb->modifier);
2695                 return false;
2696         }
2697
2698         mutex_lock(&dev->struct_mutex);
2699         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2700                                                              base_aligned,
2701                                                              base_aligned,
2702                                                              size_aligned);
2703         mutex_unlock(&dev->struct_mutex);
2704         if (!obj)
2705                 return false;
2706
2707         switch (plane_config->tiling) {
2708         case I915_TILING_NONE:
2709                 break;
2710         case I915_TILING_X:
2711         case I915_TILING_Y:
2712                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
2713                 break;
2714         default:
2715                 MISSING_CASE(plane_config->tiling);
2716                 return false;
2717         }
2718
2719         mode_cmd.pixel_format = fb->format->format;
2720         mode_cmd.width = fb->width;
2721         mode_cmd.height = fb->height;
2722         mode_cmd.pitches[0] = fb->pitches[0];
2723         mode_cmd.modifier[0] = fb->modifier;
2724         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2725
2726         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2727                 DRM_DEBUG_KMS("intel fb init failed\n");
2728                 goto out_unref_obj;
2729         }
2730
2731
2732         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2733         return true;
2734
2735 out_unref_obj:
2736         i915_gem_object_put(obj);
2737         return false;
2738 }
2739
2740 static void
2741 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2742                         struct intel_plane_state *plane_state,
2743                         bool visible)
2744 {
2745         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2746
2747         plane_state->base.visible = visible;
2748
2749         if (visible)
2750                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2751         else
2752                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2753 }
2754
2755 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
2756 {
2757         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2758         struct drm_plane *plane;
2759
2760         /*
2761          * Active_planes aliases if multiple "primary" or cursor planes
2762          * have been used on the same (or wrong) pipe. plane_mask uses
2763          * unique ids, hence we can use that to reconstruct active_planes.
2764          */
2765         crtc_state->active_planes = 0;
2766
2767         drm_for_each_plane_mask(plane, &dev_priv->drm,
2768                                 crtc_state->base.plane_mask)
2769                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
2770 }
2771
2772 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2773                                          struct intel_plane *plane)
2774 {
2775         struct intel_crtc_state *crtc_state =
2776                 to_intel_crtc_state(crtc->base.state);
2777         struct intel_plane_state *plane_state =
2778                 to_intel_plane_state(plane->base.state);
2779
2780         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
2781                       plane->base.base.id, plane->base.name,
2782                       crtc->base.base.id, crtc->base.name);
2783
2784         intel_set_plane_visible(crtc_state, plane_state, false);
2785         fixup_active_planes(crtc_state);
2786
2787         if (plane->id == PLANE_PRIMARY)
2788                 intel_pre_disable_primary_noatomic(&crtc->base);
2789
2790         trace_intel_disable_plane(&plane->base, crtc);
2791         plane->disable_plane(plane, crtc_state);
2792 }
2793
2794 static void
2795 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2796                              struct intel_initial_plane_config *plane_config)
2797 {
2798         struct drm_device *dev = intel_crtc->base.dev;
2799         struct drm_i915_private *dev_priv = to_i915(dev);
2800         struct drm_crtc *c;
2801         struct drm_i915_gem_object *obj;
2802         struct drm_plane *primary = intel_crtc->base.primary;
2803         struct drm_plane_state *plane_state = primary->state;
2804         struct intel_plane *intel_plane = to_intel_plane(primary);
2805         struct intel_plane_state *intel_state =
2806                 to_intel_plane_state(plane_state);
2807         struct drm_framebuffer *fb;
2808
2809         if (!plane_config->fb)
2810                 return;
2811
2812         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2813                 fb = &plane_config->fb->base;
2814                 goto valid_fb;
2815         }
2816
2817         kfree(plane_config->fb);
2818
2819         /*
2820          * Failed to alloc the obj, check to see if we should share
2821          * an fb with another CRTC instead
2822          */
2823         for_each_crtc(dev, c) {
2824                 struct intel_plane_state *state;
2825
2826                 if (c == &intel_crtc->base)
2827                         continue;
2828
2829                 if (!to_intel_crtc(c)->active)
2830                         continue;
2831
2832                 state = to_intel_plane_state(c->primary->state);
2833                 if (!state->vma)
2834                         continue;
2835
2836                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2837                         fb = state->base.fb;
2838                         drm_framebuffer_get(fb);
2839                         goto valid_fb;
2840                 }
2841         }
2842
2843         /*
2844          * We've failed to reconstruct the BIOS FB.  Current display state
2845          * indicates that the primary plane is visible, but has a NULL FB,
2846          * which will lead to problems later if we don't fix it up.  The
2847          * simplest solution is to just disable the primary plane now and
2848          * pretend the BIOS never had it enabled.
2849          */
2850         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2851
2852         return;
2853
2854 valid_fb:
2855         intel_state->base.rotation = plane_config->rotation;
2856         intel_fill_fb_ggtt_view(&intel_state->view, fb,
2857                                 intel_state->base.rotation);
2858         intel_state->color_plane[0].stride =
2859                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
2860
2861         mutex_lock(&dev->struct_mutex);
2862         intel_state->vma =
2863                 intel_pin_and_fence_fb_obj(fb,
2864                                            &intel_state->view,
2865                                            intel_plane_uses_fence(intel_state),
2866                                            &intel_state->flags);
2867         mutex_unlock(&dev->struct_mutex);
2868         if (IS_ERR(intel_state->vma)) {
2869                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2870                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2871
2872                 intel_state->vma = NULL;
2873                 drm_framebuffer_put(fb);
2874                 return;
2875         }
2876
2877         obj = intel_fb_obj(fb);
2878         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2879
2880         plane_state->src_x = 0;
2881         plane_state->src_y = 0;
2882         plane_state->src_w = fb->width << 16;
2883         plane_state->src_h = fb->height << 16;
2884
2885         plane_state->crtc_x = 0;
2886         plane_state->crtc_y = 0;
2887         plane_state->crtc_w = fb->width;
2888         plane_state->crtc_h = fb->height;
2889
2890         intel_state->base.src = drm_plane_state_src(plane_state);
2891         intel_state->base.dst = drm_plane_state_dest(plane_state);
2892
2893         if (i915_gem_object_is_tiled(obj))
2894                 dev_priv->preserve_bios_swizzle = true;
2895
2896         plane_state->fb = fb;
2897         plane_state->crtc = &intel_crtc->base;
2898
2899         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2900                   &obj->frontbuffer_bits);
2901 }
2902
2903 static int skl_max_plane_width(const struct drm_framebuffer *fb,
2904                                int color_plane,
2905                                unsigned int rotation)
2906 {
2907         int cpp = fb->format->cpp[color_plane];
2908
2909         switch (fb->modifier) {
2910         case DRM_FORMAT_MOD_LINEAR:
2911         case I915_FORMAT_MOD_X_TILED:
2912                 switch (cpp) {
2913                 case 8:
2914                         return 4096;
2915                 case 4:
2916                 case 2:
2917                 case 1:
2918                         return 8192;
2919                 default:
2920                         MISSING_CASE(cpp);
2921                         break;
2922                 }
2923                 break;
2924         case I915_FORMAT_MOD_Y_TILED_CCS:
2925         case I915_FORMAT_MOD_Yf_TILED_CCS:
2926                 /* FIXME AUX plane? */
2927         case I915_FORMAT_MOD_Y_TILED:
2928         case I915_FORMAT_MOD_Yf_TILED:
2929                 switch (cpp) {
2930                 case 8:
2931                         return 2048;
2932                 case 4:
2933                         return 4096;
2934                 case 2:
2935                 case 1:
2936                         return 8192;
2937                 default:
2938                         MISSING_CASE(cpp);
2939                         break;
2940                 }
2941                 break;
2942         default:
2943                 MISSING_CASE(fb->modifier);
2944         }
2945
2946         return 2048;
2947 }
2948
2949 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2950                                            int main_x, int main_y, u32 main_offset)
2951 {
2952         const struct drm_framebuffer *fb = plane_state->base.fb;
2953         int hsub = fb->format->hsub;
2954         int vsub = fb->format->vsub;
2955         int aux_x = plane_state->color_plane[1].x;
2956         int aux_y = plane_state->color_plane[1].y;
2957         u32 aux_offset = plane_state->color_plane[1].offset;
2958         u32 alignment = intel_surf_alignment(fb, 1);
2959
2960         while (aux_offset >= main_offset && aux_y <= main_y) {
2961                 int x, y;
2962
2963                 if (aux_x == main_x && aux_y == main_y)
2964                         break;
2965
2966                 if (aux_offset == 0)
2967                         break;
2968
2969                 x = aux_x / hsub;
2970                 y = aux_y / vsub;
2971                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
2972                                                                aux_offset, aux_offset - alignment);
2973                 aux_x = x * hsub + aux_x % hsub;
2974                 aux_y = y * vsub + aux_y % vsub;
2975         }
2976
2977         if (aux_x != main_x || aux_y != main_y)
2978                 return false;
2979
2980         plane_state->color_plane[1].offset = aux_offset;
2981         plane_state->color_plane[1].x = aux_x;
2982         plane_state->color_plane[1].y = aux_y;
2983
2984         return true;
2985 }
2986
2987 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2988 {
2989         const struct drm_framebuffer *fb = plane_state->base.fb;
2990         unsigned int rotation = plane_state->base.rotation;
2991         int x = plane_state->base.src.x1 >> 16;
2992         int y = plane_state->base.src.y1 >> 16;
2993         int w = drm_rect_width(&plane_state->base.src) >> 16;
2994         int h = drm_rect_height(&plane_state->base.src) >> 16;
2995         int max_width = skl_max_plane_width(fb, 0, rotation);
2996         int max_height = 4096;
2997         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
2998
2999         if (w > max_width || h > max_height) {
3000                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3001                               w, h, max_width, max_height);
3002                 return -EINVAL;
3003         }
3004
3005         intel_add_fb_offsets(&x, &y, plane_state, 0);
3006         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3007         alignment = intel_surf_alignment(fb, 0);
3008
3009         /*
3010          * AUX surface offset is specified as the distance from the
3011          * main surface offset, and it must be non-negative. Make
3012          * sure that is what we will get.
3013          */
3014         if (offset > aux_offset)
3015                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3016                                                            offset, aux_offset & ~(alignment - 1));
3017
3018         /*
3019          * When using an X-tiled surface, the plane blows up
3020          * if the x offset + width exceed the stride.
3021          *
3022          * TODO: linear and Y-tiled seem fine, Yf untested,
3023          */
3024         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3025                 int cpp = fb->format->cpp[0];
3026
3027                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3028                         if (offset == 0) {
3029                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3030                                 return -EINVAL;
3031                         }
3032
3033                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3034                                                                    offset, offset - alignment);
3035                 }
3036         }
3037
3038         /*
3039          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3040          * they match with the main surface x/y offsets.
3041          */
3042         if (is_ccs_modifier(fb->modifier)) {
3043                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3044                         if (offset == 0)
3045                                 break;
3046
3047                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3048                                                                    offset, offset - alignment);
3049                 }
3050
3051                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3052                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3053                         return -EINVAL;
3054                 }
3055         }
3056
3057         plane_state->color_plane[0].offset = offset;
3058         plane_state->color_plane[0].x = x;
3059         plane_state->color_plane[0].y = y;
3060
3061         return 0;
3062 }
3063
3064 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3065 {
3066         const struct drm_framebuffer *fb = plane_state->base.fb;
3067         unsigned int rotation = plane_state->base.rotation;
3068         int max_width = skl_max_plane_width(fb, 1, rotation);
3069         int max_height = 4096;
3070         int x = plane_state->base.src.x1 >> 17;
3071         int y = plane_state->base.src.y1 >> 17;
3072         int w = drm_rect_width(&plane_state->base.src) >> 17;
3073         int h = drm_rect_height(&plane_state->base.src) >> 17;
3074         u32 offset;
3075
3076         intel_add_fb_offsets(&x, &y, plane_state, 1);
3077         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3078
3079         /* FIXME not quite sure how/if these apply to the chroma plane */
3080         if (w > max_width || h > max_height) {
3081                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3082                               w, h, max_width, max_height);
3083                 return -EINVAL;
3084         }
3085
3086         plane_state->color_plane[1].offset = offset;
3087         plane_state->color_plane[1].x = x;
3088         plane_state->color_plane[1].y = y;
3089
3090         return 0;
3091 }
3092
3093 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3094 {
3095         const struct drm_framebuffer *fb = plane_state->base.fb;
3096         int src_x = plane_state->base.src.x1 >> 16;
3097         int src_y = plane_state->base.src.y1 >> 16;
3098         int hsub = fb->format->hsub;
3099         int vsub = fb->format->vsub;
3100         int x = src_x / hsub;
3101         int y = src_y / vsub;
3102         u32 offset;
3103
3104         intel_add_fb_offsets(&x, &y, plane_state, 1);
3105         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3106
3107         plane_state->color_plane[1].offset = offset;
3108         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3109         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3110
3111         return 0;
3112 }
3113
3114 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3115 {
3116         const struct drm_framebuffer *fb = plane_state->base.fb;
3117         unsigned int rotation = plane_state->base.rotation;
3118         int ret;
3119
3120         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3121         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3122         plane_state->color_plane[1].stride = intel_fb_pitch(fb, 1, rotation);
3123
3124         ret = intel_plane_check_stride(plane_state);
3125         if (ret)
3126                 return ret;
3127
3128         if (!plane_state->base.visible)
3129                 return 0;
3130
3131         /* Rotate src coordinates to match rotated GTT view */
3132         if (drm_rotation_90_or_270(rotation))
3133                 drm_rect_rotate(&plane_state->base.src,
3134                                 fb->width << 16, fb->height << 16,
3135                                 DRM_MODE_ROTATE_270);
3136
3137         /*
3138          * Handle the AUX surface first since
3139          * the main surface setup depends on it.
3140          */
3141         if (fb->format->format == DRM_FORMAT_NV12) {
3142                 ret = skl_check_nv12_aux_surface(plane_state);
3143                 if (ret)
3144                         return ret;
3145         } else if (is_ccs_modifier(fb->modifier)) {
3146                 ret = skl_check_ccs_aux_surface(plane_state);
3147                 if (ret)
3148                         return ret;
3149         } else {
3150                 plane_state->color_plane[1].offset = ~0xfff;
3151                 plane_state->color_plane[1].x = 0;
3152                 plane_state->color_plane[1].y = 0;
3153         }
3154
3155         ret = skl_check_main_surface(plane_state);
3156         if (ret)
3157                 return ret;
3158
3159         return 0;
3160 }
3161
3162 unsigned int
3163 i9xx_plane_max_stride(struct intel_plane *plane,
3164                       u32 pixel_format, u64 modifier,
3165                       unsigned int rotation)
3166 {
3167         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3168
3169         if (!HAS_GMCH_DISPLAY(dev_priv)) {
3170                 return 32*1024;
3171         } else if (INTEL_GEN(dev_priv) >= 4) {
3172                 if (modifier == I915_FORMAT_MOD_X_TILED)
3173                         return 16*1024;
3174                 else
3175                         return 32*1024;
3176         } else if (INTEL_GEN(dev_priv) >= 3) {
3177                 if (modifier == I915_FORMAT_MOD_X_TILED)
3178                         return 8*1024;
3179                 else
3180                         return 16*1024;
3181         } else {
3182                 if (plane->i9xx_plane == PLANE_C)
3183                         return 4*1024;
3184                 else
3185                         return 8*1024;
3186         }
3187 }
3188
3189 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3190                           const struct intel_plane_state *plane_state)
3191 {
3192         struct drm_i915_private *dev_priv =
3193                 to_i915(plane_state->base.plane->dev);
3194         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3195         const struct drm_framebuffer *fb = plane_state->base.fb;
3196         unsigned int rotation = plane_state->base.rotation;
3197         u32 dspcntr;
3198
3199         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3200
3201         if (IS_G4X(dev_priv) || IS_GEN(dev_priv, 5) ||
3202             IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
3203                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3204
3205         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3206                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3207
3208         if (INTEL_GEN(dev_priv) < 5)
3209                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3210
3211         switch (fb->format->format) {
3212         case DRM_FORMAT_C8:
3213                 dspcntr |= DISPPLANE_8BPP;
3214                 break;
3215         case DRM_FORMAT_XRGB1555:
3216                 dspcntr |= DISPPLANE_BGRX555;
3217                 break;
3218         case DRM_FORMAT_RGB565:
3219                 dspcntr |= DISPPLANE_BGRX565;
3220                 break;
3221         case DRM_FORMAT_XRGB8888:
3222                 dspcntr |= DISPPLANE_BGRX888;
3223                 break;
3224         case DRM_FORMAT_XBGR8888:
3225                 dspcntr |= DISPPLANE_RGBX888;
3226                 break;
3227         case DRM_FORMAT_XRGB2101010:
3228                 dspcntr |= DISPPLANE_BGRX101010;
3229                 break;
3230         case DRM_FORMAT_XBGR2101010:
3231                 dspcntr |= DISPPLANE_RGBX101010;
3232                 break;
3233         default:
3234                 MISSING_CASE(fb->format->format);
3235                 return 0;
3236         }
3237
3238         if (INTEL_GEN(dev_priv) >= 4 &&
3239             fb->modifier == I915_FORMAT_MOD_X_TILED)
3240                 dspcntr |= DISPPLANE_TILED;
3241
3242         if (rotation & DRM_MODE_ROTATE_180)
3243                 dspcntr |= DISPPLANE_ROTATE_180;
3244
3245         if (rotation & DRM_MODE_REFLECT_X)
3246                 dspcntr |= DISPPLANE_MIRROR;
3247
3248         return dspcntr;
3249 }
3250
3251 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3252 {
3253         struct drm_i915_private *dev_priv =
3254                 to_i915(plane_state->base.plane->dev);
3255         const struct drm_framebuffer *fb = plane_state->base.fb;
3256         unsigned int rotation = plane_state->base.rotation;
3257         int src_x = plane_state->base.src.x1 >> 16;
3258         int src_y = plane_state->base.src.y1 >> 16;
3259         u32 offset;
3260         int ret;
3261
3262         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3263         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3264
3265         ret = intel_plane_check_stride(plane_state);
3266         if (ret)
3267                 return ret;
3268
3269         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3270
3271         if (INTEL_GEN(dev_priv) >= 4)
3272                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3273                                                             plane_state, 0);
3274         else
3275                 offset = 0;
3276
3277         /* HSW/BDW do this automagically in hardware */
3278         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3279                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3280                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3281
3282                 if (rotation & DRM_MODE_ROTATE_180) {
3283                         src_x += src_w - 1;
3284                         src_y += src_h - 1;
3285                 } else if (rotation & DRM_MODE_REFLECT_X) {
3286                         src_x += src_w - 1;
3287                 }
3288         }
3289
3290         plane_state->color_plane[0].offset = offset;
3291         plane_state->color_plane[0].x = src_x;
3292         plane_state->color_plane[0].y = src_y;
3293
3294         return 0;
3295 }
3296
3297 static int
3298 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3299                  struct intel_plane_state *plane_state)
3300 {
3301         int ret;
3302
3303         ret = chv_plane_check_rotation(plane_state);
3304         if (ret)
3305                 return ret;
3306
3307         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3308                                                   &crtc_state->base,
3309                                                   DRM_PLANE_HELPER_NO_SCALING,
3310                                                   DRM_PLANE_HELPER_NO_SCALING,
3311                                                   false, true);
3312         if (ret)
3313                 return ret;
3314
3315         if (!plane_state->base.visible)
3316                 return 0;
3317
3318         ret = intel_plane_check_src_coordinates(plane_state);
3319         if (ret)
3320                 return ret;
3321
3322         ret = i9xx_check_plane_surface(plane_state);
3323         if (ret)
3324                 return ret;
3325
3326         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3327
3328         return 0;
3329 }
3330
3331 static void i9xx_update_plane(struct intel_plane *plane,
3332                               const struct intel_crtc_state *crtc_state,
3333                               const struct intel_plane_state *plane_state)
3334 {
3335         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3336         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3337         u32 linear_offset;
3338         u32 dspcntr = plane_state->ctl;
3339         int x = plane_state->color_plane[0].x;
3340         int y = plane_state->color_plane[0].y;
3341         unsigned long irqflags;
3342         u32 dspaddr_offset;
3343
3344         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3345
3346         if (INTEL_GEN(dev_priv) >= 4)
3347                 dspaddr_offset = plane_state->color_plane[0].offset;
3348         else
3349                 dspaddr_offset = linear_offset;
3350
3351         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3352
3353         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3354
3355         if (INTEL_GEN(dev_priv) < 4) {
3356                 /* pipesrc and dspsize control the size that is scaled from,
3357                  * which should always be the user's requested size.
3358                  */
3359                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3360                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3361                               ((crtc_state->pipe_src_h - 1) << 16) |
3362                               (crtc_state->pipe_src_w - 1));
3363         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3364                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3365                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3366                               ((crtc_state->pipe_src_h - 1) << 16) |
3367                               (crtc_state->pipe_src_w - 1));
3368                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3369         }
3370
3371         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3372                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3373         } else if (INTEL_GEN(dev_priv) >= 4) {
3374                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3375                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3376         }
3377
3378         /*
3379          * The control register self-arms if the plane was previously
3380          * disabled. Try to make the plane enable atomic by writing
3381          * the control register just before the surface register.
3382          */
3383         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3384         if (INTEL_GEN(dev_priv) >= 4)
3385                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3386                               intel_plane_ggtt_offset(plane_state) +
3387                               dspaddr_offset);
3388         else
3389                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3390                               intel_plane_ggtt_offset(plane_state) +
3391                               dspaddr_offset);
3392
3393         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3394 }
3395
3396 static void i9xx_disable_plane(struct intel_plane *plane,
3397                                const struct intel_crtc_state *crtc_state)
3398 {
3399         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3400         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3401         unsigned long irqflags;
3402
3403         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3404
3405         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3406         if (INTEL_GEN(dev_priv) >= 4)
3407                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3408         else
3409                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3410
3411         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3412 }
3413
3414 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3415                                     enum pipe *pipe)
3416 {
3417         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3418         enum intel_display_power_domain power_domain;
3419         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3420         intel_wakeref_t wakeref;
3421         bool ret;
3422         u32 val;
3423
3424         /*
3425          * Not 100% correct for planes that can move between pipes,
3426          * but that's only the case for gen2-4 which don't have any
3427          * display power wells.
3428          */
3429         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3430         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
3431         if (!wakeref)
3432                 return false;
3433
3434         val = I915_READ(DSPCNTR(i9xx_plane));
3435
3436         ret = val & DISPLAY_PLANE_ENABLE;
3437
3438         if (INTEL_GEN(dev_priv) >= 5)
3439                 *pipe = plane->pipe;
3440         else
3441                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3442                         DISPPLANE_SEL_PIPE_SHIFT;
3443
3444         intel_display_power_put(dev_priv, power_domain, wakeref);
3445
3446         return ret;
3447 }
3448
3449 static u32
3450 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
3451 {
3452         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3453                 return 64;
3454         else
3455                 return intel_tile_width_bytes(fb, color_plane);
3456 }
3457
3458 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3459 {
3460         struct drm_device *dev = intel_crtc->base.dev;
3461         struct drm_i915_private *dev_priv = to_i915(dev);
3462
3463         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3464         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3465         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3466 }
3467
3468 /*
3469  * This function detaches (aka. unbinds) unused scalers in hardware
3470  */
3471 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3472 {
3473         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3474         const struct intel_crtc_scaler_state *scaler_state =
3475                 &crtc_state->scaler_state;
3476         int i;
3477
3478         /* loop through and disable scalers that aren't in use */
3479         for (i = 0; i < intel_crtc->num_scalers; i++) {
3480                 if (!scaler_state->scalers[i].in_use)
3481                         skl_detach_scaler(intel_crtc, i);
3482         }
3483 }
3484
3485 static unsigned int skl_plane_stride_mult(const struct drm_framebuffer *fb,
3486                                           int color_plane, unsigned int rotation)
3487 {
3488         /*
3489          * The stride is either expressed as a multiple of 64 bytes chunks for
3490          * linear buffers or in number of tiles for tiled buffers.
3491          */
3492         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3493                 return 64;
3494         else if (drm_rotation_90_or_270(rotation))
3495                 return intel_tile_height(fb, color_plane);
3496         else
3497                 return intel_tile_width_bytes(fb, color_plane);
3498 }
3499
3500 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3501                      int color_plane)
3502 {
3503         const struct drm_framebuffer *fb = plane_state->base.fb;
3504         unsigned int rotation = plane_state->base.rotation;
3505         u32 stride = plane_state->color_plane[color_plane].stride;
3506
3507         if (color_plane >= fb->format->num_planes)
3508                 return 0;
3509
3510         return stride / skl_plane_stride_mult(fb, color_plane, rotation);
3511 }
3512
3513 static u32 skl_plane_ctl_format(u32 pixel_format)
3514 {
3515         switch (pixel_format) {
3516         case DRM_FORMAT_C8:
3517                 return PLANE_CTL_FORMAT_INDEXED;
3518         case DRM_FORMAT_RGB565:
3519                 return PLANE_CTL_FORMAT_RGB_565;
3520         case DRM_FORMAT_XBGR8888:
3521         case DRM_FORMAT_ABGR8888:
3522                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3523         case DRM_FORMAT_XRGB8888:
3524         case DRM_FORMAT_ARGB8888:
3525                 return PLANE_CTL_FORMAT_XRGB_8888;
3526         case DRM_FORMAT_XRGB2101010:
3527                 return PLANE_CTL_FORMAT_XRGB_2101010;
3528         case DRM_FORMAT_XBGR2101010:
3529                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3530         case DRM_FORMAT_YUYV:
3531                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3532         case DRM_FORMAT_YVYU:
3533                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3534         case DRM_FORMAT_UYVY:
3535                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3536         case DRM_FORMAT_VYUY:
3537                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3538         case DRM_FORMAT_NV12:
3539                 return PLANE_CTL_FORMAT_NV12;
3540         default:
3541                 MISSING_CASE(pixel_format);
3542         }
3543
3544         return 0;
3545 }
3546
3547 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
3548 {
3549         if (!plane_state->base.fb->format->has_alpha)
3550                 return PLANE_CTL_ALPHA_DISABLE;
3551
3552         switch (plane_state->base.pixel_blend_mode) {
3553         case DRM_MODE_BLEND_PIXEL_NONE:
3554                 return PLANE_CTL_ALPHA_DISABLE;
3555         case DRM_MODE_BLEND_PREMULTI:
3556                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3557         case DRM_MODE_BLEND_COVERAGE:
3558                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
3559         default:
3560                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3561                 return PLANE_CTL_ALPHA_DISABLE;
3562         }
3563 }
3564
3565 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
3566 {
3567         if (!plane_state->base.fb->format->has_alpha)
3568                 return PLANE_COLOR_ALPHA_DISABLE;
3569
3570         switch (plane_state->base.pixel_blend_mode) {
3571         case DRM_MODE_BLEND_PIXEL_NONE:
3572                 return PLANE_COLOR_ALPHA_DISABLE;
3573         case DRM_MODE_BLEND_PREMULTI:
3574                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3575         case DRM_MODE_BLEND_COVERAGE:
3576                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
3577         default:
3578                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3579                 return PLANE_COLOR_ALPHA_DISABLE;
3580         }
3581 }
3582
3583 static u32 skl_plane_ctl_tiling(u64 fb_modifier)
3584 {
3585         switch (fb_modifier) {
3586         case DRM_FORMAT_MOD_LINEAR:
3587                 break;
3588         case I915_FORMAT_MOD_X_TILED:
3589                 return PLANE_CTL_TILED_X;
3590         case I915_FORMAT_MOD_Y_TILED:
3591                 return PLANE_CTL_TILED_Y;
3592         case I915_FORMAT_MOD_Y_TILED_CCS:
3593                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3594         case I915_FORMAT_MOD_Yf_TILED:
3595                 return PLANE_CTL_TILED_YF;
3596         case I915_FORMAT_MOD_Yf_TILED_CCS:
3597                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3598         default:
3599                 MISSING_CASE(fb_modifier);
3600         }
3601
3602         return 0;
3603 }
3604
3605 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3606 {
3607         switch (rotate) {
3608         case DRM_MODE_ROTATE_0:
3609                 break;
3610         /*
3611          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3612          * while i915 HW rotation is clockwise, thats why this swapping.
3613          */
3614         case DRM_MODE_ROTATE_90:
3615                 return PLANE_CTL_ROTATE_270;
3616         case DRM_MODE_ROTATE_180:
3617                 return PLANE_CTL_ROTATE_180;
3618         case DRM_MODE_ROTATE_270:
3619                 return PLANE_CTL_ROTATE_90;
3620         default:
3621                 MISSING_CASE(rotate);
3622         }
3623
3624         return 0;
3625 }
3626
3627 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3628 {
3629         switch (reflect) {
3630         case 0:
3631                 break;
3632         case DRM_MODE_REFLECT_X:
3633                 return PLANE_CTL_FLIP_HORIZONTAL;
3634         case DRM_MODE_REFLECT_Y:
3635         default:
3636                 MISSING_CASE(reflect);
3637         }
3638
3639         return 0;
3640 }
3641
3642 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3643                   const struct intel_plane_state *plane_state)
3644 {
3645         struct drm_i915_private *dev_priv =
3646                 to_i915(plane_state->base.plane->dev);
3647         const struct drm_framebuffer *fb = plane_state->base.fb;
3648         unsigned int rotation = plane_state->base.rotation;
3649         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3650         u32 plane_ctl;
3651
3652         plane_ctl = PLANE_CTL_ENABLE;
3653
3654         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3655                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
3656                 plane_ctl |=
3657                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3658                         PLANE_CTL_PIPE_CSC_ENABLE |
3659                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3660
3661                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3662                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3663
3664                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3665                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3666         }
3667
3668         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3669         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3670         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3671
3672         if (INTEL_GEN(dev_priv) >= 10)
3673                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3674                                                 DRM_MODE_REFLECT_MASK);
3675
3676         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3677                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3678         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3679                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3680
3681         return plane_ctl;
3682 }
3683
3684 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3685                         const struct intel_plane_state *plane_state)
3686 {
3687         struct drm_i915_private *dev_priv =
3688                 to_i915(plane_state->base.plane->dev);
3689         const struct drm_framebuffer *fb = plane_state->base.fb;
3690         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3691         u32 plane_color_ctl = 0;
3692
3693         if (INTEL_GEN(dev_priv) < 11) {
3694                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3695                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3696         }
3697         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3698         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
3699
3700         if (fb->format->is_yuv && !icl_is_hdr_plane(plane)) {
3701                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3702                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3703                 else
3704                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3705
3706                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3707                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3708         } else if (fb->format->is_yuv) {
3709                 plane_color_ctl |= PLANE_COLOR_INPUT_CSC_ENABLE;
3710         }
3711
3712         return plane_color_ctl;
3713 }
3714
3715 static int
3716 __intel_display_resume(struct drm_device *dev,
3717                        struct drm_atomic_state *state,
3718                        struct drm_modeset_acquire_ctx *ctx)
3719 {
3720         struct drm_crtc_state *crtc_state;
3721         struct drm_crtc *crtc;
3722         int i, ret;
3723
3724         intel_modeset_setup_hw_state(dev, ctx);
3725         i915_redisable_vga(to_i915(dev));
3726
3727         if (!state)
3728                 return 0;
3729
3730         /*
3731          * We've duplicated the state, pointers to the old state are invalid.
3732          *
3733          * Don't attempt to use the old state until we commit the duplicated state.
3734          */
3735         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3736                 /*
3737                  * Force recalculation even if we restore
3738                  * current state. With fast modeset this may not result
3739                  * in a modeset when the state is compatible.
3740                  */
3741                 crtc_state->mode_changed = true;
3742         }
3743
3744         /* ignore any reset values/BIOS leftovers in the WM registers */
3745         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3746                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3747
3748         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3749
3750         WARN_ON(ret == -EDEADLK);
3751         return ret;
3752 }
3753
3754 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3755 {
3756         return (INTEL_INFO(dev_priv)->gpu_reset_clobbers_display &&
3757                 intel_has_gpu_reset(dev_priv));
3758 }
3759
3760 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3761 {
3762         struct drm_device *dev = &dev_priv->drm;
3763         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3764         struct drm_atomic_state *state;
3765         int ret;
3766
3767         /* reset doesn't touch the display */
3768         if (!i915_modparams.force_reset_modeset_test &&
3769             !gpu_reset_clobbers_display(dev_priv))
3770                 return;
3771
3772         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3773         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3774         wake_up_all(&dev_priv->gpu_error.wait_queue);
3775
3776         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3777                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3778                 i915_gem_set_wedged(dev_priv);
3779         }
3780
3781         /*
3782          * Need mode_config.mutex so that we don't
3783          * trample ongoing ->detect() and whatnot.
3784          */
3785         mutex_lock(&dev->mode_config.mutex);
3786         drm_modeset_acquire_init(ctx, 0);
3787         while (1) {
3788                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3789                 if (ret != -EDEADLK)
3790                         break;
3791
3792                 drm_modeset_backoff(ctx);
3793         }
3794         /*
3795          * Disabling the crtcs gracefully seems nicer. Also the
3796          * g33 docs say we should at least disable all the planes.
3797          */
3798         state = drm_atomic_helper_duplicate_state(dev, ctx);
3799         if (IS_ERR(state)) {
3800                 ret = PTR_ERR(state);
3801                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3802                 return;
3803         }
3804
3805         ret = drm_atomic_helper_disable_all(dev, ctx);
3806         if (ret) {
3807                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3808                 drm_atomic_state_put(state);
3809                 return;
3810         }
3811
3812         dev_priv->modeset_restore_state = state;
3813         state->acquire_ctx = ctx;
3814 }
3815
3816 void intel_finish_reset(struct drm_i915_private *dev_priv)
3817 {
3818         struct drm_device *dev = &dev_priv->drm;
3819         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3820         struct drm_atomic_state *state;
3821         int ret;
3822
3823         /* reset doesn't touch the display */
3824         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3825                 return;
3826
3827         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3828         if (!state)
3829                 goto unlock;
3830
3831         /* reset doesn't touch the display */
3832         if (!gpu_reset_clobbers_display(dev_priv)) {
3833                 /* for testing only restore the display */
3834                 ret = __intel_display_resume(dev, state, ctx);
3835                 if (ret)
3836                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3837         } else {
3838                 /*
3839                  * The display has been reset as well,
3840                  * so need a full re-initialization.
3841                  */
3842                 intel_runtime_pm_disable_interrupts(dev_priv);
3843                 intel_runtime_pm_enable_interrupts(dev_priv);
3844
3845                 intel_pps_unlock_regs_wa(dev_priv);
3846                 intel_modeset_init_hw(dev);
3847                 intel_init_clock_gating(dev_priv);
3848
3849                 spin_lock_irq(&dev_priv->irq_lock);
3850                 if (dev_priv->display.hpd_irq_setup)
3851                         dev_priv->display.hpd_irq_setup(dev_priv);
3852                 spin_unlock_irq(&dev_priv->irq_lock);
3853
3854                 ret = __intel_display_resume(dev, state, ctx);
3855                 if (ret)
3856                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3857
3858                 intel_hpd_init(dev_priv);
3859         }
3860
3861         drm_atomic_state_put(state);
3862 unlock:
3863         drm_modeset_drop_locks(ctx);
3864         drm_modeset_acquire_fini(ctx);
3865         mutex_unlock(&dev->mode_config.mutex);
3866
3867         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3868 }
3869
3870 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3871                                      const struct intel_crtc_state *new_crtc_state)
3872 {
3873         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3874         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3875
3876         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3877         crtc->base.mode = new_crtc_state->base.mode;
3878
3879         /*
3880          * Update pipe size and adjust fitter if needed: the reason for this is
3881          * that in compute_mode_changes we check the native mode (not the pfit
3882          * mode) to see if we can flip rather than do a full mode set. In the
3883          * fastboot case, we'll flip, but if we don't update the pipesrc and
3884          * pfit state, we'll end up with a big fb scanned out into the wrong
3885          * sized surface.
3886          */
3887
3888         I915_WRITE(PIPESRC(crtc->pipe),
3889                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3890                    (new_crtc_state->pipe_src_h - 1));
3891
3892         /* on skylake this is done by detaching scalers */
3893         if (INTEL_GEN(dev_priv) >= 9) {
3894                 skl_detach_scalers(new_crtc_state);
3895
3896                 if (new_crtc_state->pch_pfit.enabled)
3897                         skylake_pfit_enable(new_crtc_state);
3898         } else if (HAS_PCH_SPLIT(dev_priv)) {
3899                 if (new_crtc_state->pch_pfit.enabled)
3900                         ironlake_pfit_enable(new_crtc_state);
3901                 else if (old_crtc_state->pch_pfit.enabled)
3902                         ironlake_pfit_disable(old_crtc_state);
3903         }
3904 }
3905
3906 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3907 {
3908         struct drm_device *dev = crtc->base.dev;
3909         struct drm_i915_private *dev_priv = to_i915(dev);
3910         int pipe = crtc->pipe;
3911         i915_reg_t reg;
3912         u32 temp;
3913
3914         /* enable normal train */
3915         reg = FDI_TX_CTL(pipe);
3916         temp = I915_READ(reg);
3917         if (IS_IVYBRIDGE(dev_priv)) {
3918                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3919                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3920         } else {
3921                 temp &= ~FDI_LINK_TRAIN_NONE;
3922                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3923         }
3924         I915_WRITE(reg, temp);
3925
3926         reg = FDI_RX_CTL(pipe);
3927         temp = I915_READ(reg);
3928         if (HAS_PCH_CPT(dev_priv)) {
3929                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3930                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3931         } else {
3932                 temp &= ~FDI_LINK_TRAIN_NONE;
3933                 temp |= FDI_LINK_TRAIN_NONE;
3934         }
3935         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3936
3937         /* wait one idle pattern time */
3938         POSTING_READ(reg);
3939         udelay(1000);
3940
3941         /* IVB wants error correction enabled */
3942         if (IS_IVYBRIDGE(dev_priv))
3943                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3944                            FDI_FE_ERRC_ENABLE);
3945 }
3946
3947 /* The FDI link training functions for ILK/Ibexpeak. */
3948 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3949                                     const struct intel_crtc_state *crtc_state)
3950 {
3951         struct drm_device *dev = crtc->base.dev;
3952         struct drm_i915_private *dev_priv = to_i915(dev);
3953         int pipe = crtc->pipe;
3954         i915_reg_t reg;
3955         u32 temp, tries;
3956
3957         /* FDI needs bits from pipe first */
3958         assert_pipe_enabled(dev_priv, pipe);
3959
3960         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3961            for train result */
3962         reg = FDI_RX_IMR(pipe);
3963         temp = I915_READ(reg);
3964         temp &= ~FDI_RX_SYMBOL_LOCK;
3965         temp &= ~FDI_RX_BIT_LOCK;
3966         I915_WRITE(reg, temp);
3967         I915_READ(reg);
3968         udelay(150);
3969
3970         /* enable CPU FDI TX and PCH FDI RX */
3971         reg = FDI_TX_CTL(pipe);
3972         temp = I915_READ(reg);
3973         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3974         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3975         temp &= ~FDI_LINK_TRAIN_NONE;
3976         temp |= FDI_LINK_TRAIN_PATTERN_1;
3977         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3978
3979         reg = FDI_RX_CTL(pipe);
3980         temp = I915_READ(reg);
3981         temp &= ~FDI_LINK_TRAIN_NONE;
3982         temp |= FDI_LINK_TRAIN_PATTERN_1;
3983         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3984
3985         POSTING_READ(reg);
3986         udelay(150);
3987
3988         /* Ironlake workaround, enable clock pointer after FDI enable*/
3989         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3990         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3991                    FDI_RX_PHASE_SYNC_POINTER_EN);
3992
3993         reg = FDI_RX_IIR(pipe);
3994         for (tries = 0; tries < 5; tries++) {
3995                 temp = I915_READ(reg);
3996                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3997
3998                 if ((temp & FDI_RX_BIT_LOCK)) {
3999                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4000                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4001                         break;
4002                 }
4003         }
4004         if (tries == 5)
4005                 DRM_ERROR("FDI train 1 fail!\n");
4006
4007         /* Train 2 */
4008         reg = FDI_TX_CTL(pipe);
4009         temp = I915_READ(reg);
4010         temp &= ~FDI_LINK_TRAIN_NONE;
4011         temp |= FDI_LINK_TRAIN_PATTERN_2;
4012         I915_WRITE(reg, temp);
4013
4014         reg = FDI_RX_CTL(pipe);
4015         temp = I915_READ(reg);
4016         temp &= ~FDI_LINK_TRAIN_NONE;
4017         temp |= FDI_LINK_TRAIN_PATTERN_2;
4018         I915_WRITE(reg, temp);
4019
4020         POSTING_READ(reg);
4021         udelay(150);
4022
4023         reg = FDI_RX_IIR(pipe);
4024         for (tries = 0; tries < 5; tries++) {
4025                 temp = I915_READ(reg);
4026                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4027
4028                 if (temp & FDI_RX_SYMBOL_LOCK) {
4029                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4030                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4031                         break;
4032                 }
4033         }
4034         if (tries == 5)
4035                 DRM_ERROR("FDI train 2 fail!\n");
4036
4037         DRM_DEBUG_KMS("FDI train done\n");
4038
4039 }
4040
4041 static const int snb_b_fdi_train_param[] = {
4042         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4043         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4044         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4045         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4046 };
4047
4048 /* The FDI link training functions for SNB/Cougarpoint. */
4049 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4050                                 const struct intel_crtc_state *crtc_state)
4051 {
4052         struct drm_device *dev = crtc->base.dev;
4053         struct drm_i915_private *dev_priv = to_i915(dev);
4054         int pipe = crtc->pipe;
4055         i915_reg_t reg;
4056         u32 temp, i, retry;
4057
4058         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4059            for train result */
4060         reg = FDI_RX_IMR(pipe);
4061         temp = I915_READ(reg);
4062         temp &= ~FDI_RX_SYMBOL_LOCK;
4063         temp &= ~FDI_RX_BIT_LOCK;
4064         I915_WRITE(reg, temp);
4065
4066         POSTING_READ(reg);
4067         udelay(150);
4068
4069         /* enable CPU FDI TX and PCH FDI RX */
4070         reg = FDI_TX_CTL(pipe);
4071         temp = I915_READ(reg);
4072         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4073         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4074         temp &= ~FDI_LINK_TRAIN_NONE;
4075         temp |= FDI_LINK_TRAIN_PATTERN_1;
4076         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4077         /* SNB-B */
4078         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4079         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4080
4081         I915_WRITE(FDI_RX_MISC(pipe),
4082                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4083
4084         reg = FDI_RX_CTL(pipe);
4085         temp = I915_READ(reg);
4086         if (HAS_PCH_CPT(dev_priv)) {
4087                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4088                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4089         } else {
4090                 temp &= ~FDI_LINK_TRAIN_NONE;
4091                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4092         }
4093         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4094
4095         POSTING_READ(reg);
4096         udelay(150);
4097
4098         for (i = 0; i < 4; i++) {
4099                 reg = FDI_TX_CTL(pipe);
4100                 temp = I915_READ(reg);
4101                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4102                 temp |= snb_b_fdi_train_param[i];
4103                 I915_WRITE(reg, temp);
4104
4105                 POSTING_READ(reg);
4106                 udelay(500);
4107
4108                 for (retry = 0; retry < 5; retry++) {
4109                         reg = FDI_RX_IIR(pipe);
4110                         temp = I915_READ(reg);
4111                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4112                         if (temp & FDI_RX_BIT_LOCK) {
4113                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4114                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4115                                 break;
4116                         }
4117                         udelay(50);
4118                 }
4119                 if (retry < 5)
4120                         break;
4121         }
4122         if (i == 4)
4123                 DRM_ERROR("FDI train 1 fail!\n");
4124
4125         /* Train 2 */
4126         reg = FDI_TX_CTL(pipe);
4127         temp = I915_READ(reg);
4128         temp &= ~FDI_LINK_TRAIN_NONE;
4129         temp |= FDI_LINK_TRAIN_PATTERN_2;
4130         if (IS_GEN(dev_priv, 6)) {
4131                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4132                 /* SNB-B */
4133                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4134         }
4135         I915_WRITE(reg, temp);
4136
4137         reg = FDI_RX_CTL(pipe);
4138         temp = I915_READ(reg);
4139         if (HAS_PCH_CPT(dev_priv)) {
4140                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4141                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4142         } else {
4143                 temp &= ~FDI_LINK_TRAIN_NONE;
4144                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4145         }
4146         I915_WRITE(reg, temp);
4147
4148         POSTING_READ(reg);
4149         udelay(150);
4150
4151         for (i = 0; i < 4; i++) {
4152                 reg = FDI_TX_CTL(pipe);
4153                 temp = I915_READ(reg);
4154                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4155                 temp |= snb_b_fdi_train_param[i];
4156                 I915_WRITE(reg, temp);
4157
4158                 POSTING_READ(reg);
4159                 udelay(500);
4160
4161                 for (retry = 0; retry < 5; retry++) {
4162                         reg = FDI_RX_IIR(pipe);
4163                         temp = I915_READ(reg);
4164                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4165                         if (temp & FDI_RX_SYMBOL_LOCK) {
4166                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4167                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4168                                 break;
4169                         }
4170                         udelay(50);
4171                 }
4172                 if (retry < 5)
4173                         break;
4174         }
4175         if (i == 4)
4176                 DRM_ERROR("FDI train 2 fail!\n");
4177
4178         DRM_DEBUG_KMS("FDI train done.\n");
4179 }
4180
4181 /* Manual link training for Ivy Bridge A0 parts */
4182 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4183                                       const struct intel_crtc_state *crtc_state)
4184 {
4185         struct drm_device *dev = crtc->base.dev;
4186         struct drm_i915_private *dev_priv = to_i915(dev);
4187         int pipe = crtc->pipe;
4188         i915_reg_t reg;
4189         u32 temp, i, j;
4190
4191         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4192            for train result */
4193         reg = FDI_RX_IMR(pipe);
4194         temp = I915_READ(reg);
4195         temp &= ~FDI_RX_SYMBOL_LOCK;
4196         temp &= ~FDI_RX_BIT_LOCK;
4197         I915_WRITE(reg, temp);
4198
4199         POSTING_READ(reg);
4200         udelay(150);
4201
4202         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4203                       I915_READ(FDI_RX_IIR(pipe)));
4204
4205         /* Try each vswing and preemphasis setting twice before moving on */
4206         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4207                 /* disable first in case we need to retry */
4208                 reg = FDI_TX_CTL(pipe);
4209                 temp = I915_READ(reg);
4210                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4211                 temp &= ~FDI_TX_ENABLE;
4212                 I915_WRITE(reg, temp);
4213
4214                 reg = FDI_RX_CTL(pipe);
4215                 temp = I915_READ(reg);
4216                 temp &= ~FDI_LINK_TRAIN_AUTO;
4217                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4218                 temp &= ~FDI_RX_ENABLE;
4219                 I915_WRITE(reg, temp);
4220
4221                 /* enable CPU FDI TX and PCH FDI RX */
4222                 reg = FDI_TX_CTL(pipe);
4223                 temp = I915_READ(reg);
4224                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4225                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4226                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4227                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4228                 temp |= snb_b_fdi_train_param[j/2];
4229                 temp |= FDI_COMPOSITE_SYNC;
4230                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4231
4232                 I915_WRITE(FDI_RX_MISC(pipe),
4233                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4234
4235                 reg = FDI_RX_CTL(pipe);
4236                 temp = I915_READ(reg);
4237                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4238                 temp |= FDI_COMPOSITE_SYNC;
4239                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4240
4241                 POSTING_READ(reg);
4242                 udelay(1); /* should be 0.5us */
4243
4244                 for (i = 0; i < 4; i++) {
4245                         reg = FDI_RX_IIR(pipe);
4246                         temp = I915_READ(reg);
4247                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4248
4249                         if (temp & FDI_RX_BIT_LOCK ||
4250                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4251                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4252                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4253                                               i);
4254                                 break;
4255                         }
4256                         udelay(1); /* should be 0.5us */
4257                 }
4258                 if (i == 4) {
4259                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4260                         continue;
4261                 }
4262
4263                 /* Train 2 */
4264                 reg = FDI_TX_CTL(pipe);
4265                 temp = I915_READ(reg);
4266                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4267                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4268                 I915_WRITE(reg, temp);
4269
4270                 reg = FDI_RX_CTL(pipe);
4271                 temp = I915_READ(reg);
4272                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4273                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4274                 I915_WRITE(reg, temp);
4275
4276                 POSTING_READ(reg);
4277                 udelay(2); /* should be 1.5us */
4278
4279                 for (i = 0; i < 4; i++) {
4280                         reg = FDI_RX_IIR(pipe);
4281                         temp = I915_READ(reg);
4282                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4283
4284                         if (temp & FDI_RX_SYMBOL_LOCK ||
4285                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4286                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4287                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4288                                               i);
4289                                 goto train_done;
4290                         }
4291                         udelay(2); /* should be 1.5us */
4292                 }
4293                 if (i == 4)
4294                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4295         }
4296
4297 train_done:
4298         DRM_DEBUG_KMS("FDI train done.\n");
4299 }
4300
4301 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4302 {
4303         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4304         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4305         int pipe = intel_crtc->pipe;
4306         i915_reg_t reg;
4307         u32 temp;
4308
4309         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4310         reg = FDI_RX_CTL(pipe);
4311         temp = I915_READ(reg);
4312         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4313         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4314         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4315         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4316
4317         POSTING_READ(reg);
4318         udelay(200);
4319
4320         /* Switch from Rawclk to PCDclk */
4321         temp = I915_READ(reg);
4322         I915_WRITE(reg, temp | FDI_PCDCLK);
4323
4324         POSTING_READ(reg);
4325         udelay(200);
4326
4327         /* Enable CPU FDI TX PLL, always on for Ironlake */
4328         reg = FDI_TX_CTL(pipe);
4329         temp = I915_READ(reg);
4330         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4331                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4332
4333                 POSTING_READ(reg);
4334                 udelay(100);
4335         }
4336 }
4337
4338 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4339 {
4340         struct drm_device *dev = intel_crtc->base.dev;
4341         struct drm_i915_private *dev_priv = to_i915(dev);
4342         int pipe = intel_crtc->pipe;
4343         i915_reg_t reg;
4344         u32 temp;
4345
4346         /* Switch from PCDclk to Rawclk */
4347         reg = FDI_RX_CTL(pipe);
4348         temp = I915_READ(reg);
4349         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4350
4351         /* Disable CPU FDI TX PLL */
4352         reg = FDI_TX_CTL(pipe);
4353         temp = I915_READ(reg);
4354         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4355
4356         POSTING_READ(reg);
4357         udelay(100);
4358
4359         reg = FDI_RX_CTL(pipe);
4360         temp = I915_READ(reg);
4361         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4362
4363         /* Wait for the clocks to turn off. */
4364         POSTING_READ(reg);
4365         udelay(100);
4366 }
4367
4368 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4369 {
4370         struct drm_device *dev = crtc->dev;
4371         struct drm_i915_private *dev_priv = to_i915(dev);
4372         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4373         int pipe = intel_crtc->pipe;
4374         i915_reg_t reg;
4375         u32 temp;
4376
4377         /* disable CPU FDI tx and PCH FDI rx */
4378         reg = FDI_TX_CTL(pipe);
4379         temp = I915_READ(reg);
4380         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4381         POSTING_READ(reg);
4382
4383         reg = FDI_RX_CTL(pipe);
4384         temp = I915_READ(reg);
4385         temp &= ~(0x7 << 16);
4386         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4387         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4388
4389         POSTING_READ(reg);
4390         udelay(100);
4391
4392         /* Ironlake workaround, disable clock pointer after downing FDI */
4393         if (HAS_PCH_IBX(dev_priv))
4394                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4395
4396         /* still set train pattern 1 */
4397         reg = FDI_TX_CTL(pipe);
4398         temp = I915_READ(reg);
4399         temp &= ~FDI_LINK_TRAIN_NONE;
4400         temp |= FDI_LINK_TRAIN_PATTERN_1;
4401         I915_WRITE(reg, temp);
4402
4403         reg = FDI_RX_CTL(pipe);
4404         temp = I915_READ(reg);
4405         if (HAS_PCH_CPT(dev_priv)) {
4406                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4407                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4408         } else {
4409                 temp &= ~FDI_LINK_TRAIN_NONE;
4410                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4411         }
4412         /* BPC in FDI rx is consistent with that in PIPECONF */
4413         temp &= ~(0x07 << 16);
4414         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4415         I915_WRITE(reg, temp);
4416
4417         POSTING_READ(reg);
4418         udelay(100);
4419 }
4420
4421 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4422 {
4423         struct drm_crtc *crtc;
4424         bool cleanup_done;
4425
4426         drm_for_each_crtc(crtc, &dev_priv->drm) {
4427                 struct drm_crtc_commit *commit;
4428                 spin_lock(&crtc->commit_lock);
4429                 commit = list_first_entry_or_null(&crtc->commit_list,
4430                                                   struct drm_crtc_commit, commit_entry);
4431                 cleanup_done = commit ?
4432                         try_wait_for_completion(&commit->cleanup_done) : true;
4433                 spin_unlock(&crtc->commit_lock);
4434
4435                 if (cleanup_done)
4436                         continue;
4437
4438                 drm_crtc_wait_one_vblank(crtc);
4439
4440                 return true;
4441         }
4442
4443         return false;
4444 }
4445
4446 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4447 {
4448         u32 temp;
4449
4450         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4451
4452         mutex_lock(&dev_priv->sb_lock);
4453
4454         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4455         temp |= SBI_SSCCTL_DISABLE;
4456         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4457
4458         mutex_unlock(&dev_priv->sb_lock);
4459 }
4460
4461 /* Program iCLKIP clock to the desired frequency */
4462 static void lpt_program_iclkip(const struct intel_crtc_state *crtc_state)
4463 {
4464         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4465         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4466         int clock = crtc_state->base.adjusted_mode.crtc_clock;
4467         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4468         u32 temp;
4469
4470         lpt_disable_iclkip(dev_priv);
4471
4472         /* The iCLK virtual clock root frequency is in MHz,
4473          * but the adjusted_mode->crtc_clock in in KHz. To get the
4474          * divisors, it is necessary to divide one by another, so we
4475          * convert the virtual clock precision to KHz here for higher
4476          * precision.
4477          */
4478         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4479                 u32 iclk_virtual_root_freq = 172800 * 1000;
4480                 u32 iclk_pi_range = 64;
4481                 u32 desired_divisor;
4482
4483                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4484                                                     clock << auxdiv);
4485                 divsel = (desired_divisor / iclk_pi_range) - 2;
4486                 phaseinc = desired_divisor % iclk_pi_range;
4487
4488                 /*
4489                  * Near 20MHz is a corner case which is
4490                  * out of range for the 7-bit divisor
4491                  */
4492                 if (divsel <= 0x7f)
4493                         break;
4494         }
4495
4496         /* This should not happen with any sane values */
4497         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4498                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4499         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4500                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4501
4502         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4503                         clock,
4504                         auxdiv,
4505                         divsel,
4506                         phasedir,
4507                         phaseinc);
4508
4509         mutex_lock(&dev_priv->sb_lock);
4510
4511         /* Program SSCDIVINTPHASE6 */
4512         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4513         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4514         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4515         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4516         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4517         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4518         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4519         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4520
4521         /* Program SSCAUXDIV */
4522         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4523         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4524         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4525         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4526
4527         /* Enable modulator and associated divider */
4528         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4529         temp &= ~SBI_SSCCTL_DISABLE;
4530         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4531
4532         mutex_unlock(&dev_priv->sb_lock);
4533
4534         /* Wait for initialization time */
4535         udelay(24);
4536
4537         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4538 }
4539
4540 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4541 {
4542         u32 divsel, phaseinc, auxdiv;
4543         u32 iclk_virtual_root_freq = 172800 * 1000;
4544         u32 iclk_pi_range = 64;
4545         u32 desired_divisor;
4546         u32 temp;
4547
4548         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4549                 return 0;
4550
4551         mutex_lock(&dev_priv->sb_lock);
4552
4553         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4554         if (temp & SBI_SSCCTL_DISABLE) {
4555                 mutex_unlock(&dev_priv->sb_lock);
4556                 return 0;
4557         }
4558
4559         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4560         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4561                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4562         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4563                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4564
4565         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4566         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4567                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4568
4569         mutex_unlock(&dev_priv->sb_lock);
4570
4571         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4572
4573         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4574                                  desired_divisor << auxdiv);
4575 }
4576
4577 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
4578                                                 enum pipe pch_transcoder)
4579 {
4580         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4581         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4582         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4583
4584         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4585                    I915_READ(HTOTAL(cpu_transcoder)));
4586         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4587                    I915_READ(HBLANK(cpu_transcoder)));
4588         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4589                    I915_READ(HSYNC(cpu_transcoder)));
4590
4591         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4592                    I915_READ(VTOTAL(cpu_transcoder)));
4593         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4594                    I915_READ(VBLANK(cpu_transcoder)));
4595         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4596                    I915_READ(VSYNC(cpu_transcoder)));
4597         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4598                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4599 }
4600
4601 static void cpt_set_fdi_bc_bifurcation(struct drm_i915_private *dev_priv, bool enable)
4602 {
4603         u32 temp;
4604
4605         temp = I915_READ(SOUTH_CHICKEN1);
4606         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4607                 return;
4608
4609         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4610         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4611
4612         temp &= ~FDI_BC_BIFURCATION_SELECT;
4613         if (enable)
4614                 temp |= FDI_BC_BIFURCATION_SELECT;
4615
4616         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4617         I915_WRITE(SOUTH_CHICKEN1, temp);
4618         POSTING_READ(SOUTH_CHICKEN1);
4619 }
4620
4621 static void ivybridge_update_fdi_bc_bifurcation(const struct intel_crtc_state *crtc_state)
4622 {
4623         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4624         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4625
4626         switch (crtc->pipe) {
4627         case PIPE_A:
4628                 break;
4629         case PIPE_B:
4630                 if (crtc_state->fdi_lanes > 2)
4631                         cpt_set_fdi_bc_bifurcation(dev_priv, false);
4632                 else
4633                         cpt_set_fdi_bc_bifurcation(dev_priv, true);
4634
4635                 break;
4636         case PIPE_C:
4637                 cpt_set_fdi_bc_bifurcation(dev_priv, true);
4638
4639                 break;
4640         default:
4641                 BUG();
4642         }
4643 }
4644
4645 /*
4646  * Finds the encoder associated with the given CRTC. This can only be
4647  * used when we know that the CRTC isn't feeding multiple encoders!
4648  */
4649 static struct intel_encoder *
4650 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4651                            const struct intel_crtc_state *crtc_state)
4652 {
4653         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4654         const struct drm_connector_state *connector_state;
4655         const struct drm_connector *connector;
4656         struct intel_encoder *encoder = NULL;
4657         int num_encoders = 0;
4658         int i;
4659
4660         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4661                 if (connector_state->crtc != &crtc->base)
4662                         continue;
4663
4664                 encoder = to_intel_encoder(connector_state->best_encoder);
4665                 num_encoders++;
4666         }
4667
4668         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4669              num_encoders, pipe_name(crtc->pipe));
4670
4671         return encoder;
4672 }
4673
4674 /*
4675  * Enable PCH resources required for PCH ports:
4676  *   - PCH PLLs
4677  *   - FDI training & RX/TX
4678  *   - update transcoder timings
4679  *   - DP transcoding bits
4680  *   - transcoder
4681  */
4682 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4683                                 const struct intel_crtc_state *crtc_state)
4684 {
4685         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4686         struct drm_device *dev = crtc->base.dev;
4687         struct drm_i915_private *dev_priv = to_i915(dev);
4688         int pipe = crtc->pipe;
4689         u32 temp;
4690
4691         assert_pch_transcoder_disabled(dev_priv, pipe);
4692
4693         if (IS_IVYBRIDGE(dev_priv))
4694                 ivybridge_update_fdi_bc_bifurcation(crtc_state);
4695
4696         /* Write the TU size bits before fdi link training, so that error
4697          * detection works. */
4698         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4699                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4700
4701         /* For PCH output, training FDI link */
4702         dev_priv->display.fdi_link_train(crtc, crtc_state);
4703
4704         /* We need to program the right clock selection before writing the pixel
4705          * mutliplier into the DPLL. */
4706         if (HAS_PCH_CPT(dev_priv)) {
4707                 u32 sel;
4708
4709                 temp = I915_READ(PCH_DPLL_SEL);
4710                 temp |= TRANS_DPLL_ENABLE(pipe);
4711                 sel = TRANS_DPLLB_SEL(pipe);
4712                 if (crtc_state->shared_dpll ==
4713                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4714                         temp |= sel;
4715                 else
4716                         temp &= ~sel;
4717                 I915_WRITE(PCH_DPLL_SEL, temp);
4718         }
4719
4720         /* XXX: pch pll's can be enabled any time before we enable the PCH
4721          * transcoder, and we actually should do this to not upset any PCH
4722          * transcoder that already use the clock when we share it.
4723          *
4724          * Note that enable_shared_dpll tries to do the right thing, but
4725          * get_shared_dpll unconditionally resets the pll - we need that to have
4726          * the right LVDS enable sequence. */
4727         intel_enable_shared_dpll(crtc_state);
4728
4729         /* set transcoder timing, panel must allow it */
4730         assert_panel_unlocked(dev_priv, pipe);
4731         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
4732
4733         intel_fdi_normal_train(crtc);
4734
4735         /* For PCH DP, enable TRANS_DP_CTL */
4736         if (HAS_PCH_CPT(dev_priv) &&
4737             intel_crtc_has_dp_encoder(crtc_state)) {
4738                 const struct drm_display_mode *adjusted_mode =
4739                         &crtc_state->base.adjusted_mode;
4740                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4741                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4742                 enum port port;
4743
4744                 temp = I915_READ(reg);
4745                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4746                           TRANS_DP_SYNC_MASK |
4747                           TRANS_DP_BPC_MASK);
4748                 temp |= TRANS_DP_OUTPUT_ENABLE;
4749                 temp |= bpc << 9; /* same format but at 11:9 */
4750
4751                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4752                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4753                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4754                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4755
4756                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4757                 WARN_ON(port < PORT_B || port > PORT_D);
4758                 temp |= TRANS_DP_PORT_SEL(port);
4759
4760                 I915_WRITE(reg, temp);
4761         }
4762
4763         ironlake_enable_pch_transcoder(crtc_state);
4764 }
4765
4766 static void lpt_pch_enable(const struct intel_atomic_state *state,
4767                            const struct intel_crtc_state *crtc_state)
4768 {
4769         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4770         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4771         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4772
4773         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4774
4775         lpt_program_iclkip(crtc_state);
4776
4777         /* Set transcoder timing. */
4778         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
4779
4780         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4781 }
4782
4783 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4784 {
4785         struct drm_i915_private *dev_priv = to_i915(dev);
4786         i915_reg_t dslreg = PIPEDSL(pipe);
4787         u32 temp;
4788
4789         temp = I915_READ(dslreg);
4790         udelay(500);
4791         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4792                 if (wait_for(I915_READ(dslreg) != temp, 5))
4793                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4794         }
4795 }
4796
4797 /*
4798  * The hardware phase 0.0 refers to the center of the pixel.
4799  * We want to start from the top/left edge which is phase
4800  * -0.5. That matches how the hardware calculates the scaling
4801  * factors (from top-left of the first pixel to bottom-right
4802  * of the last pixel, as opposed to the pixel centers).
4803  *
4804  * For 4:2:0 subsampled chroma planes we obviously have to
4805  * adjust that so that the chroma sample position lands in
4806  * the right spot.
4807  *
4808  * Note that for packed YCbCr 4:2:2 formats there is no way to
4809  * control chroma siting. The hardware simply replicates the
4810  * chroma samples for both of the luma samples, and thus we don't
4811  * actually get the expected MPEG2 chroma siting convention :(
4812  * The same behaviour is observed on pre-SKL platforms as well.
4813  *
4814  * Theory behind the formula (note that we ignore sub-pixel
4815  * source coordinates):
4816  * s = source sample position
4817  * d = destination sample position
4818  *
4819  * Downscaling 4:1:
4820  * -0.5
4821  * | 0.0
4822  * | |     1.5 (initial phase)
4823  * | |     |
4824  * v v     v
4825  * | s | s | s | s |
4826  * |       d       |
4827  *
4828  * Upscaling 1:4:
4829  * -0.5
4830  * | -0.375 (initial phase)
4831  * | |     0.0
4832  * | |     |
4833  * v v     v
4834  * |       s       |
4835  * | d | d | d | d |
4836  */
4837 u16 skl_scaler_calc_phase(int sub, int scale, bool chroma_cosited)
4838 {
4839         int phase = -0x8000;
4840         u16 trip = 0;
4841
4842         if (chroma_cosited)
4843                 phase += (sub - 1) * 0x8000 / sub;
4844
4845         phase += scale / (2 * sub);
4846
4847         /*
4848          * Hardware initial phase limited to [-0.5:1.5].
4849          * Since the max hardware scale factor is 3.0, we
4850          * should never actually excdeed 1.0 here.
4851          */
4852         WARN_ON(phase < -0x8000 || phase > 0x18000);
4853
4854         if (phase < 0)
4855                 phase = 0x10000 + phase;
4856         else
4857                 trip = PS_PHASE_TRIP;
4858
4859         return ((phase >> 2) & PS_PHASE_MASK) | trip;
4860 }
4861
4862 static int
4863 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4864                   unsigned int scaler_user, int *scaler_id,
4865                   int src_w, int src_h, int dst_w, int dst_h,
4866                   const struct drm_format_info *format, bool need_scaler)
4867 {
4868         struct intel_crtc_scaler_state *scaler_state =
4869                 &crtc_state->scaler_state;
4870         struct intel_crtc *intel_crtc =
4871                 to_intel_crtc(crtc_state->base.crtc);
4872         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4873         const struct drm_display_mode *adjusted_mode =
4874                 &crtc_state->base.adjusted_mode;
4875
4876         /*
4877          * Src coordinates are already rotated by 270 degrees for
4878          * the 90/270 degree plane rotation cases (to match the
4879          * GTT mapping), hence no need to account for rotation here.
4880          */
4881         if (src_w != dst_w || src_h != dst_h)
4882                 need_scaler = true;
4883
4884         /*
4885          * Scaling/fitting not supported in IF-ID mode in GEN9+
4886          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4887          * Once NV12 is enabled, handle it here while allocating scaler
4888          * for NV12.
4889          */
4890         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4891             need_scaler && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4892                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4893                 return -EINVAL;
4894         }
4895
4896         /*
4897          * if plane is being disabled or scaler is no more required or force detach
4898          *  - free scaler binded to this plane/crtc
4899          *  - in order to do this, update crtc->scaler_usage
4900          *
4901          * Here scaler state in crtc_state is set free so that
4902          * scaler can be assigned to other user. Actual register
4903          * update to free the scaler is done in plane/panel-fit programming.
4904          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4905          */
4906         if (force_detach || !need_scaler) {
4907                 if (*scaler_id >= 0) {
4908                         scaler_state->scaler_users &= ~(1 << scaler_user);
4909                         scaler_state->scalers[*scaler_id].in_use = 0;
4910
4911                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4912                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4913                                 intel_crtc->pipe, scaler_user, *scaler_id,
4914                                 scaler_state->scaler_users);
4915                         *scaler_id = -1;
4916                 }
4917                 return 0;
4918         }
4919
4920         if (format && format->format == DRM_FORMAT_NV12 &&
4921             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4922                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4923                 return -EINVAL;
4924         }
4925
4926         /* range checks */
4927         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4928             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4929             (IS_GEN(dev_priv, 11) &&
4930              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4931               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4932             (!IS_GEN(dev_priv, 11) &&
4933              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4934               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4935                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4936                         "size is out of scaler range\n",
4937                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4938                 return -EINVAL;
4939         }
4940
4941         /* mark this plane as a scaler user in crtc_state */
4942         scaler_state->scaler_users |= (1 << scaler_user);
4943         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4944                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4945                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4946                 scaler_state->scaler_users);
4947
4948         return 0;
4949 }
4950
4951 /**
4952  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4953  *
4954  * @state: crtc's scaler state
4955  *
4956  * Return
4957  *     0 - scaler_usage updated successfully
4958  *    error - requested scaling cannot be supported or other error condition
4959  */
4960 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4961 {
4962         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4963         bool need_scaler = false;
4964
4965         if (state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
4966                 need_scaler = true;
4967
4968         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4969                                  &state->scaler_state.scaler_id,
4970                                  state->pipe_src_w, state->pipe_src_h,
4971                                  adjusted_mode->crtc_hdisplay,
4972                                  adjusted_mode->crtc_vdisplay, NULL, need_scaler);
4973 }
4974
4975 /**
4976  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4977  * @crtc_state: crtc's scaler state
4978  * @plane_state: atomic plane state to update
4979  *
4980  * Return
4981  *     0 - scaler_usage updated successfully
4982  *    error - requested scaling cannot be supported or other error condition
4983  */
4984 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4985                                    struct intel_plane_state *plane_state)
4986 {
4987         struct intel_plane *intel_plane =
4988                 to_intel_plane(plane_state->base.plane);
4989         struct drm_framebuffer *fb = plane_state->base.fb;
4990         int ret;
4991         bool force_detach = !fb || !plane_state->base.visible;
4992         bool need_scaler = false;
4993
4994         /* Pre-gen11 and SDR planes always need a scaler for planar formats. */
4995         if (!icl_is_hdr_plane(intel_plane) &&
4996             fb && fb->format->format == DRM_FORMAT_NV12)
4997                 need_scaler = true;
4998
4999         ret = skl_update_scaler(crtc_state, force_detach,
5000                                 drm_plane_index(&intel_plane->base),
5001                                 &plane_state->scaler_id,
5002                                 drm_rect_width(&plane_state->base.src) >> 16,
5003                                 drm_rect_height(&plane_state->base.src) >> 16,
5004                                 drm_rect_width(&plane_state->base.dst),
5005                                 drm_rect_height(&plane_state->base.dst),
5006                                 fb ? fb->format : NULL, need_scaler);
5007
5008         if (ret || plane_state->scaler_id < 0)
5009                 return ret;
5010
5011         /* check colorkey */
5012         if (plane_state->ckey.flags) {
5013                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
5014                               intel_plane->base.base.id,
5015                               intel_plane->base.name);
5016                 return -EINVAL;
5017         }
5018
5019         /* Check src format */
5020         switch (fb->format->format) {
5021         case DRM_FORMAT_RGB565:
5022         case DRM_FORMAT_XBGR8888:
5023         case DRM_FORMAT_XRGB8888:
5024         case DRM_FORMAT_ABGR8888:
5025         case DRM_FORMAT_ARGB8888:
5026         case DRM_FORMAT_XRGB2101010:
5027         case DRM_FORMAT_XBGR2101010:
5028         case DRM_FORMAT_YUYV:
5029         case DRM_FORMAT_YVYU:
5030         case DRM_FORMAT_UYVY:
5031         case DRM_FORMAT_VYUY:
5032         case DRM_FORMAT_NV12:
5033                 break;
5034         default:
5035                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5036                               intel_plane->base.base.id, intel_plane->base.name,
5037                               fb->base.id, fb->format->format);
5038                 return -EINVAL;
5039         }
5040
5041         return 0;
5042 }
5043
5044 static void skylake_scaler_disable(struct intel_crtc *crtc)
5045 {
5046         int i;
5047
5048         for (i = 0; i < crtc->num_scalers; i++)
5049                 skl_detach_scaler(crtc, i);
5050 }
5051
5052 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5053 {
5054         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5055         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5056         enum pipe pipe = crtc->pipe;
5057         const struct intel_crtc_scaler_state *scaler_state =
5058                 &crtc_state->scaler_state;
5059
5060         if (crtc_state->pch_pfit.enabled) {
5061                 u16 uv_rgb_hphase, uv_rgb_vphase;
5062                 int pfit_w, pfit_h, hscale, vscale;
5063                 int id;
5064
5065                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5066                         return;
5067
5068                 pfit_w = (crtc_state->pch_pfit.size >> 16) & 0xFFFF;
5069                 pfit_h = crtc_state->pch_pfit.size & 0xFFFF;
5070
5071                 hscale = (crtc_state->pipe_src_w << 16) / pfit_w;
5072                 vscale = (crtc_state->pipe_src_h << 16) / pfit_h;
5073
5074                 uv_rgb_hphase = skl_scaler_calc_phase(1, hscale, false);
5075                 uv_rgb_vphase = skl_scaler_calc_phase(1, vscale, false);
5076
5077                 id = scaler_state->scaler_id;
5078                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5079                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5080                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5081                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5082                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5083                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5084                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5085                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5086         }
5087 }
5088
5089 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5090 {
5091         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5092         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5093         int pipe = crtc->pipe;
5094
5095         if (crtc_state->pch_pfit.enabled) {
5096                 /* Force use of hard-coded filter coefficients
5097                  * as some pre-programmed values are broken,
5098                  * e.g. x201.
5099                  */
5100                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5101                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5102                                                  PF_PIPE_SEL_IVB(pipe));
5103                 else
5104                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5105                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5106                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5107         }
5108 }
5109
5110 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5111 {
5112         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5113         struct drm_device *dev = crtc->base.dev;
5114         struct drm_i915_private *dev_priv = to_i915(dev);
5115
5116         if (!crtc_state->ips_enabled)
5117                 return;
5118
5119         /*
5120          * We can only enable IPS after we enable a plane and wait for a vblank
5121          * This function is called from post_plane_update, which is run after
5122          * a vblank wait.
5123          */
5124         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5125
5126         if (IS_BROADWELL(dev_priv)) {
5127                 mutex_lock(&dev_priv->pcu_lock);
5128                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5129                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5130                 mutex_unlock(&dev_priv->pcu_lock);
5131                 /* Quoting Art Runyan: "its not safe to expect any particular
5132                  * value in IPS_CTL bit 31 after enabling IPS through the
5133                  * mailbox." Moreover, the mailbox may return a bogus state,
5134                  * so we need to just enable it and continue on.
5135                  */
5136         } else {
5137                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5138                 /* The bit only becomes 1 in the next vblank, so this wait here
5139                  * is essentially intel_wait_for_vblank. If we don't have this
5140                  * and don't wait for vblanks until the end of crtc_enable, then
5141                  * the HW state readout code will complain that the expected
5142                  * IPS_CTL value is not the one we read. */
5143                 if (intel_wait_for_register(dev_priv,
5144                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5145                                             50))
5146                         DRM_ERROR("Timed out waiting for IPS enable\n");
5147         }
5148 }
5149
5150 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5151 {
5152         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5153         struct drm_device *dev = crtc->base.dev;
5154         struct drm_i915_private *dev_priv = to_i915(dev);
5155
5156         if (!crtc_state->ips_enabled)
5157                 return;
5158
5159         if (IS_BROADWELL(dev_priv)) {
5160                 mutex_lock(&dev_priv->pcu_lock);
5161                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5162                 mutex_unlock(&dev_priv->pcu_lock);
5163                 /*
5164                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5165                  * 42ms timeout value leads to occasional timeouts so use 100ms
5166                  * instead.
5167                  */
5168                 if (intel_wait_for_register(dev_priv,
5169                                             IPS_CTL, IPS_ENABLE, 0,
5170                                             100))
5171                         DRM_ERROR("Timed out waiting for IPS disable\n");
5172         } else {
5173                 I915_WRITE(IPS_CTL, 0);
5174                 POSTING_READ(IPS_CTL);
5175         }
5176
5177         /* We need to wait for a vblank before we can disable the plane. */
5178         intel_wait_for_vblank(dev_priv, crtc->pipe);
5179 }
5180
5181 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5182 {
5183         if (intel_crtc->overlay) {
5184                 struct drm_device *dev = intel_crtc->base.dev;
5185
5186                 mutex_lock(&dev->struct_mutex);
5187                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5188                 mutex_unlock(&dev->struct_mutex);
5189         }
5190
5191         /* Let userspace switch the overlay on again. In most cases userspace
5192          * has to recompute where to put it anyway.
5193          */
5194 }
5195
5196 /**
5197  * intel_post_enable_primary - Perform operations after enabling primary plane
5198  * @crtc: the CRTC whose primary plane was just enabled
5199  * @new_crtc_state: the enabling state
5200  *
5201  * Performs potentially sleeping operations that must be done after the primary
5202  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5203  * called due to an explicit primary plane update, or due to an implicit
5204  * re-enable that is caused when a sprite plane is updated to no longer
5205  * completely hide the primary plane.
5206  */
5207 static void
5208 intel_post_enable_primary(struct drm_crtc *crtc,
5209                           const struct intel_crtc_state *new_crtc_state)
5210 {
5211         struct drm_device *dev = crtc->dev;
5212         struct drm_i915_private *dev_priv = to_i915(dev);
5213         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5214         int pipe = intel_crtc->pipe;
5215
5216         /*
5217          * Gen2 reports pipe underruns whenever all planes are disabled.
5218          * So don't enable underrun reporting before at least some planes
5219          * are enabled.
5220          * FIXME: Need to fix the logic to work when we turn off all planes
5221          * but leave the pipe running.
5222          */
5223         if (IS_GEN(dev_priv, 2))
5224                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5225
5226         /* Underruns don't always raise interrupts, so check manually. */
5227         intel_check_cpu_fifo_underruns(dev_priv);
5228         intel_check_pch_fifo_underruns(dev_priv);
5229 }
5230
5231 /* FIXME get rid of this and use pre_plane_update */
5232 static void
5233 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5234 {
5235         struct drm_device *dev = crtc->dev;
5236         struct drm_i915_private *dev_priv = to_i915(dev);
5237         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5238         int pipe = intel_crtc->pipe;
5239
5240         /*
5241          * Gen2 reports pipe underruns whenever all planes are disabled.
5242          * So disable underrun reporting before all the planes get disabled.
5243          */
5244         if (IS_GEN(dev_priv, 2))
5245                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5246
5247         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5248
5249         /*
5250          * Vblank time updates from the shadow to live plane control register
5251          * are blocked if the memory self-refresh mode is active at that
5252          * moment. So to make sure the plane gets truly disabled, disable
5253          * first the self-refresh mode. The self-refresh enable bit in turn
5254          * will be checked/applied by the HW only at the next frame start
5255          * event which is after the vblank start event, so we need to have a
5256          * wait-for-vblank between disabling the plane and the pipe.
5257          */
5258         if (HAS_GMCH_DISPLAY(dev_priv) &&
5259             intel_set_memory_cxsr(dev_priv, false))
5260                 intel_wait_for_vblank(dev_priv, pipe);
5261 }
5262
5263 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5264                                        const struct intel_crtc_state *new_crtc_state)
5265 {
5266         if (!old_crtc_state->ips_enabled)
5267                 return false;
5268
5269         if (needs_modeset(&new_crtc_state->base))
5270                 return true;
5271
5272         return !new_crtc_state->ips_enabled;
5273 }
5274
5275 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5276                                        const struct intel_crtc_state *new_crtc_state)
5277 {
5278         if (!new_crtc_state->ips_enabled)
5279                 return false;
5280
5281         if (needs_modeset(&new_crtc_state->base))
5282                 return true;
5283
5284         /*
5285          * We can't read out IPS on broadwell, assume the worst and
5286          * forcibly enable IPS on the first fastset.
5287          */
5288         if (new_crtc_state->update_pipe &&
5289             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5290                 return true;
5291
5292         return !old_crtc_state->ips_enabled;
5293 }
5294
5295 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5296                           const struct intel_crtc_state *crtc_state)
5297 {
5298         if (!crtc_state->nv12_planes)
5299                 return false;
5300
5301         /* WA Display #0827: Gen9:all */
5302         if (IS_GEN(dev_priv, 9) && !IS_GEMINILAKE(dev_priv))
5303                 return true;
5304
5305         return false;
5306 }
5307
5308 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5309 {
5310         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5311         struct drm_device *dev = crtc->base.dev;
5312         struct drm_i915_private *dev_priv = to_i915(dev);
5313         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5314         struct intel_crtc_state *pipe_config =
5315                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5316                                                 crtc);
5317         struct drm_plane *primary = crtc->base.primary;
5318         struct drm_plane_state *old_primary_state =
5319                 drm_atomic_get_old_plane_state(old_state, primary);
5320
5321         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5322
5323         if (pipe_config->update_wm_post && pipe_config->base.active)
5324                 intel_update_watermarks(crtc);
5325
5326         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5327                 hsw_enable_ips(pipe_config);
5328
5329         if (old_primary_state) {
5330                 struct drm_plane_state *new_primary_state =
5331                         drm_atomic_get_new_plane_state(old_state, primary);
5332
5333                 intel_fbc_post_update(crtc);
5334
5335                 if (new_primary_state->visible &&
5336                     (needs_modeset(&pipe_config->base) ||
5337                      !old_primary_state->visible))
5338                         intel_post_enable_primary(&crtc->base, pipe_config);
5339         }
5340
5341         /* Display WA 827 */
5342         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5343             !needs_nv12_wa(dev_priv, pipe_config)) {
5344                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5345         }
5346 }
5347
5348 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5349                                    struct intel_crtc_state *pipe_config)
5350 {
5351         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5352         struct drm_device *dev = crtc->base.dev;
5353         struct drm_i915_private *dev_priv = to_i915(dev);
5354         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5355         struct drm_plane *primary = crtc->base.primary;
5356         struct drm_plane_state *old_primary_state =
5357                 drm_atomic_get_old_plane_state(old_state, primary);
5358         bool modeset = needs_modeset(&pipe_config->base);
5359         struct intel_atomic_state *old_intel_state =
5360                 to_intel_atomic_state(old_state);
5361
5362         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5363                 hsw_disable_ips(old_crtc_state);
5364
5365         if (old_primary_state) {
5366                 struct intel_plane_state *new_primary_state =
5367                         intel_atomic_get_new_plane_state(old_intel_state,
5368                                                          to_intel_plane(primary));
5369
5370                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5371                 /*
5372                  * Gen2 reports pipe underruns whenever all planes are disabled.
5373                  * So disable underrun reporting before all the planes get disabled.
5374                  */
5375                 if (IS_GEN(dev_priv, 2) && old_primary_state->visible &&
5376                     (modeset || !new_primary_state->base.visible))
5377                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5378         }
5379
5380         /* Display WA 827 */
5381         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5382             needs_nv12_wa(dev_priv, pipe_config)) {
5383                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5384         }
5385
5386         /*
5387          * Vblank time updates from the shadow to live plane control register
5388          * are blocked if the memory self-refresh mode is active at that
5389          * moment. So to make sure the plane gets truly disabled, disable
5390          * first the self-refresh mode. The self-refresh enable bit in turn
5391          * will be checked/applied by the HW only at the next frame start
5392          * event which is after the vblank start event, so we need to have a
5393          * wait-for-vblank between disabling the plane and the pipe.
5394          */
5395         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5396             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5397                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5398
5399         /*
5400          * IVB workaround: must disable low power watermarks for at least
5401          * one frame before enabling scaling.  LP watermarks can be re-enabled
5402          * when scaling is disabled.
5403          *
5404          * WaCxSRDisabledForSpriteScaling:ivb
5405          */
5406         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5407             old_crtc_state->base.active)
5408                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5409
5410         /*
5411          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5412          * watermark programming here.
5413          */
5414         if (needs_modeset(&pipe_config->base))
5415                 return;
5416
5417         /*
5418          * For platforms that support atomic watermarks, program the
5419          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5420          * will be the intermediate values that are safe for both pre- and
5421          * post- vblank; when vblank happens, the 'active' values will be set
5422          * to the final 'target' values and we'll do this again to get the
5423          * optimal watermarks.  For gen9+ platforms, the values we program here
5424          * will be the final target values which will get automatically latched
5425          * at vblank time; no further programming will be necessary.
5426          *
5427          * If a platform hasn't been transitioned to atomic watermarks yet,
5428          * we'll continue to update watermarks the old way, if flags tell
5429          * us to.
5430          */
5431         if (dev_priv->display.initial_watermarks != NULL)
5432                 dev_priv->display.initial_watermarks(old_intel_state,
5433                                                      pipe_config);
5434         else if (pipe_config->update_wm_pre)
5435                 intel_update_watermarks(crtc);
5436 }
5437
5438 static void intel_crtc_disable_planes(struct intel_atomic_state *state,
5439                                       struct intel_crtc *crtc)
5440 {
5441         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5442         const struct intel_crtc_state *new_crtc_state =
5443                 intel_atomic_get_new_crtc_state(state, crtc);
5444         unsigned int update_mask = new_crtc_state->update_planes;
5445         const struct intel_plane_state *old_plane_state;
5446         struct intel_plane *plane;
5447         unsigned fb_bits = 0;
5448         int i;
5449
5450         intel_crtc_dpms_overlay_disable(crtc);
5451
5452         for_each_old_intel_plane_in_state(state, plane, old_plane_state, i) {
5453                 if (crtc->pipe != plane->pipe ||
5454                     !(update_mask & BIT(plane->id)))
5455                         continue;
5456
5457                 plane->disable_plane(plane, new_crtc_state);
5458
5459                 if (old_plane_state->base.visible)
5460                         fb_bits |= plane->frontbuffer_bit;
5461         }
5462
5463         intel_frontbuffer_flip(dev_priv, fb_bits);
5464 }
5465
5466 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5467                                           struct intel_crtc_state *crtc_state,
5468                                           struct drm_atomic_state *old_state)
5469 {
5470         struct drm_connector_state *conn_state;
5471         struct drm_connector *conn;
5472         int i;
5473
5474         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5475                 struct intel_encoder *encoder =
5476                         to_intel_encoder(conn_state->best_encoder);
5477
5478                 if (conn_state->crtc != crtc)
5479                         continue;
5480
5481                 if (encoder->pre_pll_enable)
5482                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5483         }
5484 }
5485
5486 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5487                                       struct intel_crtc_state *crtc_state,
5488                                       struct drm_atomic_state *old_state)
5489 {
5490         struct drm_connector_state *conn_state;
5491         struct drm_connector *conn;
5492         int i;
5493
5494         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5495                 struct intel_encoder *encoder =
5496                         to_intel_encoder(conn_state->best_encoder);
5497
5498                 if (conn_state->crtc != crtc)
5499                         continue;
5500
5501                 if (encoder->pre_enable)
5502                         encoder->pre_enable(encoder, crtc_state, conn_state);
5503         }
5504 }
5505
5506 static void intel_encoders_enable(struct drm_crtc *crtc,
5507                                   struct intel_crtc_state *crtc_state,
5508                                   struct drm_atomic_state *old_state)
5509 {
5510         struct drm_connector_state *conn_state;
5511         struct drm_connector *conn;
5512         int i;
5513
5514         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5515                 struct intel_encoder *encoder =
5516                         to_intel_encoder(conn_state->best_encoder);
5517
5518                 if (conn_state->crtc != crtc)
5519                         continue;
5520
5521                 if (encoder->enable)
5522                         encoder->enable(encoder, crtc_state, conn_state);
5523                 intel_opregion_notify_encoder(encoder, true);
5524         }
5525 }
5526
5527 static void intel_encoders_disable(struct drm_crtc *crtc,
5528                                    struct intel_crtc_state *old_crtc_state,
5529                                    struct drm_atomic_state *old_state)
5530 {
5531         struct drm_connector_state *old_conn_state;
5532         struct drm_connector *conn;
5533         int i;
5534
5535         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5536                 struct intel_encoder *encoder =
5537                         to_intel_encoder(old_conn_state->best_encoder);
5538
5539                 if (old_conn_state->crtc != crtc)
5540                         continue;
5541
5542                 intel_opregion_notify_encoder(encoder, false);
5543                 if (encoder->disable)
5544                         encoder->disable(encoder, old_crtc_state, old_conn_state);
5545         }
5546 }
5547
5548 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5549                                         struct intel_crtc_state *old_crtc_state,
5550                                         struct drm_atomic_state *old_state)
5551 {
5552         struct drm_connector_state *old_conn_state;
5553         struct drm_connector *conn;
5554         int i;
5555
5556         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5557                 struct intel_encoder *encoder =
5558                         to_intel_encoder(old_conn_state->best_encoder);
5559
5560                 if (old_conn_state->crtc != crtc)
5561                         continue;
5562
5563                 if (encoder->post_disable)
5564                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5565         }
5566 }
5567
5568 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5569                                             struct intel_crtc_state *old_crtc_state,
5570                                             struct drm_atomic_state *old_state)
5571 {
5572         struct drm_connector_state *old_conn_state;
5573         struct drm_connector *conn;
5574         int i;
5575
5576         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5577                 struct intel_encoder *encoder =
5578                         to_intel_encoder(old_conn_state->best_encoder);
5579
5580                 if (old_conn_state->crtc != crtc)
5581                         continue;
5582
5583                 if (encoder->post_pll_disable)
5584                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5585         }
5586 }
5587
5588 static void intel_encoders_update_pipe(struct drm_crtc *crtc,
5589                                        struct intel_crtc_state *crtc_state,
5590                                        struct drm_atomic_state *old_state)
5591 {
5592         struct drm_connector_state *conn_state;
5593         struct drm_connector *conn;
5594         int i;
5595
5596         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5597                 struct intel_encoder *encoder =
5598                         to_intel_encoder(conn_state->best_encoder);
5599
5600                 if (conn_state->crtc != crtc)
5601                         continue;
5602
5603                 if (encoder->update_pipe)
5604                         encoder->update_pipe(encoder, crtc_state, conn_state);
5605         }
5606 }
5607
5608 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5609                                  struct drm_atomic_state *old_state)
5610 {
5611         struct drm_crtc *crtc = pipe_config->base.crtc;
5612         struct drm_device *dev = crtc->dev;
5613         struct drm_i915_private *dev_priv = to_i915(dev);
5614         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5615         int pipe = intel_crtc->pipe;
5616         struct intel_atomic_state *old_intel_state =
5617                 to_intel_atomic_state(old_state);
5618
5619         if (WARN_ON(intel_crtc->active))
5620                 return;
5621
5622         /*
5623          * Sometimes spurious CPU pipe underruns happen during FDI
5624          * training, at least with VGA+HDMI cloning. Suppress them.
5625          *
5626          * On ILK we get an occasional spurious CPU pipe underruns
5627          * between eDP port A enable and vdd enable. Also PCH port
5628          * enable seems to result in the occasional CPU pipe underrun.
5629          *
5630          * Spurious PCH underruns also occur during PCH enabling.
5631          */
5632         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5633         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5634
5635         if (pipe_config->has_pch_encoder)
5636                 intel_prepare_shared_dpll(pipe_config);
5637
5638         if (intel_crtc_has_dp_encoder(pipe_config))
5639                 intel_dp_set_m_n(pipe_config, M1_N1);
5640
5641         intel_set_pipe_timings(pipe_config);
5642         intel_set_pipe_src_size(pipe_config);
5643
5644         if (pipe_config->has_pch_encoder) {
5645                 intel_cpu_transcoder_set_m_n(pipe_config,
5646                                              &pipe_config->fdi_m_n, NULL);
5647         }
5648
5649         ironlake_set_pipeconf(pipe_config);
5650
5651         intel_crtc->active = true;
5652
5653         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5654
5655         if (pipe_config->has_pch_encoder) {
5656                 /* Note: FDI PLL enabling _must_ be done before we enable the
5657                  * cpu pipes, hence this is separate from all the other fdi/pch
5658                  * enabling. */
5659                 ironlake_fdi_pll_enable(pipe_config);
5660         } else {
5661                 assert_fdi_tx_disabled(dev_priv, pipe);
5662                 assert_fdi_rx_disabled(dev_priv, pipe);
5663         }
5664
5665         ironlake_pfit_enable(pipe_config);
5666
5667         /*
5668          * On ILK+ LUT must be loaded before the pipe is running but with
5669          * clocks enabled
5670          */
5671         intel_color_load_luts(pipe_config);
5672
5673         if (dev_priv->display.initial_watermarks != NULL)
5674                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5675         intel_enable_pipe(pipe_config);
5676
5677         if (pipe_config->has_pch_encoder)
5678                 ironlake_pch_enable(old_intel_state, pipe_config);
5679
5680         assert_vblank_disabled(crtc);
5681         drm_crtc_vblank_on(crtc);
5682
5683         intel_encoders_enable(crtc, pipe_config, old_state);
5684
5685         if (HAS_PCH_CPT(dev_priv))
5686                 cpt_verify_modeset(dev, intel_crtc->pipe);
5687
5688         /*
5689          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5690          * And a second vblank wait is needed at least on ILK with
5691          * some interlaced HDMI modes. Let's do the double wait always
5692          * in case there are more corner cases we don't know about.
5693          */
5694         if (pipe_config->has_pch_encoder) {
5695                 intel_wait_for_vblank(dev_priv, pipe);
5696                 intel_wait_for_vblank(dev_priv, pipe);
5697         }
5698         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5699         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5700 }
5701
5702 /* IPS only exists on ULT machines and is tied to pipe A. */
5703 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5704 {
5705         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5706 }
5707
5708 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5709                                             enum pipe pipe, bool apply)
5710 {
5711         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5712         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5713
5714         if (apply)
5715                 val |= mask;
5716         else
5717                 val &= ~mask;
5718
5719         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5720 }
5721
5722 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5723 {
5724         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5725         enum pipe pipe = crtc->pipe;
5726         u32 val;
5727
5728         val = MBUS_DBOX_A_CREDIT(2);
5729         val |= MBUS_DBOX_BW_CREDIT(1);
5730         val |= MBUS_DBOX_B_CREDIT(8);
5731
5732         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5733 }
5734
5735 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5736                                 struct drm_atomic_state *old_state)
5737 {
5738         struct drm_crtc *crtc = pipe_config->base.crtc;
5739         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5740         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5741         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5742         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
5743         struct intel_atomic_state *old_intel_state =
5744                 to_intel_atomic_state(old_state);
5745         bool psl_clkgate_wa;
5746         u32 pipe_chicken;
5747
5748         if (WARN_ON(intel_crtc->active))
5749                 return;
5750
5751         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5752
5753         if (pipe_config->shared_dpll)
5754                 intel_enable_shared_dpll(pipe_config);
5755
5756         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5757
5758         if (intel_crtc_has_dp_encoder(pipe_config))
5759                 intel_dp_set_m_n(pipe_config, M1_N1);
5760
5761         if (!transcoder_is_dsi(cpu_transcoder))
5762                 intel_set_pipe_timings(pipe_config);
5763
5764         intel_set_pipe_src_size(pipe_config);
5765
5766         if (cpu_transcoder != TRANSCODER_EDP &&
5767             !transcoder_is_dsi(cpu_transcoder)) {
5768                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5769                            pipe_config->pixel_multiplier - 1);
5770         }
5771
5772         if (pipe_config->has_pch_encoder) {
5773                 intel_cpu_transcoder_set_m_n(pipe_config,
5774                                              &pipe_config->fdi_m_n, NULL);
5775         }
5776
5777         if (!transcoder_is_dsi(cpu_transcoder))
5778                 haswell_set_pipeconf(pipe_config);
5779
5780         haswell_set_pipemisc(pipe_config);
5781
5782         intel_color_set_csc(pipe_config);
5783
5784         intel_crtc->active = true;
5785
5786         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5787         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5788                          pipe_config->pch_pfit.enabled;
5789         if (psl_clkgate_wa)
5790                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5791
5792         if (INTEL_GEN(dev_priv) >= 9)
5793                 skylake_pfit_enable(pipe_config);
5794         else
5795                 ironlake_pfit_enable(pipe_config);
5796
5797         /*
5798          * On ILK+ LUT must be loaded before the pipe is running but with
5799          * clocks enabled
5800          */
5801         intel_color_load_luts(pipe_config);
5802
5803         /*
5804          * Display WA #1153: enable hardware to bypass the alpha math
5805          * and rounding for per-pixel values 00 and 0xff
5806          */
5807         if (INTEL_GEN(dev_priv) >= 11) {
5808                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5809                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5810                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5811                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5812         }
5813
5814         intel_ddi_set_pipe_settings(pipe_config);
5815         if (!transcoder_is_dsi(cpu_transcoder))
5816                 intel_ddi_enable_transcoder_func(pipe_config);
5817
5818         if (dev_priv->display.initial_watermarks != NULL)
5819                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5820
5821         if (INTEL_GEN(dev_priv) >= 11)
5822                 icl_pipe_mbus_enable(intel_crtc);
5823
5824         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5825         if (!transcoder_is_dsi(cpu_transcoder))
5826                 intel_enable_pipe(pipe_config);
5827
5828         if (pipe_config->has_pch_encoder)
5829                 lpt_pch_enable(old_intel_state, pipe_config);
5830
5831         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
5832                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5833
5834         assert_vblank_disabled(crtc);
5835         drm_crtc_vblank_on(crtc);
5836
5837         intel_encoders_enable(crtc, pipe_config, old_state);
5838
5839         if (psl_clkgate_wa) {
5840                 intel_wait_for_vblank(dev_priv, pipe);
5841                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5842         }
5843
5844         /* If we change the relative order between pipe/planes enabling, we need
5845          * to change the workaround. */
5846         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5847         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5848                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5849                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5850         }
5851 }
5852
5853 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
5854 {
5855         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5856         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5857         enum pipe pipe = crtc->pipe;
5858
5859         /* To avoid upsetting the power well on haswell only disable the pfit if
5860          * it's in use. The hw state code will make sure we get this right. */
5861         if (old_crtc_state->pch_pfit.enabled) {
5862                 I915_WRITE(PF_CTL(pipe), 0);
5863                 I915_WRITE(PF_WIN_POS(pipe), 0);
5864                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5865         }
5866 }
5867
5868 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5869                                   struct drm_atomic_state *old_state)
5870 {
5871         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5872         struct drm_device *dev = crtc->dev;
5873         struct drm_i915_private *dev_priv = to_i915(dev);
5874         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5875         int pipe = intel_crtc->pipe;
5876
5877         /*
5878          * Sometimes spurious CPU pipe underruns happen when the
5879          * pipe is already disabled, but FDI RX/TX is still enabled.
5880          * Happens at least with VGA+HDMI cloning. Suppress them.
5881          */
5882         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5883         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5884
5885         intel_encoders_disable(crtc, old_crtc_state, old_state);
5886
5887         drm_crtc_vblank_off(crtc);
5888         assert_vblank_disabled(crtc);
5889
5890         intel_disable_pipe(old_crtc_state);
5891
5892         ironlake_pfit_disable(old_crtc_state);
5893
5894         if (old_crtc_state->has_pch_encoder)
5895                 ironlake_fdi_disable(crtc);
5896
5897         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5898
5899         if (old_crtc_state->has_pch_encoder) {
5900                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5901
5902                 if (HAS_PCH_CPT(dev_priv)) {
5903                         i915_reg_t reg;
5904                         u32 temp;
5905
5906                         /* disable TRANS_DP_CTL */
5907                         reg = TRANS_DP_CTL(pipe);
5908                         temp = I915_READ(reg);
5909                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5910                                   TRANS_DP_PORT_SEL_MASK);
5911                         temp |= TRANS_DP_PORT_SEL_NONE;
5912                         I915_WRITE(reg, temp);
5913
5914                         /* disable DPLL_SEL */
5915                         temp = I915_READ(PCH_DPLL_SEL);
5916                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5917                         I915_WRITE(PCH_DPLL_SEL, temp);
5918                 }
5919
5920                 ironlake_fdi_pll_disable(intel_crtc);
5921         }
5922
5923         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5924         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5925 }
5926
5927 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5928                                  struct drm_atomic_state *old_state)
5929 {
5930         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5931         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5932         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5933         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5934
5935         intel_encoders_disable(crtc, old_crtc_state, old_state);
5936
5937         drm_crtc_vblank_off(crtc);
5938         assert_vblank_disabled(crtc);
5939
5940         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5941         if (!transcoder_is_dsi(cpu_transcoder))
5942                 intel_disable_pipe(old_crtc_state);
5943
5944         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5945                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5946
5947         if (!transcoder_is_dsi(cpu_transcoder))
5948                 intel_ddi_disable_transcoder_func(old_crtc_state);
5949
5950         intel_dsc_disable(old_crtc_state);
5951
5952         if (INTEL_GEN(dev_priv) >= 9)
5953                 skylake_scaler_disable(intel_crtc);
5954         else
5955                 ironlake_pfit_disable(old_crtc_state);
5956
5957         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5958
5959         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5960 }
5961
5962 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
5963 {
5964         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5965         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5966
5967         if (!crtc_state->gmch_pfit.control)
5968                 return;
5969
5970         /*
5971          * The panel fitter should only be adjusted whilst the pipe is disabled,
5972          * according to register description and PRM.
5973          */
5974         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5975         assert_pipe_disabled(dev_priv, crtc->pipe);
5976
5977         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
5978         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
5979
5980         /* Border color in case we don't scale up to the full screen. Black by
5981          * default, change to something else for debugging. */
5982         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5983 }
5984
5985 bool intel_port_is_combophy(struct drm_i915_private *dev_priv, enum port port)
5986 {
5987         if (port == PORT_NONE)
5988                 return false;
5989
5990         if (IS_ICELAKE(dev_priv))
5991                 return port <= PORT_B;
5992
5993         return false;
5994 }
5995
5996 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
5997 {
5998         if (IS_ICELAKE(dev_priv))
5999                 return port >= PORT_C && port <= PORT_F;
6000
6001         return false;
6002 }
6003
6004 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
6005 {
6006         if (!intel_port_is_tc(dev_priv, port))
6007                 return PORT_TC_NONE;
6008
6009         return port - PORT_C;
6010 }
6011
6012 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
6013 {
6014         switch (port) {
6015         case PORT_A:
6016                 return POWER_DOMAIN_PORT_DDI_A_LANES;
6017         case PORT_B:
6018                 return POWER_DOMAIN_PORT_DDI_B_LANES;
6019         case PORT_C:
6020                 return POWER_DOMAIN_PORT_DDI_C_LANES;
6021         case PORT_D:
6022                 return POWER_DOMAIN_PORT_DDI_D_LANES;
6023         case PORT_E:
6024                 return POWER_DOMAIN_PORT_DDI_E_LANES;
6025         case PORT_F:
6026                 return POWER_DOMAIN_PORT_DDI_F_LANES;
6027         default:
6028                 MISSING_CASE(port);
6029                 return POWER_DOMAIN_PORT_OTHER;
6030         }
6031 }
6032
6033 enum intel_display_power_domain
6034 intel_aux_power_domain(struct intel_digital_port *dig_port)
6035 {
6036         switch (dig_port->aux_ch) {
6037         case AUX_CH_A:
6038                 return POWER_DOMAIN_AUX_A;
6039         case AUX_CH_B:
6040                 return POWER_DOMAIN_AUX_B;
6041         case AUX_CH_C:
6042                 return POWER_DOMAIN_AUX_C;
6043         case AUX_CH_D:
6044                 return POWER_DOMAIN_AUX_D;
6045         case AUX_CH_E:
6046                 return POWER_DOMAIN_AUX_E;
6047         case AUX_CH_F:
6048                 return POWER_DOMAIN_AUX_F;
6049         default:
6050                 MISSING_CASE(dig_port->aux_ch);
6051                 return POWER_DOMAIN_AUX_A;
6052         }
6053 }
6054
6055 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
6056                                   struct intel_crtc_state *crtc_state)
6057 {
6058         struct drm_device *dev = crtc->dev;
6059         struct drm_i915_private *dev_priv = to_i915(dev);
6060         struct drm_encoder *encoder;
6061         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6062         enum pipe pipe = intel_crtc->pipe;
6063         u64 mask;
6064         enum transcoder transcoder = crtc_state->cpu_transcoder;
6065
6066         if (!crtc_state->base.active)
6067                 return 0;
6068
6069         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6070         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6071         if (crtc_state->pch_pfit.enabled ||
6072             crtc_state->pch_pfit.force_thru)
6073                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6074
6075         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
6076                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6077
6078                 mask |= BIT_ULL(intel_encoder->power_domain);
6079         }
6080
6081         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6082                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6083
6084         if (crtc_state->shared_dpll)
6085                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
6086
6087         return mask;
6088 }
6089
6090 static u64
6091 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6092                                struct intel_crtc_state *crtc_state)
6093 {
6094         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6095         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6096         enum intel_display_power_domain domain;
6097         u64 domains, new_domains, old_domains;
6098
6099         old_domains = intel_crtc->enabled_power_domains;
6100         intel_crtc->enabled_power_domains = new_domains =
6101                 get_crtc_power_domains(crtc, crtc_state);
6102
6103         domains = new_domains & ~old_domains;
6104
6105         for_each_power_domain(domain, domains)
6106                 intel_display_power_get(dev_priv, domain);
6107
6108         return old_domains & ~new_domains;
6109 }
6110
6111 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6112                                       u64 domains)
6113 {
6114         enum intel_display_power_domain domain;
6115
6116         for_each_power_domain(domain, domains)
6117                 intel_display_power_put_unchecked(dev_priv, domain);
6118 }
6119
6120 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6121                                    struct drm_atomic_state *old_state)
6122 {
6123         struct intel_atomic_state *old_intel_state =
6124                 to_intel_atomic_state(old_state);
6125         struct drm_crtc *crtc = pipe_config->base.crtc;
6126         struct drm_device *dev = crtc->dev;
6127         struct drm_i915_private *dev_priv = to_i915(dev);
6128         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6129         int pipe = intel_crtc->pipe;
6130
6131         if (WARN_ON(intel_crtc->active))
6132                 return;
6133
6134         if (intel_crtc_has_dp_encoder(pipe_config))
6135                 intel_dp_set_m_n(pipe_config, M1_N1);
6136
6137         intel_set_pipe_timings(pipe_config);
6138         intel_set_pipe_src_size(pipe_config);
6139
6140         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6141                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6142                 I915_WRITE(CHV_CANVAS(pipe), 0);
6143         }
6144
6145         i9xx_set_pipeconf(pipe_config);
6146
6147         intel_color_set_csc(pipe_config);
6148
6149         intel_crtc->active = true;
6150
6151         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6152
6153         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6154
6155         if (IS_CHERRYVIEW(dev_priv)) {
6156                 chv_prepare_pll(intel_crtc, pipe_config);
6157                 chv_enable_pll(intel_crtc, pipe_config);
6158         } else {
6159                 vlv_prepare_pll(intel_crtc, pipe_config);
6160                 vlv_enable_pll(intel_crtc, pipe_config);
6161         }
6162
6163         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6164
6165         i9xx_pfit_enable(pipe_config);
6166
6167         intel_color_load_luts(pipe_config);
6168
6169         dev_priv->display.initial_watermarks(old_intel_state,
6170                                              pipe_config);
6171         intel_enable_pipe(pipe_config);
6172
6173         assert_vblank_disabled(crtc);
6174         drm_crtc_vblank_on(crtc);
6175
6176         intel_encoders_enable(crtc, pipe_config, old_state);
6177 }
6178
6179 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6180 {
6181         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6182         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6183
6184         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6185         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6186 }
6187
6188 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6189                              struct drm_atomic_state *old_state)
6190 {
6191         struct intel_atomic_state *old_intel_state =
6192                 to_intel_atomic_state(old_state);
6193         struct drm_crtc *crtc = pipe_config->base.crtc;
6194         struct drm_device *dev = crtc->dev;
6195         struct drm_i915_private *dev_priv = to_i915(dev);
6196         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6197         enum pipe pipe = intel_crtc->pipe;
6198
6199         if (WARN_ON(intel_crtc->active))
6200                 return;
6201
6202         i9xx_set_pll_dividers(pipe_config);
6203
6204         if (intel_crtc_has_dp_encoder(pipe_config))
6205                 intel_dp_set_m_n(pipe_config, M1_N1);
6206
6207         intel_set_pipe_timings(pipe_config);
6208         intel_set_pipe_src_size(pipe_config);
6209
6210         i9xx_set_pipeconf(pipe_config);
6211
6212         intel_crtc->active = true;
6213
6214         if (!IS_GEN(dev_priv, 2))
6215                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6216
6217         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6218
6219         i9xx_enable_pll(intel_crtc, pipe_config);
6220
6221         i9xx_pfit_enable(pipe_config);
6222
6223         intel_color_load_luts(pipe_config);
6224
6225         if (dev_priv->display.initial_watermarks != NULL)
6226                 dev_priv->display.initial_watermarks(old_intel_state,
6227                                                      pipe_config);
6228         else
6229                 intel_update_watermarks(intel_crtc);
6230         intel_enable_pipe(pipe_config);
6231
6232         assert_vblank_disabled(crtc);
6233         drm_crtc_vblank_on(crtc);
6234
6235         intel_encoders_enable(crtc, pipe_config, old_state);
6236 }
6237
6238 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6239 {
6240         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6241         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6242
6243         if (!old_crtc_state->gmch_pfit.control)
6244                 return;
6245
6246         assert_pipe_disabled(dev_priv, crtc->pipe);
6247
6248         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6249                       I915_READ(PFIT_CONTROL));
6250         I915_WRITE(PFIT_CONTROL, 0);
6251 }
6252
6253 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6254                               struct drm_atomic_state *old_state)
6255 {
6256         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6257         struct drm_device *dev = crtc->dev;
6258         struct drm_i915_private *dev_priv = to_i915(dev);
6259         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6260         int pipe = intel_crtc->pipe;
6261
6262         /*
6263          * On gen2 planes are double buffered but the pipe isn't, so we must
6264          * wait for planes to fully turn off before disabling the pipe.
6265          */
6266         if (IS_GEN(dev_priv, 2))
6267                 intel_wait_for_vblank(dev_priv, pipe);
6268
6269         intel_encoders_disable(crtc, old_crtc_state, old_state);
6270
6271         drm_crtc_vblank_off(crtc);
6272         assert_vblank_disabled(crtc);
6273
6274         intel_disable_pipe(old_crtc_state);
6275
6276         i9xx_pfit_disable(old_crtc_state);
6277
6278         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6279
6280         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6281                 if (IS_CHERRYVIEW(dev_priv))
6282                         chv_disable_pll(dev_priv, pipe);
6283                 else if (IS_VALLEYVIEW(dev_priv))
6284                         vlv_disable_pll(dev_priv, pipe);
6285                 else
6286                         i9xx_disable_pll(old_crtc_state);
6287         }
6288
6289         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6290
6291         if (!IS_GEN(dev_priv, 2))
6292                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6293
6294         if (!dev_priv->display.initial_watermarks)
6295                 intel_update_watermarks(intel_crtc);
6296
6297         /* clock the pipe down to 640x480@60 to potentially save power */
6298         if (IS_I830(dev_priv))
6299                 i830_enable_pipe(dev_priv, pipe);
6300 }
6301
6302 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6303                                         struct drm_modeset_acquire_ctx *ctx)
6304 {
6305         struct intel_encoder *encoder;
6306         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6307         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6308         enum intel_display_power_domain domain;
6309         struct intel_plane *plane;
6310         u64 domains;
6311         struct drm_atomic_state *state;
6312         struct intel_crtc_state *crtc_state;
6313         int ret;
6314
6315         if (!intel_crtc->active)
6316                 return;
6317
6318         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6319                 const struct intel_plane_state *plane_state =
6320                         to_intel_plane_state(plane->base.state);
6321
6322                 if (plane_state->base.visible)
6323                         intel_plane_disable_noatomic(intel_crtc, plane);
6324         }
6325
6326         state = drm_atomic_state_alloc(crtc->dev);
6327         if (!state) {
6328                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6329                               crtc->base.id, crtc->name);
6330                 return;
6331         }
6332
6333         state->acquire_ctx = ctx;
6334
6335         /* Everything's already locked, -EDEADLK can't happen. */
6336         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6337         ret = drm_atomic_add_affected_connectors(state, crtc);
6338
6339         WARN_ON(IS_ERR(crtc_state) || ret);
6340
6341         dev_priv->display.crtc_disable(crtc_state, state);
6342
6343         drm_atomic_state_put(state);
6344
6345         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6346                       crtc->base.id, crtc->name);
6347
6348         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6349         crtc->state->active = false;
6350         intel_crtc->active = false;
6351         crtc->enabled = false;
6352         crtc->state->connector_mask = 0;
6353         crtc->state->encoder_mask = 0;
6354
6355         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6356                 encoder->base.crtc = NULL;
6357
6358         intel_fbc_disable(intel_crtc);
6359         intel_update_watermarks(intel_crtc);
6360         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6361
6362         domains = intel_crtc->enabled_power_domains;
6363         for_each_power_domain(domain, domains)
6364                 intel_display_power_put_unchecked(dev_priv, domain);
6365         intel_crtc->enabled_power_domains = 0;
6366
6367         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6368         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6369         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6370 }
6371
6372 /*
6373  * turn all crtc's off, but do not adjust state
6374  * This has to be paired with a call to intel_modeset_setup_hw_state.
6375  */
6376 int intel_display_suspend(struct drm_device *dev)
6377 {
6378         struct drm_i915_private *dev_priv = to_i915(dev);
6379         struct drm_atomic_state *state;
6380         int ret;
6381
6382         state = drm_atomic_helper_suspend(dev);
6383         ret = PTR_ERR_OR_ZERO(state);
6384         if (ret)
6385                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6386         else
6387                 dev_priv->modeset_restore_state = state;
6388         return ret;
6389 }
6390
6391 void intel_encoder_destroy(struct drm_encoder *encoder)
6392 {
6393         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6394
6395         drm_encoder_cleanup(encoder);
6396         kfree(intel_encoder);
6397 }
6398
6399 /* Cross check the actual hw state with our own modeset state tracking (and it's
6400  * internal consistency). */
6401 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6402                                          struct drm_connector_state *conn_state)
6403 {
6404         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6405
6406         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6407                       connector->base.base.id,
6408                       connector->base.name);
6409
6410         if (connector->get_hw_state(connector)) {
6411                 struct intel_encoder *encoder = connector->encoder;
6412
6413                 I915_STATE_WARN(!crtc_state,
6414                          "connector enabled without attached crtc\n");
6415
6416                 if (!crtc_state)
6417                         return;
6418
6419                 I915_STATE_WARN(!crtc_state->active,
6420                       "connector is active, but attached crtc isn't\n");
6421
6422                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6423                         return;
6424
6425                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6426                         "atomic encoder doesn't match attached encoder\n");
6427
6428                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6429                         "attached encoder crtc differs from connector crtc\n");
6430         } else {
6431                 I915_STATE_WARN(crtc_state && crtc_state->active,
6432                         "attached crtc is active, but connector isn't\n");
6433                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6434                         "best encoder set without crtc!\n");
6435         }
6436 }
6437
6438 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6439 {
6440         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6441                 return crtc_state->fdi_lanes;
6442
6443         return 0;
6444 }
6445
6446 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6447                                      struct intel_crtc_state *pipe_config)
6448 {
6449         struct drm_i915_private *dev_priv = to_i915(dev);
6450         struct drm_atomic_state *state = pipe_config->base.state;
6451         struct intel_crtc *other_crtc;
6452         struct intel_crtc_state *other_crtc_state;
6453
6454         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6455                       pipe_name(pipe), pipe_config->fdi_lanes);
6456         if (pipe_config->fdi_lanes > 4) {
6457                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6458                               pipe_name(pipe), pipe_config->fdi_lanes);
6459                 return -EINVAL;
6460         }
6461
6462         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6463                 if (pipe_config->fdi_lanes > 2) {
6464                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6465                                       pipe_config->fdi_lanes);
6466                         return -EINVAL;
6467                 } else {
6468                         return 0;
6469                 }
6470         }
6471
6472         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6473                 return 0;
6474
6475         /* Ivybridge 3 pipe is really complicated */
6476         switch (pipe) {
6477         case PIPE_A:
6478                 return 0;
6479         case PIPE_B:
6480                 if (pipe_config->fdi_lanes <= 2)
6481                         return 0;
6482
6483                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6484                 other_crtc_state =
6485                         intel_atomic_get_crtc_state(state, other_crtc);
6486                 if (IS_ERR(other_crtc_state))
6487                         return PTR_ERR(other_crtc_state);
6488
6489                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6490                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6491                                       pipe_name(pipe), pipe_config->fdi_lanes);
6492                         return -EINVAL;
6493                 }
6494                 return 0;
6495         case PIPE_C:
6496                 if (pipe_config->fdi_lanes > 2) {
6497                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6498                                       pipe_name(pipe), pipe_config->fdi_lanes);
6499                         return -EINVAL;
6500                 }
6501
6502                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6503                 other_crtc_state =
6504                         intel_atomic_get_crtc_state(state, other_crtc);
6505                 if (IS_ERR(other_crtc_state))
6506                         return PTR_ERR(other_crtc_state);
6507
6508                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6509                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6510                         return -EINVAL;
6511                 }
6512                 return 0;
6513         default:
6514                 BUG();
6515         }
6516 }
6517
6518 #define RETRY 1
6519 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6520                                        struct intel_crtc_state *pipe_config)
6521 {
6522         struct drm_device *dev = intel_crtc->base.dev;
6523         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6524         int lane, link_bw, fdi_dotclock, ret;
6525         bool needs_recompute = false;
6526
6527 retry:
6528         /* FDI is a binary signal running at ~2.7GHz, encoding
6529          * each output octet as 10 bits. The actual frequency
6530          * is stored as a divider into a 100MHz clock, and the
6531          * mode pixel clock is stored in units of 1KHz.
6532          * Hence the bw of each lane in terms of the mode signal
6533          * is:
6534          */
6535         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6536
6537         fdi_dotclock = adjusted_mode->crtc_clock;
6538
6539         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6540                                            pipe_config->pipe_bpp);
6541
6542         pipe_config->fdi_lanes = lane;
6543
6544         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6545                                link_bw, &pipe_config->fdi_m_n, false);
6546
6547         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6548         if (ret == -EDEADLK)
6549                 return ret;
6550
6551         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6552                 pipe_config->pipe_bpp -= 2*3;
6553                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6554                               pipe_config->pipe_bpp);
6555                 needs_recompute = true;
6556                 pipe_config->bw_constrained = true;
6557
6558                 goto retry;
6559         }
6560
6561         if (needs_recompute)
6562                 return RETRY;
6563
6564         return ret;
6565 }
6566
6567 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6568 {
6569         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6570         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6571
6572         /* IPS only exists on ULT machines and is tied to pipe A. */
6573         if (!hsw_crtc_supports_ips(crtc))
6574                 return false;
6575
6576         if (!i915_modparams.enable_ips)
6577                 return false;
6578
6579         if (crtc_state->pipe_bpp > 24)
6580                 return false;
6581
6582         /*
6583          * We compare against max which means we must take
6584          * the increased cdclk requirement into account when
6585          * calculating the new cdclk.
6586          *
6587          * Should measure whether using a lower cdclk w/o IPS
6588          */
6589         if (IS_BROADWELL(dev_priv) &&
6590             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6591                 return false;
6592
6593         return true;
6594 }
6595
6596 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6597 {
6598         struct drm_i915_private *dev_priv =
6599                 to_i915(crtc_state->base.crtc->dev);
6600         struct intel_atomic_state *intel_state =
6601                 to_intel_atomic_state(crtc_state->base.state);
6602
6603         if (!hsw_crtc_state_ips_capable(crtc_state))
6604                 return false;
6605
6606         if (crtc_state->ips_force_disable)
6607                 return false;
6608
6609         /* IPS should be fine as long as at least one plane is enabled. */
6610         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6611                 return false;
6612
6613         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6614         if (IS_BROADWELL(dev_priv) &&
6615             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6616                 return false;
6617
6618         return true;
6619 }
6620
6621 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6622 {
6623         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6624
6625         /* GDG double wide on either pipe, otherwise pipe A only */
6626         return INTEL_GEN(dev_priv) < 4 &&
6627                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6628 }
6629
6630 static u32 ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6631 {
6632         u32 pixel_rate;
6633
6634         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6635
6636         /*
6637          * We only use IF-ID interlacing. If we ever use
6638          * PF-ID we'll need to adjust the pixel_rate here.
6639          */
6640
6641         if (pipe_config->pch_pfit.enabled) {
6642                 u64 pipe_w, pipe_h, pfit_w, pfit_h;
6643                 u32 pfit_size = pipe_config->pch_pfit.size;
6644
6645                 pipe_w = pipe_config->pipe_src_w;
6646                 pipe_h = pipe_config->pipe_src_h;
6647
6648                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6649                 pfit_h = pfit_size & 0xFFFF;
6650                 if (pipe_w < pfit_w)
6651                         pipe_w = pfit_w;
6652                 if (pipe_h < pfit_h)
6653                         pipe_h = pfit_h;
6654
6655                 if (WARN_ON(!pfit_w || !pfit_h))
6656                         return pixel_rate;
6657
6658                 pixel_rate = div_u64((u64)pixel_rate * pipe_w * pipe_h,
6659                                      pfit_w * pfit_h);
6660         }
6661
6662         return pixel_rate;
6663 }
6664
6665 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6666 {
6667         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6668
6669         if (HAS_GMCH_DISPLAY(dev_priv))
6670                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6671                 crtc_state->pixel_rate =
6672                         crtc_state->base.adjusted_mode.crtc_clock;
6673         else
6674                 crtc_state->pixel_rate =
6675                         ilk_pipe_pixel_rate(crtc_state);
6676 }
6677
6678 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6679                                      struct intel_crtc_state *pipe_config)
6680 {
6681         struct drm_device *dev = crtc->base.dev;
6682         struct drm_i915_private *dev_priv = to_i915(dev);
6683         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6684         int clock_limit = dev_priv->max_dotclk_freq;
6685
6686         if (INTEL_GEN(dev_priv) < 4) {
6687                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6688
6689                 /*
6690                  * Enable double wide mode when the dot clock
6691                  * is > 90% of the (display) core speed.
6692                  */
6693                 if (intel_crtc_supports_double_wide(crtc) &&
6694                     adjusted_mode->crtc_clock > clock_limit) {
6695                         clock_limit = dev_priv->max_dotclk_freq;
6696                         pipe_config->double_wide = true;
6697                 }
6698         }
6699
6700         if (adjusted_mode->crtc_clock > clock_limit) {
6701                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6702                               adjusted_mode->crtc_clock, clock_limit,
6703                               yesno(pipe_config->double_wide));
6704                 return -EINVAL;
6705         }
6706
6707         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
6708              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
6709              pipe_config->base.ctm) {
6710                 /*
6711                  * There is only one pipe CSC unit per pipe, and we need that
6712                  * for output conversion from RGB->YCBCR. So if CTM is already
6713                  * applied we can't support YCBCR420 output.
6714                  */
6715                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6716                 return -EINVAL;
6717         }
6718
6719         /*
6720          * Pipe horizontal size must be even in:
6721          * - DVO ganged mode
6722          * - LVDS dual channel mode
6723          * - Double wide pipe
6724          */
6725         if (pipe_config->pipe_src_w & 1) {
6726                 if (pipe_config->double_wide) {
6727                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6728                         return -EINVAL;
6729                 }
6730
6731                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6732                     intel_is_dual_link_lvds(dev)) {
6733                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6734                         return -EINVAL;
6735                 }
6736         }
6737
6738         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6739          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6740          */
6741         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6742                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6743                 return -EINVAL;
6744
6745         intel_crtc_compute_pixel_rate(pipe_config);
6746
6747         if (pipe_config->has_pch_encoder)
6748                 return ironlake_fdi_compute_config(crtc, pipe_config);
6749
6750         return 0;
6751 }
6752
6753 static void
6754 intel_reduce_m_n_ratio(u32 *num, u32 *den)
6755 {
6756         while (*num > DATA_LINK_M_N_MASK ||
6757                *den > DATA_LINK_M_N_MASK) {
6758                 *num >>= 1;
6759                 *den >>= 1;
6760         }
6761 }
6762
6763 static void compute_m_n(unsigned int m, unsigned int n,
6764                         u32 *ret_m, u32 *ret_n,
6765                         bool constant_n)
6766 {
6767         /*
6768          * Several DP dongles in particular seem to be fussy about
6769          * too large link M/N values. Give N value as 0x8000 that
6770          * should be acceptable by specific devices. 0x8000 is the
6771          * specified fixed N value for asynchronous clock mode,
6772          * which the devices expect also in synchronous clock mode.
6773          */
6774         if (constant_n)
6775                 *ret_n = 0x8000;
6776         else
6777                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6778
6779         *ret_m = div_u64((u64)m * *ret_n, n);
6780         intel_reduce_m_n_ratio(ret_m, ret_n);
6781 }
6782
6783 void
6784 intel_link_compute_m_n(u16 bits_per_pixel, int nlanes,
6785                        int pixel_clock, int link_clock,
6786                        struct intel_link_m_n *m_n,
6787                        bool constant_n)
6788 {
6789         m_n->tu = 64;
6790
6791         compute_m_n(bits_per_pixel * pixel_clock,
6792                     link_clock * nlanes * 8,
6793                     &m_n->gmch_m, &m_n->gmch_n,
6794                     constant_n);
6795
6796         compute_m_n(pixel_clock, link_clock,
6797                     &m_n->link_m, &m_n->link_n,
6798                     constant_n);
6799 }
6800
6801 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6802 {
6803         if (i915_modparams.panel_use_ssc >= 0)
6804                 return i915_modparams.panel_use_ssc != 0;
6805         return dev_priv->vbt.lvds_use_ssc
6806                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6807 }
6808
6809 static u32 pnv_dpll_compute_fp(struct dpll *dpll)
6810 {
6811         return (1 << dpll->n) << 16 | dpll->m2;
6812 }
6813
6814 static u32 i9xx_dpll_compute_fp(struct dpll *dpll)
6815 {
6816         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6817 }
6818
6819 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6820                                      struct intel_crtc_state *crtc_state,
6821                                      struct dpll *reduced_clock)
6822 {
6823         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6824         u32 fp, fp2 = 0;
6825
6826         if (IS_PINEVIEW(dev_priv)) {
6827                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6828                 if (reduced_clock)
6829                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6830         } else {
6831                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6832                 if (reduced_clock)
6833                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6834         }
6835
6836         crtc_state->dpll_hw_state.fp0 = fp;
6837
6838         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6839             reduced_clock) {
6840                 crtc_state->dpll_hw_state.fp1 = fp2;
6841         } else {
6842                 crtc_state->dpll_hw_state.fp1 = fp;
6843         }
6844 }
6845
6846 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6847                 pipe)
6848 {
6849         u32 reg_val;
6850
6851         /*
6852          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6853          * and set it to a reasonable value instead.
6854          */
6855         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6856         reg_val &= 0xffffff00;
6857         reg_val |= 0x00000030;
6858         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6859
6860         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6861         reg_val &= 0x00ffffff;
6862         reg_val |= 0x8c000000;
6863         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6864
6865         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6866         reg_val &= 0xffffff00;
6867         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6868
6869         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6870         reg_val &= 0x00ffffff;
6871         reg_val |= 0xb0000000;
6872         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6873 }
6874
6875 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
6876                                          const struct intel_link_m_n *m_n)
6877 {
6878         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6879         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6880         enum pipe pipe = crtc->pipe;
6881
6882         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6883         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6884         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6885         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6886 }
6887
6888 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
6889                                  enum transcoder transcoder)
6890 {
6891         if (IS_HASWELL(dev_priv))
6892                 return transcoder == TRANSCODER_EDP;
6893
6894         /*
6895          * Strictly speaking some registers are available before
6896          * gen7, but we only support DRRS on gen7+
6897          */
6898         return IS_GEN(dev_priv, 7) || IS_CHERRYVIEW(dev_priv);
6899 }
6900
6901 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
6902                                          const struct intel_link_m_n *m_n,
6903                                          const struct intel_link_m_n *m2_n2)
6904 {
6905         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6906         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6907         enum pipe pipe = crtc->pipe;
6908         enum transcoder transcoder = crtc_state->cpu_transcoder;
6909
6910         if (INTEL_GEN(dev_priv) >= 5) {
6911                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6912                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6913                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6914                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6915                 /*
6916                  *  M2_N2 registers are set only if DRRS is supported
6917                  * (to make sure the registers are not unnecessarily accessed).
6918                  */
6919                 if (m2_n2 && crtc_state->has_drrs &&
6920                     transcoder_has_m2_n2(dev_priv, transcoder)) {
6921                         I915_WRITE(PIPE_DATA_M2(transcoder),
6922                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6923                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6924                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6925                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6926                 }
6927         } else {
6928                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6929                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6930                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6931                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6932         }
6933 }
6934
6935 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
6936 {
6937         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6938
6939         if (m_n == M1_N1) {
6940                 dp_m_n = &crtc_state->dp_m_n;
6941                 dp_m2_n2 = &crtc_state->dp_m2_n2;
6942         } else if (m_n == M2_N2) {
6943
6944                 /*
6945                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6946                  * needs to be programmed into M1_N1.
6947                  */
6948                 dp_m_n = &crtc_state->dp_m2_n2;
6949         } else {
6950                 DRM_ERROR("Unsupported divider value\n");
6951                 return;
6952         }
6953
6954         if (crtc_state->has_pch_encoder)
6955                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
6956         else
6957                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
6958 }
6959
6960 static void vlv_compute_dpll(struct intel_crtc *crtc,
6961                              struct intel_crtc_state *pipe_config)
6962 {
6963         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6964                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6965         if (crtc->pipe != PIPE_A)
6966                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6967
6968         /* DPLL not used with DSI, but still need the rest set up */
6969         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6970                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6971                         DPLL_EXT_BUFFER_ENABLE_VLV;
6972
6973         pipe_config->dpll_hw_state.dpll_md =
6974                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6975 }
6976
6977 static void chv_compute_dpll(struct intel_crtc *crtc,
6978                              struct intel_crtc_state *pipe_config)
6979 {
6980         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6981                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6982         if (crtc->pipe != PIPE_A)
6983                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6984
6985         /* DPLL not used with DSI, but still need the rest set up */
6986         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6987                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6988
6989         pipe_config->dpll_hw_state.dpll_md =
6990                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6991 }
6992
6993 static void vlv_prepare_pll(struct intel_crtc *crtc,
6994                             const struct intel_crtc_state *pipe_config)
6995 {
6996         struct drm_device *dev = crtc->base.dev;
6997         struct drm_i915_private *dev_priv = to_i915(dev);
6998         enum pipe pipe = crtc->pipe;
6999         u32 mdiv;
7000         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7001         u32 coreclk, reg_val;
7002
7003         /* Enable Refclk */
7004         I915_WRITE(DPLL(pipe),
7005                    pipe_config->dpll_hw_state.dpll &
7006                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7007
7008         /* No need to actually set up the DPLL with DSI */
7009         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7010                 return;
7011
7012         mutex_lock(&dev_priv->sb_lock);
7013
7014         bestn = pipe_config->dpll.n;
7015         bestm1 = pipe_config->dpll.m1;
7016         bestm2 = pipe_config->dpll.m2;
7017         bestp1 = pipe_config->dpll.p1;
7018         bestp2 = pipe_config->dpll.p2;
7019
7020         /* See eDP HDMI DPIO driver vbios notes doc */
7021
7022         /* PLL B needs special handling */
7023         if (pipe == PIPE_B)
7024                 vlv_pllb_recal_opamp(dev_priv, pipe);
7025
7026         /* Set up Tx target for periodic Rcomp update */
7027         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7028
7029         /* Disable target IRef on PLL */
7030         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7031         reg_val &= 0x00ffffff;
7032         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7033
7034         /* Disable fast lock */
7035         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7036
7037         /* Set idtafcrecal before PLL is enabled */
7038         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7039         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7040         mdiv |= ((bestn << DPIO_N_SHIFT));
7041         mdiv |= (1 << DPIO_K_SHIFT);
7042
7043         /*
7044          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7045          * but we don't support that).
7046          * Note: don't use the DAC post divider as it seems unstable.
7047          */
7048         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7049         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7050
7051         mdiv |= DPIO_ENABLE_CALIBRATION;
7052         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7053
7054         /* Set HBR and RBR LPF coefficients */
7055         if (pipe_config->port_clock == 162000 ||
7056             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
7057             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
7058                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7059                                  0x009f0003);
7060         else
7061                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7062                                  0x00d0000f);
7063
7064         if (intel_crtc_has_dp_encoder(pipe_config)) {
7065                 /* Use SSC source */
7066                 if (pipe == PIPE_A)
7067                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7068                                          0x0df40000);
7069                 else
7070                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7071                                          0x0df70000);
7072         } else { /* HDMI or VGA */
7073                 /* Use bend source */
7074                 if (pipe == PIPE_A)
7075                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7076                                          0x0df70000);
7077                 else
7078                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7079                                          0x0df40000);
7080         }
7081
7082         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7083         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7084         if (intel_crtc_has_dp_encoder(pipe_config))
7085                 coreclk |= 0x01000000;
7086         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7087
7088         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7089         mutex_unlock(&dev_priv->sb_lock);
7090 }
7091
7092 static void chv_prepare_pll(struct intel_crtc *crtc,
7093                             const struct intel_crtc_state *pipe_config)
7094 {
7095         struct drm_device *dev = crtc->base.dev;
7096         struct drm_i915_private *dev_priv = to_i915(dev);
7097         enum pipe pipe = crtc->pipe;
7098         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7099         u32 loopfilter, tribuf_calcntr;
7100         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7101         u32 dpio_val;
7102         int vco;
7103
7104         /* Enable Refclk and SSC */
7105         I915_WRITE(DPLL(pipe),
7106                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7107
7108         /* No need to actually set up the DPLL with DSI */
7109         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7110                 return;
7111
7112         bestn = pipe_config->dpll.n;
7113         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7114         bestm1 = pipe_config->dpll.m1;
7115         bestm2 = pipe_config->dpll.m2 >> 22;
7116         bestp1 = pipe_config->dpll.p1;
7117         bestp2 = pipe_config->dpll.p2;
7118         vco = pipe_config->dpll.vco;
7119         dpio_val = 0;
7120         loopfilter = 0;
7121
7122         mutex_lock(&dev_priv->sb_lock);
7123
7124         /* p1 and p2 divider */
7125         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7126                         5 << DPIO_CHV_S1_DIV_SHIFT |
7127                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7128                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7129                         1 << DPIO_CHV_K_DIV_SHIFT);
7130
7131         /* Feedback post-divider - m2 */
7132         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7133
7134         /* Feedback refclk divider - n and m1 */
7135         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7136                         DPIO_CHV_M1_DIV_BY_2 |
7137                         1 << DPIO_CHV_N_DIV_SHIFT);
7138
7139         /* M2 fraction division */
7140         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7141
7142         /* M2 fraction division enable */
7143         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7144         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7145         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7146         if (bestm2_frac)
7147                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7148         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7149
7150         /* Program digital lock detect threshold */
7151         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7152         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7153                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7154         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7155         if (!bestm2_frac)
7156                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7157         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7158
7159         /* Loop filter */
7160         if (vco == 5400000) {
7161                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7162                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7163                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7164                 tribuf_calcntr = 0x9;
7165         } else if (vco <= 6200000) {
7166                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7167                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7168                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7169                 tribuf_calcntr = 0x9;
7170         } else if (vco <= 6480000) {
7171                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7172                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7173                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7174                 tribuf_calcntr = 0x8;
7175         } else {
7176                 /* Not supported. Apply the same limits as in the max case */
7177                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7178                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7179                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7180                 tribuf_calcntr = 0;
7181         }
7182         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7183
7184         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7185         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7186         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7187         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7188
7189         /* AFC Recal */
7190         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7191                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7192                         DPIO_AFC_RECAL);
7193
7194         mutex_unlock(&dev_priv->sb_lock);
7195 }
7196
7197 /**
7198  * vlv_force_pll_on - forcibly enable just the PLL
7199  * @dev_priv: i915 private structure
7200  * @pipe: pipe PLL to enable
7201  * @dpll: PLL configuration
7202  *
7203  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7204  * in cases where we need the PLL enabled even when @pipe is not going to
7205  * be enabled.
7206  */
7207 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7208                      const struct dpll *dpll)
7209 {
7210         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7211         struct intel_crtc_state *pipe_config;
7212
7213         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7214         if (!pipe_config)
7215                 return -ENOMEM;
7216
7217         pipe_config->base.crtc = &crtc->base;
7218         pipe_config->pixel_multiplier = 1;
7219         pipe_config->dpll = *dpll;
7220
7221         if (IS_CHERRYVIEW(dev_priv)) {
7222                 chv_compute_dpll(crtc, pipe_config);
7223                 chv_prepare_pll(crtc, pipe_config);
7224                 chv_enable_pll(crtc, pipe_config);
7225         } else {
7226                 vlv_compute_dpll(crtc, pipe_config);
7227                 vlv_prepare_pll(crtc, pipe_config);
7228                 vlv_enable_pll(crtc, pipe_config);
7229         }
7230
7231         kfree(pipe_config);
7232
7233         return 0;
7234 }
7235
7236 /**
7237  * vlv_force_pll_off - forcibly disable just the PLL
7238  * @dev_priv: i915 private structure
7239  * @pipe: pipe PLL to disable
7240  *
7241  * Disable the PLL for @pipe. To be used in cases where we need
7242  * the PLL enabled even when @pipe is not going to be enabled.
7243  */
7244 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7245 {
7246         if (IS_CHERRYVIEW(dev_priv))
7247                 chv_disable_pll(dev_priv, pipe);
7248         else
7249                 vlv_disable_pll(dev_priv, pipe);
7250 }
7251
7252 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7253                               struct intel_crtc_state *crtc_state,
7254                               struct dpll *reduced_clock)
7255 {
7256         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7257         u32 dpll;
7258         struct dpll *clock = &crtc_state->dpll;
7259
7260         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7261
7262         dpll = DPLL_VGA_MODE_DIS;
7263
7264         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7265                 dpll |= DPLLB_MODE_LVDS;
7266         else
7267                 dpll |= DPLLB_MODE_DAC_SERIAL;
7268
7269         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7270             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7271                 dpll |= (crtc_state->pixel_multiplier - 1)
7272                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7273         }
7274
7275         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7276             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7277                 dpll |= DPLL_SDVO_HIGH_SPEED;
7278
7279         if (intel_crtc_has_dp_encoder(crtc_state))
7280                 dpll |= DPLL_SDVO_HIGH_SPEED;
7281
7282         /* compute bitmask from p1 value */
7283         if (IS_PINEVIEW(dev_priv))
7284                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7285         else {
7286                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7287                 if (IS_G4X(dev_priv) && reduced_clock)
7288                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7289         }
7290         switch (clock->p2) {
7291         case 5:
7292                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7293                 break;
7294         case 7:
7295                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7296                 break;
7297         case 10:
7298                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7299                 break;
7300         case 14:
7301                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7302                 break;
7303         }
7304         if (INTEL_GEN(dev_priv) >= 4)
7305                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7306
7307         if (crtc_state->sdvo_tv_clock)
7308                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7309         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7310                  intel_panel_use_ssc(dev_priv))
7311                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7312         else
7313                 dpll |= PLL_REF_INPUT_DREFCLK;
7314
7315         dpll |= DPLL_VCO_ENABLE;
7316         crtc_state->dpll_hw_state.dpll = dpll;
7317
7318         if (INTEL_GEN(dev_priv) >= 4) {
7319                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7320                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7321                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7322         }
7323 }
7324
7325 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7326                               struct intel_crtc_state *crtc_state,
7327                               struct dpll *reduced_clock)
7328 {
7329         struct drm_device *dev = crtc->base.dev;
7330         struct drm_i915_private *dev_priv = to_i915(dev);
7331         u32 dpll;
7332         struct dpll *clock = &crtc_state->dpll;
7333
7334         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7335
7336         dpll = DPLL_VGA_MODE_DIS;
7337
7338         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7339                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7340         } else {
7341                 if (clock->p1 == 2)
7342                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7343                 else
7344                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7345                 if (clock->p2 == 4)
7346                         dpll |= PLL_P2_DIVIDE_BY_4;
7347         }
7348
7349         if (!IS_I830(dev_priv) &&
7350             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7351                 dpll |= DPLL_DVO_2X_MODE;
7352
7353         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7354             intel_panel_use_ssc(dev_priv))
7355                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7356         else
7357                 dpll |= PLL_REF_INPUT_DREFCLK;
7358
7359         dpll |= DPLL_VCO_ENABLE;
7360         crtc_state->dpll_hw_state.dpll = dpll;
7361 }
7362
7363 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7364 {
7365         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7366         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7367         enum pipe pipe = crtc->pipe;
7368         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7369         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7370         u32 crtc_vtotal, crtc_vblank_end;
7371         int vsyncshift = 0;
7372
7373         /* We need to be careful not to changed the adjusted mode, for otherwise
7374          * the hw state checker will get angry at the mismatch. */
7375         crtc_vtotal = adjusted_mode->crtc_vtotal;
7376         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7377
7378         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7379                 /* the chip adds 2 halflines automatically */
7380                 crtc_vtotal -= 1;
7381                 crtc_vblank_end -= 1;
7382
7383                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7384                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7385                 else
7386                         vsyncshift = adjusted_mode->crtc_hsync_start -
7387                                 adjusted_mode->crtc_htotal / 2;
7388                 if (vsyncshift < 0)
7389                         vsyncshift += adjusted_mode->crtc_htotal;
7390         }
7391
7392         if (INTEL_GEN(dev_priv) > 3)
7393                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7394
7395         I915_WRITE(HTOTAL(cpu_transcoder),
7396                    (adjusted_mode->crtc_hdisplay - 1) |
7397                    ((adjusted_mode->crtc_htotal - 1) << 16));
7398         I915_WRITE(HBLANK(cpu_transcoder),
7399                    (adjusted_mode->crtc_hblank_start - 1) |
7400                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7401         I915_WRITE(HSYNC(cpu_transcoder),
7402                    (adjusted_mode->crtc_hsync_start - 1) |
7403                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7404
7405         I915_WRITE(VTOTAL(cpu_transcoder),
7406                    (adjusted_mode->crtc_vdisplay - 1) |
7407                    ((crtc_vtotal - 1) << 16));
7408         I915_WRITE(VBLANK(cpu_transcoder),
7409                    (adjusted_mode->crtc_vblank_start - 1) |
7410                    ((crtc_vblank_end - 1) << 16));
7411         I915_WRITE(VSYNC(cpu_transcoder),
7412                    (adjusted_mode->crtc_vsync_start - 1) |
7413                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7414
7415         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7416          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7417          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7418          * bits. */
7419         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7420             (pipe == PIPE_B || pipe == PIPE_C))
7421                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7422
7423 }
7424
7425 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
7426 {
7427         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7428         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7429         enum pipe pipe = crtc->pipe;
7430
7431         /* pipesrc controls the size that is scaled from, which should
7432          * always be the user's requested size.
7433          */
7434         I915_WRITE(PIPESRC(pipe),
7435                    ((crtc_state->pipe_src_w - 1) << 16) |
7436                    (crtc_state->pipe_src_h - 1));
7437 }
7438
7439 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7440                                    struct intel_crtc_state *pipe_config)
7441 {
7442         struct drm_device *dev = crtc->base.dev;
7443         struct drm_i915_private *dev_priv = to_i915(dev);
7444         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7445         u32 tmp;
7446
7447         tmp = I915_READ(HTOTAL(cpu_transcoder));
7448         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7449         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7450         tmp = I915_READ(HBLANK(cpu_transcoder));
7451         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7452         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7453         tmp = I915_READ(HSYNC(cpu_transcoder));
7454         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7455         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7456
7457         tmp = I915_READ(VTOTAL(cpu_transcoder));
7458         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7459         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7460         tmp = I915_READ(VBLANK(cpu_transcoder));
7461         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7462         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7463         tmp = I915_READ(VSYNC(cpu_transcoder));
7464         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7465         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7466
7467         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7468                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7469                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7470                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7471         }
7472 }
7473
7474 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7475                                     struct intel_crtc_state *pipe_config)
7476 {
7477         struct drm_device *dev = crtc->base.dev;
7478         struct drm_i915_private *dev_priv = to_i915(dev);
7479         u32 tmp;
7480
7481         tmp = I915_READ(PIPESRC(crtc->pipe));
7482         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7483         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7484
7485         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7486         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7487 }
7488
7489 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7490                                  struct intel_crtc_state *pipe_config)
7491 {
7492         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7493         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7494         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7495         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7496
7497         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7498         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7499         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7500         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7501
7502         mode->flags = pipe_config->base.adjusted_mode.flags;
7503         mode->type = DRM_MODE_TYPE_DRIVER;
7504
7505         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7506
7507         mode->hsync = drm_mode_hsync(mode);
7508         mode->vrefresh = drm_mode_vrefresh(mode);
7509         drm_mode_set_name(mode);
7510 }
7511
7512 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
7513 {
7514         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7515         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7516         u32 pipeconf;
7517
7518         pipeconf = 0;
7519
7520         /* we keep both pipes enabled on 830 */
7521         if (IS_I830(dev_priv))
7522                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
7523
7524         if (crtc_state->double_wide)
7525                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7526
7527         /* only g4x and later have fancy bpc/dither controls */
7528         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7529             IS_CHERRYVIEW(dev_priv)) {
7530                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7531                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
7532                         pipeconf |= PIPECONF_DITHER_EN |
7533                                     PIPECONF_DITHER_TYPE_SP;
7534
7535                 switch (crtc_state->pipe_bpp) {
7536                 case 18:
7537                         pipeconf |= PIPECONF_6BPC;
7538                         break;
7539                 case 24:
7540                         pipeconf |= PIPECONF_8BPC;
7541                         break;
7542                 case 30:
7543                         pipeconf |= PIPECONF_10BPC;
7544                         break;
7545                 default:
7546                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7547                         BUG();
7548                 }
7549         }
7550
7551         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7552                 if (INTEL_GEN(dev_priv) < 4 ||
7553                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7554                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7555                 else
7556                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7557         } else
7558                 pipeconf |= PIPECONF_PROGRESSIVE;
7559
7560         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7561              crtc_state->limited_color_range)
7562                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7563
7564         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
7565         POSTING_READ(PIPECONF(crtc->pipe));
7566 }
7567
7568 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7569                                    struct intel_crtc_state *crtc_state)
7570 {
7571         struct drm_device *dev = crtc->base.dev;
7572         struct drm_i915_private *dev_priv = to_i915(dev);
7573         const struct intel_limit *limit;
7574         int refclk = 48000;
7575
7576         memset(&crtc_state->dpll_hw_state, 0,
7577                sizeof(crtc_state->dpll_hw_state));
7578
7579         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7580                 if (intel_panel_use_ssc(dev_priv)) {
7581                         refclk = dev_priv->vbt.lvds_ssc_freq;
7582                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7583                 }
7584
7585                 limit = &intel_limits_i8xx_lvds;
7586         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7587                 limit = &intel_limits_i8xx_dvo;
7588         } else {
7589                 limit = &intel_limits_i8xx_dac;
7590         }
7591
7592         if (!crtc_state->clock_set &&
7593             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7594                                  refclk, NULL, &crtc_state->dpll)) {
7595                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7596                 return -EINVAL;
7597         }
7598
7599         i8xx_compute_dpll(crtc, crtc_state, NULL);
7600
7601         return 0;
7602 }
7603
7604 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7605                                   struct intel_crtc_state *crtc_state)
7606 {
7607         struct drm_device *dev = crtc->base.dev;
7608         struct drm_i915_private *dev_priv = to_i915(dev);
7609         const struct intel_limit *limit;
7610         int refclk = 96000;
7611
7612         memset(&crtc_state->dpll_hw_state, 0,
7613                sizeof(crtc_state->dpll_hw_state));
7614
7615         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7616                 if (intel_panel_use_ssc(dev_priv)) {
7617                         refclk = dev_priv->vbt.lvds_ssc_freq;
7618                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7619                 }
7620
7621                 if (intel_is_dual_link_lvds(dev))
7622                         limit = &intel_limits_g4x_dual_channel_lvds;
7623                 else
7624                         limit = &intel_limits_g4x_single_channel_lvds;
7625         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7626                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7627                 limit = &intel_limits_g4x_hdmi;
7628         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7629                 limit = &intel_limits_g4x_sdvo;
7630         } else {
7631                 /* The option is for other outputs */
7632                 limit = &intel_limits_i9xx_sdvo;
7633         }
7634
7635         if (!crtc_state->clock_set &&
7636             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7637                                 refclk, NULL, &crtc_state->dpll)) {
7638                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7639                 return -EINVAL;
7640         }
7641
7642         i9xx_compute_dpll(crtc, crtc_state, NULL);
7643
7644         return 0;
7645 }
7646
7647 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7648                                   struct intel_crtc_state *crtc_state)
7649 {
7650         struct drm_device *dev = crtc->base.dev;
7651         struct drm_i915_private *dev_priv = to_i915(dev);
7652         const struct intel_limit *limit;
7653         int refclk = 96000;
7654
7655         memset(&crtc_state->dpll_hw_state, 0,
7656                sizeof(crtc_state->dpll_hw_state));
7657
7658         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7659                 if (intel_panel_use_ssc(dev_priv)) {
7660                         refclk = dev_priv->vbt.lvds_ssc_freq;
7661                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7662                 }
7663
7664                 limit = &intel_limits_pineview_lvds;
7665         } else {
7666                 limit = &intel_limits_pineview_sdvo;
7667         }
7668
7669         if (!crtc_state->clock_set &&
7670             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7671                                 refclk, NULL, &crtc_state->dpll)) {
7672                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7673                 return -EINVAL;
7674         }
7675
7676         i9xx_compute_dpll(crtc, crtc_state, NULL);
7677
7678         return 0;
7679 }
7680
7681 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7682                                    struct intel_crtc_state *crtc_state)
7683 {
7684         struct drm_device *dev = crtc->base.dev;
7685         struct drm_i915_private *dev_priv = to_i915(dev);
7686         const struct intel_limit *limit;
7687         int refclk = 96000;
7688
7689         memset(&crtc_state->dpll_hw_state, 0,
7690                sizeof(crtc_state->dpll_hw_state));
7691
7692         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7693                 if (intel_panel_use_ssc(dev_priv)) {
7694                         refclk = dev_priv->vbt.lvds_ssc_freq;
7695                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7696                 }
7697
7698                 limit = &intel_limits_i9xx_lvds;
7699         } else {
7700                 limit = &intel_limits_i9xx_sdvo;
7701         }
7702
7703         if (!crtc_state->clock_set &&
7704             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7705                                  refclk, NULL, &crtc_state->dpll)) {
7706                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7707                 return -EINVAL;
7708         }
7709
7710         i9xx_compute_dpll(crtc, crtc_state, NULL);
7711
7712         return 0;
7713 }
7714
7715 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7716                                   struct intel_crtc_state *crtc_state)
7717 {
7718         int refclk = 100000;
7719         const struct intel_limit *limit = &intel_limits_chv;
7720
7721         memset(&crtc_state->dpll_hw_state, 0,
7722                sizeof(crtc_state->dpll_hw_state));
7723
7724         if (!crtc_state->clock_set &&
7725             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7726                                 refclk, NULL, &crtc_state->dpll)) {
7727                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7728                 return -EINVAL;
7729         }
7730
7731         chv_compute_dpll(crtc, crtc_state);
7732
7733         return 0;
7734 }
7735
7736 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7737                                   struct intel_crtc_state *crtc_state)
7738 {
7739         int refclk = 100000;
7740         const struct intel_limit *limit = &intel_limits_vlv;
7741
7742         memset(&crtc_state->dpll_hw_state, 0,
7743                sizeof(crtc_state->dpll_hw_state));
7744
7745         if (!crtc_state->clock_set &&
7746             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7747                                 refclk, NULL, &crtc_state->dpll)) {
7748                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7749                 return -EINVAL;
7750         }
7751
7752         vlv_compute_dpll(crtc, crtc_state);
7753
7754         return 0;
7755 }
7756
7757 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7758                                  struct intel_crtc_state *pipe_config)
7759 {
7760         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7761         u32 tmp;
7762
7763         if (INTEL_GEN(dev_priv) <= 3 &&
7764             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7765                 return;
7766
7767         tmp = I915_READ(PFIT_CONTROL);
7768         if (!(tmp & PFIT_ENABLE))
7769                 return;
7770
7771         /* Check whether the pfit is attached to our pipe. */
7772         if (INTEL_GEN(dev_priv) < 4) {
7773                 if (crtc->pipe != PIPE_B)
7774                         return;
7775         } else {
7776                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7777                         return;
7778         }
7779
7780         pipe_config->gmch_pfit.control = tmp;
7781         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7782 }
7783
7784 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7785                                struct intel_crtc_state *pipe_config)
7786 {
7787         struct drm_device *dev = crtc->base.dev;
7788         struct drm_i915_private *dev_priv = to_i915(dev);
7789         int pipe = pipe_config->cpu_transcoder;
7790         struct dpll clock;
7791         u32 mdiv;
7792         int refclk = 100000;
7793
7794         /* In case of DSI, DPLL will not be used */
7795         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7796                 return;
7797
7798         mutex_lock(&dev_priv->sb_lock);
7799         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7800         mutex_unlock(&dev_priv->sb_lock);
7801
7802         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7803         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7804         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7805         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7806         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7807
7808         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7809 }
7810
7811 static void
7812 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7813                               struct intel_initial_plane_config *plane_config)
7814 {
7815         struct drm_device *dev = crtc->base.dev;
7816         struct drm_i915_private *dev_priv = to_i915(dev);
7817         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7818         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7819         enum pipe pipe;
7820         u32 val, base, offset;
7821         int fourcc, pixel_format;
7822         unsigned int aligned_height;
7823         struct drm_framebuffer *fb;
7824         struct intel_framebuffer *intel_fb;
7825
7826         if (!plane->get_hw_state(plane, &pipe))
7827                 return;
7828
7829         WARN_ON(pipe != crtc->pipe);
7830
7831         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7832         if (!intel_fb) {
7833                 DRM_DEBUG_KMS("failed to alloc fb\n");
7834                 return;
7835         }
7836
7837         fb = &intel_fb->base;
7838
7839         fb->dev = dev;
7840
7841         val = I915_READ(DSPCNTR(i9xx_plane));
7842
7843         if (INTEL_GEN(dev_priv) >= 4) {
7844                 if (val & DISPPLANE_TILED) {
7845                         plane_config->tiling = I915_TILING_X;
7846                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7847                 }
7848
7849                 if (val & DISPPLANE_ROTATE_180)
7850                         plane_config->rotation = DRM_MODE_ROTATE_180;
7851         }
7852
7853         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B &&
7854             val & DISPPLANE_MIRROR)
7855                 plane_config->rotation |= DRM_MODE_REFLECT_X;
7856
7857         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7858         fourcc = i9xx_format_to_fourcc(pixel_format);
7859         fb->format = drm_format_info(fourcc);
7860
7861         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7862                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7863                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7864         } else if (INTEL_GEN(dev_priv) >= 4) {
7865                 if (plane_config->tiling)
7866                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7867                 else
7868                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7869                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7870         } else {
7871                 base = I915_READ(DSPADDR(i9xx_plane));
7872         }
7873         plane_config->base = base;
7874
7875         val = I915_READ(PIPESRC(pipe));
7876         fb->width = ((val >> 16) & 0xfff) + 1;
7877         fb->height = ((val >> 0) & 0xfff) + 1;
7878
7879         val = I915_READ(DSPSTRIDE(i9xx_plane));
7880         fb->pitches[0] = val & 0xffffffc0;
7881
7882         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7883
7884         plane_config->size = fb->pitches[0] * aligned_height;
7885
7886         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7887                       crtc->base.name, plane->base.name, fb->width, fb->height,
7888                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7889                       plane_config->size);
7890
7891         plane_config->fb = intel_fb;
7892 }
7893
7894 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7895                                struct intel_crtc_state *pipe_config)
7896 {
7897         struct drm_device *dev = crtc->base.dev;
7898         struct drm_i915_private *dev_priv = to_i915(dev);
7899         int pipe = pipe_config->cpu_transcoder;
7900         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7901         struct dpll clock;
7902         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7903         int refclk = 100000;
7904
7905         /* In case of DSI, DPLL will not be used */
7906         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7907                 return;
7908
7909         mutex_lock(&dev_priv->sb_lock);
7910         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7911         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7912         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7913         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7914         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7915         mutex_unlock(&dev_priv->sb_lock);
7916
7917         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7918         clock.m2 = (pll_dw0 & 0xff) << 22;
7919         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7920                 clock.m2 |= pll_dw2 & 0x3fffff;
7921         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7922         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7923         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7924
7925         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7926 }
7927
7928 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
7929                                         struct intel_crtc_state *pipe_config)
7930 {
7931         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7932         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
7933
7934         pipe_config->lspcon_downsampling = false;
7935
7936         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
7937                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
7938
7939                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
7940                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
7941                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
7942
7943                         if (ycbcr420_enabled) {
7944                                 /* We support 4:2:0 in full blend mode only */
7945                                 if (!blend)
7946                                         output = INTEL_OUTPUT_FORMAT_INVALID;
7947                                 else if (!(IS_GEMINILAKE(dev_priv) ||
7948                                            INTEL_GEN(dev_priv) >= 10))
7949                                         output = INTEL_OUTPUT_FORMAT_INVALID;
7950                                 else
7951                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
7952                         } else {
7953                                 /*
7954                                  * Currently there is no interface defined to
7955                                  * check user preference between RGB/YCBCR444
7956                                  * or YCBCR420. So the only possible case for
7957                                  * YCBCR444 usage is driving YCBCR420 output
7958                                  * with LSPCON, when pipe is configured for
7959                                  * YCBCR444 output and LSPCON takes care of
7960                                  * downsampling it.
7961                                  */
7962                                 pipe_config->lspcon_downsampling = true;
7963                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
7964                         }
7965                 }
7966         }
7967
7968         pipe_config->output_format = output;
7969 }
7970
7971 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7972                                  struct intel_crtc_state *pipe_config)
7973 {
7974         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7975         enum intel_display_power_domain power_domain;
7976         intel_wakeref_t wakeref;
7977         u32 tmp;
7978         bool ret;
7979
7980         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7981         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
7982         if (!wakeref)
7983                 return false;
7984
7985         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
7986         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7987         pipe_config->shared_dpll = NULL;
7988
7989         ret = false;
7990
7991         tmp = I915_READ(PIPECONF(crtc->pipe));
7992         if (!(tmp & PIPECONF_ENABLE))
7993                 goto out;
7994
7995         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7996             IS_CHERRYVIEW(dev_priv)) {
7997                 switch (tmp & PIPECONF_BPC_MASK) {
7998                 case PIPECONF_6BPC:
7999                         pipe_config->pipe_bpp = 18;
8000                         break;
8001                 case PIPECONF_8BPC:
8002                         pipe_config->pipe_bpp = 24;
8003                         break;
8004                 case PIPECONF_10BPC:
8005                         pipe_config->pipe_bpp = 30;
8006                         break;
8007                 default:
8008                         break;
8009                 }
8010         }
8011
8012         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8013             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8014                 pipe_config->limited_color_range = true;
8015
8016         if (INTEL_GEN(dev_priv) < 4)
8017                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8018
8019         intel_get_pipe_timings(crtc, pipe_config);
8020         intel_get_pipe_src_size(crtc, pipe_config);
8021
8022         i9xx_get_pfit_config(crtc, pipe_config);
8023
8024         if (INTEL_GEN(dev_priv) >= 4) {
8025                 /* No way to read it out on pipes B and C */
8026                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8027                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8028                 else
8029                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8030                 pipe_config->pixel_multiplier =
8031                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8032                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8033                 pipe_config->dpll_hw_state.dpll_md = tmp;
8034         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8035                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8036                 tmp = I915_READ(DPLL(crtc->pipe));
8037                 pipe_config->pixel_multiplier =
8038                         ((tmp & SDVO_MULTIPLIER_MASK)
8039                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8040         } else {
8041                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8042                  * port and will be fixed up in the encoder->get_config
8043                  * function. */
8044                 pipe_config->pixel_multiplier = 1;
8045         }
8046         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8047         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8048                 /*
8049                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8050                  * on 830. Filter it out here so that we don't
8051                  * report errors due to that.
8052                  */
8053                 if (IS_I830(dev_priv))
8054                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8055
8056                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8057                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8058         } else {
8059                 /* Mask out read-only status bits. */
8060                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8061                                                      DPLL_PORTC_READY_MASK |
8062                                                      DPLL_PORTB_READY_MASK);
8063         }
8064
8065         if (IS_CHERRYVIEW(dev_priv))
8066                 chv_crtc_clock_get(crtc, pipe_config);
8067         else if (IS_VALLEYVIEW(dev_priv))
8068                 vlv_crtc_clock_get(crtc, pipe_config);
8069         else
8070                 i9xx_crtc_clock_get(crtc, pipe_config);
8071
8072         /*
8073          * Normally the dotclock is filled in by the encoder .get_config()
8074          * but in case the pipe is enabled w/o any ports we need a sane
8075          * default.
8076          */
8077         pipe_config->base.adjusted_mode.crtc_clock =
8078                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8079
8080         ret = true;
8081
8082 out:
8083         intel_display_power_put(dev_priv, power_domain, wakeref);
8084
8085         return ret;
8086 }
8087
8088 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8089 {
8090         struct intel_encoder *encoder;
8091         int i;
8092         u32 val, final;
8093         bool has_lvds = false;
8094         bool has_cpu_edp = false;
8095         bool has_panel = false;
8096         bool has_ck505 = false;
8097         bool can_ssc = false;
8098         bool using_ssc_source = false;
8099
8100         /* We need to take the global config into account */
8101         for_each_intel_encoder(&dev_priv->drm, encoder) {
8102                 switch (encoder->type) {
8103                 case INTEL_OUTPUT_LVDS:
8104                         has_panel = true;
8105                         has_lvds = true;
8106                         break;
8107                 case INTEL_OUTPUT_EDP:
8108                         has_panel = true;
8109                         if (encoder->port == PORT_A)
8110                                 has_cpu_edp = true;
8111                         break;
8112                 default:
8113                         break;
8114                 }
8115         }
8116
8117         if (HAS_PCH_IBX(dev_priv)) {
8118                 has_ck505 = dev_priv->vbt.display_clock_mode;
8119                 can_ssc = has_ck505;
8120         } else {
8121                 has_ck505 = false;
8122                 can_ssc = true;
8123         }
8124
8125         /* Check if any DPLLs are using the SSC source */
8126         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8127                 u32 temp = I915_READ(PCH_DPLL(i));
8128
8129                 if (!(temp & DPLL_VCO_ENABLE))
8130                         continue;
8131
8132                 if ((temp & PLL_REF_INPUT_MASK) ==
8133                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8134                         using_ssc_source = true;
8135                         break;
8136                 }
8137         }
8138
8139         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8140                       has_panel, has_lvds, has_ck505, using_ssc_source);
8141
8142         /* Ironlake: try to setup display ref clock before DPLL
8143          * enabling. This is only under driver's control after
8144          * PCH B stepping, previous chipset stepping should be
8145          * ignoring this setting.
8146          */
8147         val = I915_READ(PCH_DREF_CONTROL);
8148
8149         /* As we must carefully and slowly disable/enable each source in turn,
8150          * compute the final state we want first and check if we need to
8151          * make any changes at all.
8152          */
8153         final = val;
8154         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8155         if (has_ck505)
8156                 final |= DREF_NONSPREAD_CK505_ENABLE;
8157         else
8158                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8159
8160         final &= ~DREF_SSC_SOURCE_MASK;
8161         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8162         final &= ~DREF_SSC1_ENABLE;
8163
8164         if (has_panel) {
8165                 final |= DREF_SSC_SOURCE_ENABLE;
8166
8167                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8168                         final |= DREF_SSC1_ENABLE;
8169
8170                 if (has_cpu_edp) {
8171                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8172                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8173                         else
8174                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8175                 } else
8176                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8177         } else if (using_ssc_source) {
8178                 final |= DREF_SSC_SOURCE_ENABLE;
8179                 final |= DREF_SSC1_ENABLE;
8180         }
8181
8182         if (final == val)
8183                 return;
8184
8185         /* Always enable nonspread source */
8186         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8187
8188         if (has_ck505)
8189                 val |= DREF_NONSPREAD_CK505_ENABLE;
8190         else
8191                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8192
8193         if (has_panel) {
8194                 val &= ~DREF_SSC_SOURCE_MASK;
8195                 val |= DREF_SSC_SOURCE_ENABLE;
8196
8197                 /* SSC must be turned on before enabling the CPU output  */
8198                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8199                         DRM_DEBUG_KMS("Using SSC on panel\n");
8200                         val |= DREF_SSC1_ENABLE;
8201                 } else
8202                         val &= ~DREF_SSC1_ENABLE;
8203
8204                 /* Get SSC going before enabling the outputs */
8205                 I915_WRITE(PCH_DREF_CONTROL, val);
8206                 POSTING_READ(PCH_DREF_CONTROL);
8207                 udelay(200);
8208
8209                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8210
8211                 /* Enable CPU source on CPU attached eDP */
8212                 if (has_cpu_edp) {
8213                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8214                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8215                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8216                         } else
8217                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8218                 } else
8219                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8220
8221                 I915_WRITE(PCH_DREF_CONTROL, val);
8222                 POSTING_READ(PCH_DREF_CONTROL);
8223                 udelay(200);
8224         } else {
8225                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8226
8227                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8228
8229                 /* Turn off CPU output */
8230                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8231
8232                 I915_WRITE(PCH_DREF_CONTROL, val);
8233                 POSTING_READ(PCH_DREF_CONTROL);
8234                 udelay(200);
8235
8236                 if (!using_ssc_source) {
8237                         DRM_DEBUG_KMS("Disabling SSC source\n");
8238
8239                         /* Turn off the SSC source */
8240                         val &= ~DREF_SSC_SOURCE_MASK;
8241                         val |= DREF_SSC_SOURCE_DISABLE;
8242
8243                         /* Turn off SSC1 */
8244                         val &= ~DREF_SSC1_ENABLE;
8245
8246                         I915_WRITE(PCH_DREF_CONTROL, val);
8247                         POSTING_READ(PCH_DREF_CONTROL);
8248                         udelay(200);
8249                 }
8250         }
8251
8252         BUG_ON(val != final);
8253 }
8254
8255 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8256 {
8257         u32 tmp;
8258
8259         tmp = I915_READ(SOUTH_CHICKEN2);
8260         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8261         I915_WRITE(SOUTH_CHICKEN2, tmp);
8262
8263         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8264                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8265                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8266
8267         tmp = I915_READ(SOUTH_CHICKEN2);
8268         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8269         I915_WRITE(SOUTH_CHICKEN2, tmp);
8270
8271         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8272                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8273                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8274 }
8275
8276 /* WaMPhyProgramming:hsw */
8277 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8278 {
8279         u32 tmp;
8280
8281         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8282         tmp &= ~(0xFF << 24);
8283         tmp |= (0x12 << 24);
8284         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8285
8286         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8287         tmp |= (1 << 11);
8288         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8289
8290         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8291         tmp |= (1 << 11);
8292         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8293
8294         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8295         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8296         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8297
8298         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8299         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8300         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8301
8302         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8303         tmp &= ~(7 << 13);
8304         tmp |= (5 << 13);
8305         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8306
8307         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8308         tmp &= ~(7 << 13);
8309         tmp |= (5 << 13);
8310         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8311
8312         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8313         tmp &= ~0xFF;
8314         tmp |= 0x1C;
8315         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8316
8317         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8318         tmp &= ~0xFF;
8319         tmp |= 0x1C;
8320         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8321
8322         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8323         tmp &= ~(0xFF << 16);
8324         tmp |= (0x1C << 16);
8325         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8326
8327         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8328         tmp &= ~(0xFF << 16);
8329         tmp |= (0x1C << 16);
8330         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8331
8332         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8333         tmp |= (1 << 27);
8334         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8335
8336         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8337         tmp |= (1 << 27);
8338         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8339
8340         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8341         tmp &= ~(0xF << 28);
8342         tmp |= (4 << 28);
8343         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8344
8345         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8346         tmp &= ~(0xF << 28);
8347         tmp |= (4 << 28);
8348         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8349 }
8350
8351 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8352  * Programming" based on the parameters passed:
8353  * - Sequence to enable CLKOUT_DP
8354  * - Sequence to enable CLKOUT_DP without spread
8355  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8356  */
8357 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8358                                  bool with_spread, bool with_fdi)
8359 {
8360         u32 reg, tmp;
8361
8362         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8363                 with_spread = true;
8364         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8365             with_fdi, "LP PCH doesn't have FDI\n"))
8366                 with_fdi = false;
8367
8368         mutex_lock(&dev_priv->sb_lock);
8369
8370         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8371         tmp &= ~SBI_SSCCTL_DISABLE;
8372         tmp |= SBI_SSCCTL_PATHALT;
8373         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8374
8375         udelay(24);
8376
8377         if (with_spread) {
8378                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8379                 tmp &= ~SBI_SSCCTL_PATHALT;
8380                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8381
8382                 if (with_fdi) {
8383                         lpt_reset_fdi_mphy(dev_priv);
8384                         lpt_program_fdi_mphy(dev_priv);
8385                 }
8386         }
8387
8388         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8389         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8390         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8391         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8392
8393         mutex_unlock(&dev_priv->sb_lock);
8394 }
8395
8396 /* Sequence to disable CLKOUT_DP */
8397 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8398 {
8399         u32 reg, tmp;
8400
8401         mutex_lock(&dev_priv->sb_lock);
8402
8403         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8404         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8405         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8406         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8407
8408         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8409         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8410                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8411                         tmp |= SBI_SSCCTL_PATHALT;
8412                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8413                         udelay(32);
8414                 }
8415                 tmp |= SBI_SSCCTL_DISABLE;
8416                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8417         }
8418
8419         mutex_unlock(&dev_priv->sb_lock);
8420 }
8421
8422 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8423
8424 static const u16 sscdivintphase[] = {
8425         [BEND_IDX( 50)] = 0x3B23,
8426         [BEND_IDX( 45)] = 0x3B23,
8427         [BEND_IDX( 40)] = 0x3C23,
8428         [BEND_IDX( 35)] = 0x3C23,
8429         [BEND_IDX( 30)] = 0x3D23,
8430         [BEND_IDX( 25)] = 0x3D23,
8431         [BEND_IDX( 20)] = 0x3E23,
8432         [BEND_IDX( 15)] = 0x3E23,
8433         [BEND_IDX( 10)] = 0x3F23,
8434         [BEND_IDX(  5)] = 0x3F23,
8435         [BEND_IDX(  0)] = 0x0025,
8436         [BEND_IDX( -5)] = 0x0025,
8437         [BEND_IDX(-10)] = 0x0125,
8438         [BEND_IDX(-15)] = 0x0125,
8439         [BEND_IDX(-20)] = 0x0225,
8440         [BEND_IDX(-25)] = 0x0225,
8441         [BEND_IDX(-30)] = 0x0325,
8442         [BEND_IDX(-35)] = 0x0325,
8443         [BEND_IDX(-40)] = 0x0425,
8444         [BEND_IDX(-45)] = 0x0425,
8445         [BEND_IDX(-50)] = 0x0525,
8446 };
8447
8448 /*
8449  * Bend CLKOUT_DP
8450  * steps -50 to 50 inclusive, in steps of 5
8451  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8452  * change in clock period = -(steps / 10) * 5.787 ps
8453  */
8454 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8455 {
8456         u32 tmp;
8457         int idx = BEND_IDX(steps);
8458
8459         if (WARN_ON(steps % 5 != 0))
8460                 return;
8461
8462         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8463                 return;
8464
8465         mutex_lock(&dev_priv->sb_lock);
8466
8467         if (steps % 10 != 0)
8468                 tmp = 0xAAAAAAAB;
8469         else
8470                 tmp = 0x00000000;
8471         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8472
8473         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8474         tmp &= 0xffff0000;
8475         tmp |= sscdivintphase[idx];
8476         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8477
8478         mutex_unlock(&dev_priv->sb_lock);
8479 }
8480
8481 #undef BEND_IDX
8482
8483 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8484 {
8485         struct intel_encoder *encoder;
8486         bool has_vga = false;
8487
8488         for_each_intel_encoder(&dev_priv->drm, encoder) {
8489                 switch (encoder->type) {
8490                 case INTEL_OUTPUT_ANALOG:
8491                         has_vga = true;
8492                         break;
8493                 default:
8494                         break;
8495                 }
8496         }
8497
8498         if (has_vga) {
8499                 lpt_bend_clkout_dp(dev_priv, 0);
8500                 lpt_enable_clkout_dp(dev_priv, true, true);
8501         } else {
8502                 lpt_disable_clkout_dp(dev_priv);
8503         }
8504 }
8505
8506 /*
8507  * Initialize reference clocks when the driver loads
8508  */
8509 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8510 {
8511         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8512                 ironlake_init_pch_refclk(dev_priv);
8513         else if (HAS_PCH_LPT(dev_priv))
8514                 lpt_init_pch_refclk(dev_priv);
8515 }
8516
8517 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
8518 {
8519         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8520         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8521         enum pipe pipe = crtc->pipe;
8522         u32 val;
8523
8524         val = 0;
8525
8526         switch (crtc_state->pipe_bpp) {
8527         case 18:
8528                 val |= PIPECONF_6BPC;
8529                 break;
8530         case 24:
8531                 val |= PIPECONF_8BPC;
8532                 break;
8533         case 30:
8534                 val |= PIPECONF_10BPC;
8535                 break;
8536         case 36:
8537                 val |= PIPECONF_12BPC;
8538                 break;
8539         default:
8540                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8541                 BUG();
8542         }
8543
8544         if (crtc_state->dither)
8545                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8546
8547         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8548                 val |= PIPECONF_INTERLACED_ILK;
8549         else
8550                 val |= PIPECONF_PROGRESSIVE;
8551
8552         if (crtc_state->limited_color_range)
8553                 val |= PIPECONF_COLOR_RANGE_SELECT;
8554
8555         I915_WRITE(PIPECONF(pipe), val);
8556         POSTING_READ(PIPECONF(pipe));
8557 }
8558
8559 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
8560 {
8561         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8562         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8563         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
8564         u32 val = 0;
8565
8566         if (IS_HASWELL(dev_priv) && crtc_state->dither)
8567                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8568
8569         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8570                 val |= PIPECONF_INTERLACED_ILK;
8571         else
8572                 val |= PIPECONF_PROGRESSIVE;
8573
8574         I915_WRITE(PIPECONF(cpu_transcoder), val);
8575         POSTING_READ(PIPECONF(cpu_transcoder));
8576 }
8577
8578 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state)
8579 {
8580         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
8581         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8582
8583         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8584                 u32 val = 0;
8585
8586                 switch (crtc_state->pipe_bpp) {
8587                 case 18:
8588                         val |= PIPEMISC_DITHER_6_BPC;
8589                         break;
8590                 case 24:
8591                         val |= PIPEMISC_DITHER_8_BPC;
8592                         break;
8593                 case 30:
8594                         val |= PIPEMISC_DITHER_10_BPC;
8595                         break;
8596                 case 36:
8597                         val |= PIPEMISC_DITHER_12_BPC;
8598                         break;
8599                 default:
8600                         /* Case prevented by pipe_config_set_bpp. */
8601                         BUG();
8602                 }
8603
8604                 if (crtc_state->dither)
8605                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8606
8607                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
8608                     crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
8609                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
8610
8611                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
8612                         val |= PIPEMISC_YUV420_ENABLE |
8613                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8614
8615                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8616         }
8617 }
8618
8619 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8620 {
8621         /*
8622          * Account for spread spectrum to avoid
8623          * oversubscribing the link. Max center spread
8624          * is 2.5%; use 5% for safety's sake.
8625          */
8626         u32 bps = target_clock * bpp * 21 / 20;
8627         return DIV_ROUND_UP(bps, link_bw * 8);
8628 }
8629
8630 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8631 {
8632         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8633 }
8634
8635 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8636                                   struct intel_crtc_state *crtc_state,
8637                                   struct dpll *reduced_clock)
8638 {
8639         struct drm_crtc *crtc = &intel_crtc->base;
8640         struct drm_device *dev = crtc->dev;
8641         struct drm_i915_private *dev_priv = to_i915(dev);
8642         u32 dpll, fp, fp2;
8643         int factor;
8644
8645         /* Enable autotuning of the PLL clock (if permissible) */
8646         factor = 21;
8647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8648                 if ((intel_panel_use_ssc(dev_priv) &&
8649                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8650                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8651                         factor = 25;
8652         } else if (crtc_state->sdvo_tv_clock)
8653                 factor = 20;
8654
8655         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8656
8657         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8658                 fp |= FP_CB_TUNE;
8659
8660         if (reduced_clock) {
8661                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8662
8663                 if (reduced_clock->m < factor * reduced_clock->n)
8664                         fp2 |= FP_CB_TUNE;
8665         } else {
8666                 fp2 = fp;
8667         }
8668
8669         dpll = 0;
8670
8671         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8672                 dpll |= DPLLB_MODE_LVDS;
8673         else
8674                 dpll |= DPLLB_MODE_DAC_SERIAL;
8675
8676         dpll |= (crtc_state->pixel_multiplier - 1)
8677                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8678
8679         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8680             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8681                 dpll |= DPLL_SDVO_HIGH_SPEED;
8682
8683         if (intel_crtc_has_dp_encoder(crtc_state))
8684                 dpll |= DPLL_SDVO_HIGH_SPEED;
8685
8686         /*
8687          * The high speed IO clock is only really required for
8688          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8689          * possible to share the DPLL between CRT and HDMI. Enabling
8690          * the clock needlessly does no real harm, except use up a
8691          * bit of power potentially.
8692          *
8693          * We'll limit this to IVB with 3 pipes, since it has only two
8694          * DPLLs and so DPLL sharing is the only way to get three pipes
8695          * driving PCH ports at the same time. On SNB we could do this,
8696          * and potentially avoid enabling the second DPLL, but it's not
8697          * clear if it''s a win or loss power wise. No point in doing
8698          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8699          */
8700         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8701             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8702                 dpll |= DPLL_SDVO_HIGH_SPEED;
8703
8704         /* compute bitmask from p1 value */
8705         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8706         /* also FPA1 */
8707         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8708
8709         switch (crtc_state->dpll.p2) {
8710         case 5:
8711                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8712                 break;
8713         case 7:
8714                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8715                 break;
8716         case 10:
8717                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8718                 break;
8719         case 14:
8720                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8721                 break;
8722         }
8723
8724         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8725             intel_panel_use_ssc(dev_priv))
8726                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8727         else
8728                 dpll |= PLL_REF_INPUT_DREFCLK;
8729
8730         dpll |= DPLL_VCO_ENABLE;
8731
8732         crtc_state->dpll_hw_state.dpll = dpll;
8733         crtc_state->dpll_hw_state.fp0 = fp;
8734         crtc_state->dpll_hw_state.fp1 = fp2;
8735 }
8736
8737 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8738                                        struct intel_crtc_state *crtc_state)
8739 {
8740         struct drm_device *dev = crtc->base.dev;
8741         struct drm_i915_private *dev_priv = to_i915(dev);
8742         const struct intel_limit *limit;
8743         int refclk = 120000;
8744
8745         memset(&crtc_state->dpll_hw_state, 0,
8746                sizeof(crtc_state->dpll_hw_state));
8747
8748         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8749         if (!crtc_state->has_pch_encoder)
8750                 return 0;
8751
8752         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8753                 if (intel_panel_use_ssc(dev_priv)) {
8754                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8755                                       dev_priv->vbt.lvds_ssc_freq);
8756                         refclk = dev_priv->vbt.lvds_ssc_freq;
8757                 }
8758
8759                 if (intel_is_dual_link_lvds(dev)) {
8760                         if (refclk == 100000)
8761                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8762                         else
8763                                 limit = &intel_limits_ironlake_dual_lvds;
8764                 } else {
8765                         if (refclk == 100000)
8766                                 limit = &intel_limits_ironlake_single_lvds_100m;
8767                         else
8768                                 limit = &intel_limits_ironlake_single_lvds;
8769                 }
8770         } else {
8771                 limit = &intel_limits_ironlake_dac;
8772         }
8773
8774         if (!crtc_state->clock_set &&
8775             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8776                                 refclk, NULL, &crtc_state->dpll)) {
8777                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8778                 return -EINVAL;
8779         }
8780
8781         ironlake_compute_dpll(crtc, crtc_state, NULL);
8782
8783         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8784                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
8785                               pipe_name(crtc->pipe));
8786                 return -EINVAL;
8787         }
8788
8789         return 0;
8790 }
8791
8792 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8793                                          struct intel_link_m_n *m_n)
8794 {
8795         struct drm_device *dev = crtc->base.dev;
8796         struct drm_i915_private *dev_priv = to_i915(dev);
8797         enum pipe pipe = crtc->pipe;
8798
8799         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8800         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8801         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8802                 & ~TU_SIZE_MASK;
8803         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8804         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8805                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8806 }
8807
8808 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8809                                          enum transcoder transcoder,
8810                                          struct intel_link_m_n *m_n,
8811                                          struct intel_link_m_n *m2_n2)
8812 {
8813         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8814         enum pipe pipe = crtc->pipe;
8815
8816         if (INTEL_GEN(dev_priv) >= 5) {
8817                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8818                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8819                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8820                         & ~TU_SIZE_MASK;
8821                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8822                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8823                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8824
8825                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
8826                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8827                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8828                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8829                                         & ~TU_SIZE_MASK;
8830                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8831                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8832                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8833                 }
8834         } else {
8835                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8836                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8837                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8838                         & ~TU_SIZE_MASK;
8839                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8840                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8841                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8842         }
8843 }
8844
8845 void intel_dp_get_m_n(struct intel_crtc *crtc,
8846                       struct intel_crtc_state *pipe_config)
8847 {
8848         if (pipe_config->has_pch_encoder)
8849                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8850         else
8851                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8852                                              &pipe_config->dp_m_n,
8853                                              &pipe_config->dp_m2_n2);
8854 }
8855
8856 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8857                                         struct intel_crtc_state *pipe_config)
8858 {
8859         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8860                                      &pipe_config->fdi_m_n, NULL);
8861 }
8862
8863 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8864                                     struct intel_crtc_state *pipe_config)
8865 {
8866         struct drm_device *dev = crtc->base.dev;
8867         struct drm_i915_private *dev_priv = to_i915(dev);
8868         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8869         u32 ps_ctrl = 0;
8870         int id = -1;
8871         int i;
8872
8873         /* find scaler attached to this pipe */
8874         for (i = 0; i < crtc->num_scalers; i++) {
8875                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8876                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8877                         id = i;
8878                         pipe_config->pch_pfit.enabled = true;
8879                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8880                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8881                         scaler_state->scalers[i].in_use = true;
8882                         break;
8883                 }
8884         }
8885
8886         scaler_state->scaler_id = id;
8887         if (id >= 0) {
8888                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8889         } else {
8890                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8891         }
8892 }
8893
8894 static void
8895 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8896                                  struct intel_initial_plane_config *plane_config)
8897 {
8898         struct drm_device *dev = crtc->base.dev;
8899         struct drm_i915_private *dev_priv = to_i915(dev);
8900         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8901         enum plane_id plane_id = plane->id;
8902         enum pipe pipe;
8903         u32 val, base, offset, stride_mult, tiling, alpha;
8904         int fourcc, pixel_format;
8905         unsigned int aligned_height;
8906         struct drm_framebuffer *fb;
8907         struct intel_framebuffer *intel_fb;
8908
8909         if (!plane->get_hw_state(plane, &pipe))
8910                 return;
8911
8912         WARN_ON(pipe != crtc->pipe);
8913
8914         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8915         if (!intel_fb) {
8916                 DRM_DEBUG_KMS("failed to alloc fb\n");
8917                 return;
8918         }
8919
8920         fb = &intel_fb->base;
8921
8922         fb->dev = dev;
8923
8924         val = I915_READ(PLANE_CTL(pipe, plane_id));
8925
8926         if (INTEL_GEN(dev_priv) >= 11)
8927                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8928         else
8929                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8930
8931         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8932                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8933                 alpha &= PLANE_COLOR_ALPHA_MASK;
8934         } else {
8935                 alpha = val & PLANE_CTL_ALPHA_MASK;
8936         }
8937
8938         fourcc = skl_format_to_fourcc(pixel_format,
8939                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8940         fb->format = drm_format_info(fourcc);
8941
8942         tiling = val & PLANE_CTL_TILED_MASK;
8943         switch (tiling) {
8944         case PLANE_CTL_TILED_LINEAR:
8945                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8946                 break;
8947         case PLANE_CTL_TILED_X:
8948                 plane_config->tiling = I915_TILING_X;
8949                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8950                 break;
8951         case PLANE_CTL_TILED_Y:
8952                 plane_config->tiling = I915_TILING_Y;
8953                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8954                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8955                 else
8956                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8957                 break;
8958         case PLANE_CTL_TILED_YF:
8959                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8960                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8961                 else
8962                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8963                 break;
8964         default:
8965                 MISSING_CASE(tiling);
8966                 goto error;
8967         }
8968
8969         /*
8970          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
8971          * while i915 HW rotation is clockwise, thats why this swapping.
8972          */
8973         switch (val & PLANE_CTL_ROTATE_MASK) {
8974         case PLANE_CTL_ROTATE_0:
8975                 plane_config->rotation = DRM_MODE_ROTATE_0;
8976                 break;
8977         case PLANE_CTL_ROTATE_90:
8978                 plane_config->rotation = DRM_MODE_ROTATE_270;
8979                 break;
8980         case PLANE_CTL_ROTATE_180:
8981                 plane_config->rotation = DRM_MODE_ROTATE_180;
8982                 break;
8983         case PLANE_CTL_ROTATE_270:
8984                 plane_config->rotation = DRM_MODE_ROTATE_90;
8985                 break;
8986         }
8987
8988         if (INTEL_GEN(dev_priv) >= 10 &&
8989             val & PLANE_CTL_FLIP_HORIZONTAL)
8990                 plane_config->rotation |= DRM_MODE_REFLECT_X;
8991
8992         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8993         plane_config->base = base;
8994
8995         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8996
8997         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8998         fb->height = ((val >> 16) & 0xfff) + 1;
8999         fb->width = ((val >> 0) & 0x1fff) + 1;
9000
9001         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
9002         stride_mult = skl_plane_stride_mult(fb, 0, DRM_MODE_ROTATE_0);
9003         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9004
9005         aligned_height = intel_fb_align_height(fb, 0, fb->height);
9006
9007         plane_config->size = fb->pitches[0] * aligned_height;
9008
9009         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9010                       crtc->base.name, plane->base.name, fb->width, fb->height,
9011                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9012                       plane_config->size);
9013
9014         plane_config->fb = intel_fb;
9015         return;
9016
9017 error:
9018         kfree(intel_fb);
9019 }
9020
9021 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9022                                      struct intel_crtc_state *pipe_config)
9023 {
9024         struct drm_device *dev = crtc->base.dev;
9025         struct drm_i915_private *dev_priv = to_i915(dev);
9026         u32 tmp;
9027
9028         tmp = I915_READ(PF_CTL(crtc->pipe));
9029
9030         if (tmp & PF_ENABLE) {
9031                 pipe_config->pch_pfit.enabled = true;
9032                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9033                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9034
9035                 /* We currently do not free assignements of panel fitters on
9036                  * ivb/hsw (since we don't use the higher upscaling modes which
9037                  * differentiates them) so just WARN about this case for now. */
9038                 if (IS_GEN(dev_priv, 7)) {
9039                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9040                                 PF_PIPE_SEL_IVB(crtc->pipe));
9041                 }
9042         }
9043 }
9044
9045 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9046                                      struct intel_crtc_state *pipe_config)
9047 {
9048         struct drm_device *dev = crtc->base.dev;
9049         struct drm_i915_private *dev_priv = to_i915(dev);
9050         enum intel_display_power_domain power_domain;
9051         intel_wakeref_t wakeref;
9052         u32 tmp;
9053         bool ret;
9054
9055         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9056         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
9057         if (!wakeref)
9058                 return false;
9059
9060         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
9061         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9062         pipe_config->shared_dpll = NULL;
9063
9064         ret = false;
9065         tmp = I915_READ(PIPECONF(crtc->pipe));
9066         if (!(tmp & PIPECONF_ENABLE))
9067                 goto out;
9068
9069         switch (tmp & PIPECONF_BPC_MASK) {
9070         case PIPECONF_6BPC:
9071                 pipe_config->pipe_bpp = 18;
9072                 break;
9073         case PIPECONF_8BPC:
9074                 pipe_config->pipe_bpp = 24;
9075                 break;
9076         case PIPECONF_10BPC:
9077                 pipe_config->pipe_bpp = 30;
9078                 break;
9079         case PIPECONF_12BPC:
9080                 pipe_config->pipe_bpp = 36;
9081                 break;
9082         default:
9083                 break;
9084         }
9085
9086         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9087                 pipe_config->limited_color_range = true;
9088
9089         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9090                 struct intel_shared_dpll *pll;
9091                 enum intel_dpll_id pll_id;
9092
9093                 pipe_config->has_pch_encoder = true;
9094
9095                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9096                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9097                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9098
9099                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9100
9101                 if (HAS_PCH_IBX(dev_priv)) {
9102                         /*
9103                          * The pipe->pch transcoder and pch transcoder->pll
9104                          * mapping is fixed.
9105                          */
9106                         pll_id = (enum intel_dpll_id) crtc->pipe;
9107                 } else {
9108                         tmp = I915_READ(PCH_DPLL_SEL);
9109                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9110                                 pll_id = DPLL_ID_PCH_PLL_B;
9111                         else
9112                                 pll_id= DPLL_ID_PCH_PLL_A;
9113                 }
9114
9115                 pipe_config->shared_dpll =
9116                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9117                 pll = pipe_config->shared_dpll;
9118
9119                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9120                                                 &pipe_config->dpll_hw_state));
9121
9122                 tmp = pipe_config->dpll_hw_state.dpll;
9123                 pipe_config->pixel_multiplier =
9124                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9125                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9126
9127                 ironlake_pch_clock_get(crtc, pipe_config);
9128         } else {
9129                 pipe_config->pixel_multiplier = 1;
9130         }
9131
9132         intel_get_pipe_timings(crtc, pipe_config);
9133         intel_get_pipe_src_size(crtc, pipe_config);
9134
9135         ironlake_get_pfit_config(crtc, pipe_config);
9136
9137         ret = true;
9138
9139 out:
9140         intel_display_power_put(dev_priv, power_domain, wakeref);
9141
9142         return ret;
9143 }
9144
9145 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9146 {
9147         struct drm_device *dev = &dev_priv->drm;
9148         struct intel_crtc *crtc;
9149
9150         for_each_intel_crtc(dev, crtc)
9151                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9152                      pipe_name(crtc->pipe));
9153
9154         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
9155                         "Display power well on\n");
9156         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9157         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9158         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9159         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9160         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9161              "CPU PWM1 enabled\n");
9162         if (IS_HASWELL(dev_priv))
9163                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9164                      "CPU PWM2 enabled\n");
9165         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9166              "PCH PWM1 enabled\n");
9167         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9168              "Utility pin enabled\n");
9169         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9170
9171         /*
9172          * In theory we can still leave IRQs enabled, as long as only the HPD
9173          * interrupts remain enabled. We used to check for that, but since it's
9174          * gen-specific and since we only disable LCPLL after we fully disable
9175          * the interrupts, the check below should be enough.
9176          */
9177         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9178 }
9179
9180 static u32 hsw_read_dcomp(struct drm_i915_private *dev_priv)
9181 {
9182         if (IS_HASWELL(dev_priv))
9183                 return I915_READ(D_COMP_HSW);
9184         else
9185                 return I915_READ(D_COMP_BDW);
9186 }
9187
9188 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, u32 val)
9189 {
9190         if (IS_HASWELL(dev_priv)) {
9191                 mutex_lock(&dev_priv->pcu_lock);
9192                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9193                                             val))
9194                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9195                 mutex_unlock(&dev_priv->pcu_lock);
9196         } else {
9197                 I915_WRITE(D_COMP_BDW, val);
9198                 POSTING_READ(D_COMP_BDW);
9199         }
9200 }
9201
9202 /*
9203  * This function implements pieces of two sequences from BSpec:
9204  * - Sequence for display software to disable LCPLL
9205  * - Sequence for display software to allow package C8+
9206  * The steps implemented here are just the steps that actually touch the LCPLL
9207  * register. Callers should take care of disabling all the display engine
9208  * functions, doing the mode unset, fixing interrupts, etc.
9209  */
9210 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9211                               bool switch_to_fclk, bool allow_power_down)
9212 {
9213         u32 val;
9214
9215         assert_can_disable_lcpll(dev_priv);
9216
9217         val = I915_READ(LCPLL_CTL);
9218
9219         if (switch_to_fclk) {
9220                 val |= LCPLL_CD_SOURCE_FCLK;
9221                 I915_WRITE(LCPLL_CTL, val);
9222
9223                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9224                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9225                         DRM_ERROR("Switching to FCLK failed\n");
9226
9227                 val = I915_READ(LCPLL_CTL);
9228         }
9229
9230         val |= LCPLL_PLL_DISABLE;
9231         I915_WRITE(LCPLL_CTL, val);
9232         POSTING_READ(LCPLL_CTL);
9233
9234         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9235                 DRM_ERROR("LCPLL still locked\n");
9236
9237         val = hsw_read_dcomp(dev_priv);
9238         val |= D_COMP_COMP_DISABLE;
9239         hsw_write_dcomp(dev_priv, val);
9240         ndelay(100);
9241
9242         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9243                      1))
9244                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9245
9246         if (allow_power_down) {
9247                 val = I915_READ(LCPLL_CTL);
9248                 val |= LCPLL_POWER_DOWN_ALLOW;
9249                 I915_WRITE(LCPLL_CTL, val);
9250                 POSTING_READ(LCPLL_CTL);
9251         }
9252 }
9253
9254 /*
9255  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9256  * source.
9257  */
9258 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9259 {
9260         u32 val;
9261
9262         val = I915_READ(LCPLL_CTL);
9263
9264         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9265                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9266                 return;
9267
9268         /*
9269          * Make sure we're not on PC8 state before disabling PC8, otherwise
9270          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9271          */
9272         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9273
9274         if (val & LCPLL_POWER_DOWN_ALLOW) {
9275                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9276                 I915_WRITE(LCPLL_CTL, val);
9277                 POSTING_READ(LCPLL_CTL);
9278         }
9279
9280         val = hsw_read_dcomp(dev_priv);
9281         val |= D_COMP_COMP_FORCE;
9282         val &= ~D_COMP_COMP_DISABLE;
9283         hsw_write_dcomp(dev_priv, val);
9284
9285         val = I915_READ(LCPLL_CTL);
9286         val &= ~LCPLL_PLL_DISABLE;
9287         I915_WRITE(LCPLL_CTL, val);
9288
9289         if (intel_wait_for_register(dev_priv,
9290                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9291                                     5))
9292                 DRM_ERROR("LCPLL not locked yet\n");
9293
9294         if (val & LCPLL_CD_SOURCE_FCLK) {
9295                 val = I915_READ(LCPLL_CTL);
9296                 val &= ~LCPLL_CD_SOURCE_FCLK;
9297                 I915_WRITE(LCPLL_CTL, val);
9298
9299                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9300                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9301                         DRM_ERROR("Switching back to LCPLL failed\n");
9302         }
9303
9304         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9305
9306         intel_update_cdclk(dev_priv);
9307         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9308 }
9309
9310 /*
9311  * Package states C8 and deeper are really deep PC states that can only be
9312  * reached when all the devices on the system allow it, so even if the graphics
9313  * device allows PC8+, it doesn't mean the system will actually get to these
9314  * states. Our driver only allows PC8+ when going into runtime PM.
9315  *
9316  * The requirements for PC8+ are that all the outputs are disabled, the power
9317  * well is disabled and most interrupts are disabled, and these are also
9318  * requirements for runtime PM. When these conditions are met, we manually do
9319  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9320  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9321  * hang the machine.
9322  *
9323  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9324  * the state of some registers, so when we come back from PC8+ we need to
9325  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9326  * need to take care of the registers kept by RC6. Notice that this happens even
9327  * if we don't put the device in PCI D3 state (which is what currently happens
9328  * because of the runtime PM support).
9329  *
9330  * For more, read "Display Sequences for Package C8" on the hardware
9331  * documentation.
9332  */
9333 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9334 {
9335         u32 val;
9336
9337         DRM_DEBUG_KMS("Enabling package C8+\n");
9338
9339         if (HAS_PCH_LPT_LP(dev_priv)) {
9340                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9341                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9342                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9343         }
9344
9345         lpt_disable_clkout_dp(dev_priv);
9346         hsw_disable_lcpll(dev_priv, true, true);
9347 }
9348
9349 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9350 {
9351         u32 val;
9352
9353         DRM_DEBUG_KMS("Disabling package C8+\n");
9354
9355         hsw_restore_lcpll(dev_priv);
9356         lpt_init_pch_refclk(dev_priv);
9357
9358         if (HAS_PCH_LPT_LP(dev_priv)) {
9359                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9360                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9361                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9362         }
9363 }
9364
9365 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9366                                       struct intel_crtc_state *crtc_state)
9367 {
9368         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9369         struct intel_atomic_state *state =
9370                 to_intel_atomic_state(crtc_state->base.state);
9371
9372         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI) ||
9373             IS_ICELAKE(dev_priv)) {
9374                 struct intel_encoder *encoder =
9375                         intel_get_crtc_new_encoder(state, crtc_state);
9376
9377                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9378                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9379                                       pipe_name(crtc->pipe));
9380                         return -EINVAL;
9381                 }
9382         }
9383
9384         return 0;
9385 }
9386
9387 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9388                                    enum port port,
9389                                    struct intel_crtc_state *pipe_config)
9390 {
9391         enum intel_dpll_id id;
9392         u32 temp;
9393
9394         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9395         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9396
9397         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9398                 return;
9399
9400         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9401 }
9402
9403 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9404                                 enum port port,
9405                                 struct intel_crtc_state *pipe_config)
9406 {
9407         enum intel_dpll_id id;
9408         u32 temp;
9409
9410         /* TODO: TBT pll not implemented. */
9411         if (intel_port_is_combophy(dev_priv, port)) {
9412                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9413                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9414                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9415
9416                 if (WARN_ON(!intel_dpll_is_combophy(id)))
9417                         return;
9418         } else if (intel_port_is_tc(dev_priv, port)) {
9419                 id = icl_port_to_mg_pll_id(port);
9420         } else {
9421                 WARN(1, "Invalid port %x\n", port);
9422                 return;
9423         }
9424
9425         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9426 }
9427
9428 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9429                                 enum port port,
9430                                 struct intel_crtc_state *pipe_config)
9431 {
9432         enum intel_dpll_id id;
9433
9434         switch (port) {
9435         case PORT_A:
9436                 id = DPLL_ID_SKL_DPLL0;
9437                 break;
9438         case PORT_B:
9439                 id = DPLL_ID_SKL_DPLL1;
9440                 break;
9441         case PORT_C:
9442                 id = DPLL_ID_SKL_DPLL2;
9443                 break;
9444         default:
9445                 DRM_ERROR("Incorrect port type\n");
9446                 return;
9447         }
9448
9449         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9450 }
9451
9452 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9453                                 enum port port,
9454                                 struct intel_crtc_state *pipe_config)
9455 {
9456         enum intel_dpll_id id;
9457         u32 temp;
9458
9459         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9460         id = temp >> (port * 3 + 1);
9461
9462         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9463                 return;
9464
9465         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9466 }
9467
9468 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9469                                 enum port port,
9470                                 struct intel_crtc_state *pipe_config)
9471 {
9472         enum intel_dpll_id id;
9473         u32 ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9474
9475         switch (ddi_pll_sel) {
9476         case PORT_CLK_SEL_WRPLL1:
9477                 id = DPLL_ID_WRPLL1;
9478                 break;
9479         case PORT_CLK_SEL_WRPLL2:
9480                 id = DPLL_ID_WRPLL2;
9481                 break;
9482         case PORT_CLK_SEL_SPLL:
9483                 id = DPLL_ID_SPLL;
9484                 break;
9485         case PORT_CLK_SEL_LCPLL_810:
9486                 id = DPLL_ID_LCPLL_810;
9487                 break;
9488         case PORT_CLK_SEL_LCPLL_1350:
9489                 id = DPLL_ID_LCPLL_1350;
9490                 break;
9491         case PORT_CLK_SEL_LCPLL_2700:
9492                 id = DPLL_ID_LCPLL_2700;
9493                 break;
9494         default:
9495                 MISSING_CASE(ddi_pll_sel);
9496                 /* fall through */
9497         case PORT_CLK_SEL_NONE:
9498                 return;
9499         }
9500
9501         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9502 }
9503
9504 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9505                                      struct intel_crtc_state *pipe_config,
9506                                      u64 *power_domain_mask)
9507 {
9508         struct drm_device *dev = crtc->base.dev;
9509         struct drm_i915_private *dev_priv = to_i915(dev);
9510         enum intel_display_power_domain power_domain;
9511         unsigned long panel_transcoder_mask = BIT(TRANSCODER_EDP);
9512         unsigned long enabled_panel_transcoders = 0;
9513         enum transcoder panel_transcoder;
9514         u32 tmp;
9515
9516         if (IS_ICELAKE(dev_priv))
9517                 panel_transcoder_mask |=
9518                         BIT(TRANSCODER_DSI_0) | BIT(TRANSCODER_DSI_1);
9519
9520         /*
9521          * The pipe->transcoder mapping is fixed with the exception of the eDP
9522          * and DSI transcoders handled below.
9523          */
9524         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9525
9526         /*
9527          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9528          * consistency and less surprising code; it's in always on power).
9529          */
9530         for_each_set_bit(panel_transcoder,
9531                          &panel_transcoder_mask,
9532                          ARRAY_SIZE(INTEL_INFO(dev_priv)->trans_offsets)) {
9533                 enum pipe trans_pipe;
9534
9535                 tmp = I915_READ(TRANS_DDI_FUNC_CTL(panel_transcoder));
9536                 if (!(tmp & TRANS_DDI_FUNC_ENABLE))
9537                         continue;
9538
9539                 /*
9540                  * Log all enabled ones, only use the first one.
9541                  *
9542                  * FIXME: This won't work for two separate DSI displays.
9543                  */
9544                 enabled_panel_transcoders |= BIT(panel_transcoder);
9545                 if (enabled_panel_transcoders != BIT(panel_transcoder))
9546                         continue;
9547
9548                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9549                 default:
9550                         WARN(1, "unknown pipe linked to transcoder %s\n",
9551                              transcoder_name(panel_transcoder));
9552                         /* fall through */
9553                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9554                 case TRANS_DDI_EDP_INPUT_A_ON:
9555                         trans_pipe = PIPE_A;
9556                         break;
9557                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9558                         trans_pipe = PIPE_B;
9559                         break;
9560                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9561                         trans_pipe = PIPE_C;
9562                         break;
9563                 }
9564
9565                 if (trans_pipe == crtc->pipe)
9566                         pipe_config->cpu_transcoder = panel_transcoder;
9567         }
9568
9569         /*
9570          * Valid combos: none, eDP, DSI0, DSI1, DSI0+DSI1
9571          */
9572         WARN_ON((enabled_panel_transcoders & BIT(TRANSCODER_EDP)) &&
9573                 enabled_panel_transcoders != BIT(TRANSCODER_EDP));
9574
9575         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9576         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9577                 return false;
9578
9579         WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
9580         *power_domain_mask |= BIT_ULL(power_domain);
9581
9582         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9583
9584         return tmp & PIPECONF_ENABLE;
9585 }
9586
9587 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9588                                          struct intel_crtc_state *pipe_config,
9589                                          u64 *power_domain_mask)
9590 {
9591         struct drm_device *dev = crtc->base.dev;
9592         struct drm_i915_private *dev_priv = to_i915(dev);
9593         enum intel_display_power_domain power_domain;
9594         enum port port;
9595         enum transcoder cpu_transcoder;
9596         u32 tmp;
9597
9598         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9599                 if (port == PORT_A)
9600                         cpu_transcoder = TRANSCODER_DSI_A;
9601                 else
9602                         cpu_transcoder = TRANSCODER_DSI_C;
9603
9604                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9605                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9606                         continue;
9607
9608                 WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
9609                 *power_domain_mask |= BIT_ULL(power_domain);
9610
9611                 /*
9612                  * The PLL needs to be enabled with a valid divider
9613                  * configuration, otherwise accessing DSI registers will hang
9614                  * the machine. See BSpec North Display Engine
9615                  * registers/MIPI[BXT]. We can break out here early, since we
9616                  * need the same DSI PLL to be enabled for both DSI ports.
9617                  */
9618                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9619                         break;
9620
9621                 /* XXX: this works for video mode only */
9622                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9623                 if (!(tmp & DPI_ENABLE))
9624                         continue;
9625
9626                 tmp = I915_READ(MIPI_CTRL(port));
9627                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9628                         continue;
9629
9630                 pipe_config->cpu_transcoder = cpu_transcoder;
9631                 break;
9632         }
9633
9634         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9635 }
9636
9637 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9638                                        struct intel_crtc_state *pipe_config)
9639 {
9640         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9641         struct intel_shared_dpll *pll;
9642         enum port port;
9643         u32 tmp;
9644
9645         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9646
9647         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9648
9649         if (IS_ICELAKE(dev_priv))
9650                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9651         else if (IS_CANNONLAKE(dev_priv))
9652                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9653         else if (IS_GEN9_BC(dev_priv))
9654                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9655         else if (IS_GEN9_LP(dev_priv))
9656                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9657         else
9658                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9659
9660         pll = pipe_config->shared_dpll;
9661         if (pll) {
9662                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9663                                                 &pipe_config->dpll_hw_state));
9664         }
9665
9666         /*
9667          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9668          * DDI E. So just check whether this pipe is wired to DDI E and whether
9669          * the PCH transcoder is on.
9670          */
9671         if (INTEL_GEN(dev_priv) < 9 &&
9672             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9673                 pipe_config->has_pch_encoder = true;
9674
9675                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9676                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9677                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9678
9679                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9680         }
9681 }
9682
9683 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9684                                     struct intel_crtc_state *pipe_config)
9685 {
9686         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9687         enum intel_display_power_domain power_domain;
9688         u64 power_domain_mask;
9689         bool active;
9690
9691         intel_crtc_init_scalers(crtc, pipe_config);
9692
9693         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9694         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9695                 return false;
9696         power_domain_mask = BIT_ULL(power_domain);
9697
9698         pipe_config->shared_dpll = NULL;
9699
9700         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9701
9702         if (IS_GEN9_LP(dev_priv) &&
9703             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9704                 WARN_ON(active);
9705                 active = true;
9706         }
9707
9708         if (!active)
9709                 goto out;
9710
9711         if (!transcoder_is_dsi(pipe_config->cpu_transcoder) ||
9712             IS_ICELAKE(dev_priv)) {
9713                 haswell_get_ddi_port_state(crtc, pipe_config);
9714                 intel_get_pipe_timings(crtc, pipe_config);
9715         }
9716
9717         intel_get_pipe_src_size(crtc, pipe_config);
9718         intel_get_crtc_ycbcr_config(crtc, pipe_config);
9719
9720         pipe_config->gamma_mode =
9721                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9722
9723         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9724         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9725                 WARN_ON(power_domain_mask & BIT_ULL(power_domain));
9726                 power_domain_mask |= BIT_ULL(power_domain);
9727
9728                 if (INTEL_GEN(dev_priv) >= 9)
9729                         skylake_get_pfit_config(crtc, pipe_config);
9730                 else
9731                         ironlake_get_pfit_config(crtc, pipe_config);
9732         }
9733
9734         if (hsw_crtc_supports_ips(crtc)) {
9735                 if (IS_HASWELL(dev_priv))
9736                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9737                 else {
9738                         /*
9739                          * We cannot readout IPS state on broadwell, set to
9740                          * true so we can set it to a defined state on first
9741                          * commit.
9742                          */
9743                         pipe_config->ips_enabled = true;
9744                 }
9745         }
9746
9747         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9748             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9749                 pipe_config->pixel_multiplier =
9750                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9751         } else {
9752                 pipe_config->pixel_multiplier = 1;
9753         }
9754
9755 out:
9756         for_each_power_domain(power_domain, power_domain_mask)
9757                 intel_display_power_put_unchecked(dev_priv, power_domain);
9758
9759         return active;
9760 }
9761
9762 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9763 {
9764         struct drm_i915_private *dev_priv =
9765                 to_i915(plane_state->base.plane->dev);
9766         const struct drm_framebuffer *fb = plane_state->base.fb;
9767         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9768         u32 base;
9769
9770         if (INTEL_INFO(dev_priv)->display.cursor_needs_physical)
9771                 base = obj->phys_handle->busaddr;
9772         else
9773                 base = intel_plane_ggtt_offset(plane_state);
9774
9775         base += plane_state->color_plane[0].offset;
9776
9777         /* ILK+ do this automagically */
9778         if (HAS_GMCH_DISPLAY(dev_priv) &&
9779             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9780                 base += (plane_state->base.crtc_h *
9781                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9782
9783         return base;
9784 }
9785
9786 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9787 {
9788         int x = plane_state->base.crtc_x;
9789         int y = plane_state->base.crtc_y;
9790         u32 pos = 0;
9791
9792         if (x < 0) {
9793                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9794                 x = -x;
9795         }
9796         pos |= x << CURSOR_X_SHIFT;
9797
9798         if (y < 0) {
9799                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9800                 y = -y;
9801         }
9802         pos |= y << CURSOR_Y_SHIFT;
9803
9804         return pos;
9805 }
9806
9807 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9808 {
9809         const struct drm_mode_config *config =
9810                 &plane_state->base.plane->dev->mode_config;
9811         int width = plane_state->base.crtc_w;
9812         int height = plane_state->base.crtc_h;
9813
9814         return width > 0 && width <= config->cursor_width &&
9815                 height > 0 && height <= config->cursor_height;
9816 }
9817
9818 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
9819 {
9820         const struct drm_framebuffer *fb = plane_state->base.fb;
9821         unsigned int rotation = plane_state->base.rotation;
9822         int src_x, src_y;
9823         u32 offset;
9824         int ret;
9825
9826         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
9827         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
9828
9829         ret = intel_plane_check_stride(plane_state);
9830         if (ret)
9831                 return ret;
9832
9833         src_x = plane_state->base.src_x >> 16;
9834         src_y = plane_state->base.src_y >> 16;
9835
9836         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9837         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
9838                                                     plane_state, 0);
9839
9840         if (src_x != 0 || src_y != 0) {
9841                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9842                 return -EINVAL;
9843         }
9844
9845         plane_state->color_plane[0].offset = offset;
9846
9847         return 0;
9848 }
9849
9850 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9851                               struct intel_plane_state *plane_state)
9852 {
9853         const struct drm_framebuffer *fb = plane_state->base.fb;
9854         int ret;
9855
9856         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9857                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9858                 return -EINVAL;
9859         }
9860
9861         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9862                                                   &crtc_state->base,
9863                                                   DRM_PLANE_HELPER_NO_SCALING,
9864                                                   DRM_PLANE_HELPER_NO_SCALING,
9865                                                   true, true);
9866         if (ret)
9867                 return ret;
9868
9869         if (!plane_state->base.visible)
9870                 return 0;
9871
9872         ret = intel_plane_check_src_coordinates(plane_state);
9873         if (ret)
9874                 return ret;
9875
9876         ret = intel_cursor_check_surface(plane_state);
9877         if (ret)
9878                 return ret;
9879
9880         return 0;
9881 }
9882
9883 static unsigned int
9884 i845_cursor_max_stride(struct intel_plane *plane,
9885                        u32 pixel_format, u64 modifier,
9886                        unsigned int rotation)
9887 {
9888         return 2048;
9889 }
9890
9891 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9892                            const struct intel_plane_state *plane_state)
9893 {
9894         return CURSOR_ENABLE |
9895                 CURSOR_GAMMA_ENABLE |
9896                 CURSOR_FORMAT_ARGB |
9897                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
9898 }
9899
9900 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9901 {
9902         int width = plane_state->base.crtc_w;
9903
9904         /*
9905          * 845g/865g are only limited by the width of their cursors,
9906          * the height is arbitrary up to the precision of the register.
9907          */
9908         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9909 }
9910
9911 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
9912                              struct intel_plane_state *plane_state)
9913 {
9914         const struct drm_framebuffer *fb = plane_state->base.fb;
9915         int ret;
9916
9917         ret = intel_check_cursor(crtc_state, plane_state);
9918         if (ret)
9919                 return ret;
9920
9921         /* if we want to turn off the cursor ignore width and height */
9922         if (!fb)
9923                 return 0;
9924
9925         /* Check for which cursor types we support */
9926         if (!i845_cursor_size_ok(plane_state)) {
9927                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9928                           plane_state->base.crtc_w,
9929                           plane_state->base.crtc_h);
9930                 return -EINVAL;
9931         }
9932
9933         WARN_ON(plane_state->base.visible &&
9934                 plane_state->color_plane[0].stride != fb->pitches[0]);
9935
9936         switch (fb->pitches[0]) {
9937         case 256:
9938         case 512:
9939         case 1024:
9940         case 2048:
9941                 break;
9942         default:
9943                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9944                               fb->pitches[0]);
9945                 return -EINVAL;
9946         }
9947
9948         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9949
9950         return 0;
9951 }
9952
9953 static void i845_update_cursor(struct intel_plane *plane,
9954                                const struct intel_crtc_state *crtc_state,
9955                                const struct intel_plane_state *plane_state)
9956 {
9957         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9958         u32 cntl = 0, base = 0, pos = 0, size = 0;
9959         unsigned long irqflags;
9960
9961         if (plane_state && plane_state->base.visible) {
9962                 unsigned int width = plane_state->base.crtc_w;
9963                 unsigned int height = plane_state->base.crtc_h;
9964
9965                 cntl = plane_state->ctl;
9966                 size = (height << 12) | width;
9967
9968                 base = intel_cursor_base(plane_state);
9969                 pos = intel_cursor_position(plane_state);
9970         }
9971
9972         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9973
9974         /* On these chipsets we can only modify the base/size/stride
9975          * whilst the cursor is disabled.
9976          */
9977         if (plane->cursor.base != base ||
9978             plane->cursor.size != size ||
9979             plane->cursor.cntl != cntl) {
9980                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9981                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9982                 I915_WRITE_FW(CURSIZE, size);
9983                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9984                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9985
9986                 plane->cursor.base = base;
9987                 plane->cursor.size = size;
9988                 plane->cursor.cntl = cntl;
9989         } else {
9990                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9991         }
9992
9993         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9994 }
9995
9996 static void i845_disable_cursor(struct intel_plane *plane,
9997                                 const struct intel_crtc_state *crtc_state)
9998 {
9999         i845_update_cursor(plane, crtc_state, NULL);
10000 }
10001
10002 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
10003                                      enum pipe *pipe)
10004 {
10005         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10006         enum intel_display_power_domain power_domain;
10007         intel_wakeref_t wakeref;
10008         bool ret;
10009
10010         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
10011         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10012         if (!wakeref)
10013                 return false;
10014
10015         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
10016
10017         *pipe = PIPE_A;
10018
10019         intel_display_power_put(dev_priv, power_domain, wakeref);
10020
10021         return ret;
10022 }
10023
10024 static unsigned int
10025 i9xx_cursor_max_stride(struct intel_plane *plane,
10026                        u32 pixel_format, u64 modifier,
10027                        unsigned int rotation)
10028 {
10029         return plane->base.dev->mode_config.cursor_width * 4;
10030 }
10031
10032 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
10033                            const struct intel_plane_state *plane_state)
10034 {
10035         struct drm_i915_private *dev_priv =
10036                 to_i915(plane_state->base.plane->dev);
10037         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10038         u32 cntl = 0;
10039
10040         if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
10041                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
10042
10043         if (INTEL_GEN(dev_priv) <= 10) {
10044                 cntl |= MCURSOR_GAMMA_ENABLE;
10045
10046                 if (HAS_DDI(dev_priv))
10047                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
10048         }
10049
10050         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10051                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
10052
10053         switch (plane_state->base.crtc_w) {
10054         case 64:
10055                 cntl |= MCURSOR_MODE_64_ARGB_AX;
10056                 break;
10057         case 128:
10058                 cntl |= MCURSOR_MODE_128_ARGB_AX;
10059                 break;
10060         case 256:
10061                 cntl |= MCURSOR_MODE_256_ARGB_AX;
10062                 break;
10063         default:
10064                 MISSING_CASE(plane_state->base.crtc_w);
10065                 return 0;
10066         }
10067
10068         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
10069                 cntl |= MCURSOR_ROTATE_180;
10070
10071         return cntl;
10072 }
10073
10074 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
10075 {
10076         struct drm_i915_private *dev_priv =
10077                 to_i915(plane_state->base.plane->dev);
10078         int width = plane_state->base.crtc_w;
10079         int height = plane_state->base.crtc_h;
10080
10081         if (!intel_cursor_size_ok(plane_state))
10082                 return false;
10083
10084         /* Cursor width is limited to a few power-of-two sizes */
10085         switch (width) {
10086         case 256:
10087         case 128:
10088         case 64:
10089                 break;
10090         default:
10091                 return false;
10092         }
10093
10094         /*
10095          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10096          * height from 8 lines up to the cursor width, when the
10097          * cursor is not rotated. Everything else requires square
10098          * cursors.
10099          */
10100         if (HAS_CUR_FBC(dev_priv) &&
10101             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10102                 if (height < 8 || height > width)
10103                         return false;
10104         } else {
10105                 if (height != width)
10106                         return false;
10107         }
10108
10109         return true;
10110 }
10111
10112 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10113                              struct intel_plane_state *plane_state)
10114 {
10115         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10116         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10117         const struct drm_framebuffer *fb = plane_state->base.fb;
10118         enum pipe pipe = plane->pipe;
10119         int ret;
10120
10121         ret = intel_check_cursor(crtc_state, plane_state);
10122         if (ret)
10123                 return ret;
10124
10125         /* if we want to turn off the cursor ignore width and height */
10126         if (!fb)
10127                 return 0;
10128
10129         /* Check for which cursor types we support */
10130         if (!i9xx_cursor_size_ok(plane_state)) {
10131                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10132                           plane_state->base.crtc_w,
10133                           plane_state->base.crtc_h);
10134                 return -EINVAL;
10135         }
10136
10137         WARN_ON(plane_state->base.visible &&
10138                 plane_state->color_plane[0].stride != fb->pitches[0]);
10139
10140         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10141                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10142                               fb->pitches[0], plane_state->base.crtc_w);
10143                 return -EINVAL;
10144         }
10145
10146         /*
10147          * There's something wrong with the cursor on CHV pipe C.
10148          * If it straddles the left edge of the screen then
10149          * moving it away from the edge or disabling it often
10150          * results in a pipe underrun, and often that can lead to
10151          * dead pipe (constant underrun reported, and it scans
10152          * out just a solid color). To recover from that, the
10153          * display power well must be turned off and on again.
10154          * Refuse the put the cursor into that compromised position.
10155          */
10156         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10157             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10158                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10159                 return -EINVAL;
10160         }
10161
10162         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10163
10164         return 0;
10165 }
10166
10167 static void i9xx_update_cursor(struct intel_plane *plane,
10168                                const struct intel_crtc_state *crtc_state,
10169                                const struct intel_plane_state *plane_state)
10170 {
10171         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10172         enum pipe pipe = plane->pipe;
10173         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10174         unsigned long irqflags;
10175
10176         if (plane_state && plane_state->base.visible) {
10177                 cntl = plane_state->ctl;
10178
10179                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10180                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10181
10182                 base = intel_cursor_base(plane_state);
10183                 pos = intel_cursor_position(plane_state);
10184         }
10185
10186         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10187
10188         /*
10189          * On some platforms writing CURCNTR first will also
10190          * cause CURPOS to be armed by the CURBASE write.
10191          * Without the CURCNTR write the CURPOS write would
10192          * arm itself. Thus we always update CURCNTR before
10193          * CURPOS.
10194          *
10195          * On other platforms CURPOS always requires the
10196          * CURBASE write to arm the update. Additonally
10197          * a write to any of the cursor register will cancel
10198          * an already armed cursor update. Thus leaving out
10199          * the CURBASE write after CURPOS could lead to a
10200          * cursor that doesn't appear to move, or even change
10201          * shape. Thus we always write CURBASE.
10202          *
10203          * The other registers are armed by by the CURBASE write
10204          * except when the plane is getting enabled at which time
10205          * the CURCNTR write arms the update.
10206          */
10207
10208         if (INTEL_GEN(dev_priv) >= 9)
10209                 skl_write_cursor_wm(plane, crtc_state);
10210
10211         if (plane->cursor.base != base ||
10212             plane->cursor.size != fbc_ctl ||
10213             plane->cursor.cntl != cntl) {
10214                 if (HAS_CUR_FBC(dev_priv))
10215                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10216                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10217                 I915_WRITE_FW(CURPOS(pipe), pos);
10218                 I915_WRITE_FW(CURBASE(pipe), base);
10219
10220                 plane->cursor.base = base;
10221                 plane->cursor.size = fbc_ctl;
10222                 plane->cursor.cntl = cntl;
10223         } else {
10224                 I915_WRITE_FW(CURPOS(pipe), pos);
10225                 I915_WRITE_FW(CURBASE(pipe), base);
10226         }
10227
10228         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10229 }
10230
10231 static void i9xx_disable_cursor(struct intel_plane *plane,
10232                                 const struct intel_crtc_state *crtc_state)
10233 {
10234         i9xx_update_cursor(plane, crtc_state, NULL);
10235 }
10236
10237 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10238                                      enum pipe *pipe)
10239 {
10240         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10241         enum intel_display_power_domain power_domain;
10242         intel_wakeref_t wakeref;
10243         bool ret;
10244         u32 val;
10245
10246         /*
10247          * Not 100% correct for planes that can move between pipes,
10248          * but that's only the case for gen2-3 which don't have any
10249          * display power wells.
10250          */
10251         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10252         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10253         if (!wakeref)
10254                 return false;
10255
10256         val = I915_READ(CURCNTR(plane->pipe));
10257
10258         ret = val & MCURSOR_MODE;
10259
10260         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10261                 *pipe = plane->pipe;
10262         else
10263                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10264                         MCURSOR_PIPE_SELECT_SHIFT;
10265
10266         intel_display_power_put(dev_priv, power_domain, wakeref);
10267
10268         return ret;
10269 }
10270
10271 /* VESA 640x480x72Hz mode to set on the pipe */
10272 static const struct drm_display_mode load_detect_mode = {
10273         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10274                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10275 };
10276
10277 struct drm_framebuffer *
10278 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10279                          struct drm_mode_fb_cmd2 *mode_cmd)
10280 {
10281         struct intel_framebuffer *intel_fb;
10282         int ret;
10283
10284         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10285         if (!intel_fb)
10286                 return ERR_PTR(-ENOMEM);
10287
10288         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10289         if (ret)
10290                 goto err;
10291
10292         return &intel_fb->base;
10293
10294 err:
10295         kfree(intel_fb);
10296         return ERR_PTR(ret);
10297 }
10298
10299 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10300                                         struct drm_crtc *crtc)
10301 {
10302         struct drm_plane *plane;
10303         struct drm_plane_state *plane_state;
10304         int ret, i;
10305
10306         ret = drm_atomic_add_affected_planes(state, crtc);
10307         if (ret)
10308                 return ret;
10309
10310         for_each_new_plane_in_state(state, plane, plane_state, i) {
10311                 if (plane_state->crtc != crtc)
10312                         continue;
10313
10314                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10315                 if (ret)
10316                         return ret;
10317
10318                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10319         }
10320
10321         return 0;
10322 }
10323
10324 int intel_get_load_detect_pipe(struct drm_connector *connector,
10325                                const struct drm_display_mode *mode,
10326                                struct intel_load_detect_pipe *old,
10327                                struct drm_modeset_acquire_ctx *ctx)
10328 {
10329         struct intel_crtc *intel_crtc;
10330         struct intel_encoder *intel_encoder =
10331                 intel_attached_encoder(connector);
10332         struct drm_crtc *possible_crtc;
10333         struct drm_encoder *encoder = &intel_encoder->base;
10334         struct drm_crtc *crtc = NULL;
10335         struct drm_device *dev = encoder->dev;
10336         struct drm_i915_private *dev_priv = to_i915(dev);
10337         struct drm_mode_config *config = &dev->mode_config;
10338         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10339         struct drm_connector_state *connector_state;
10340         struct intel_crtc_state *crtc_state;
10341         int ret, i = -1;
10342
10343         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10344                       connector->base.id, connector->name,
10345                       encoder->base.id, encoder->name);
10346
10347         old->restore_state = NULL;
10348
10349         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10350
10351         /*
10352          * Algorithm gets a little messy:
10353          *
10354          *   - if the connector already has an assigned crtc, use it (but make
10355          *     sure it's on first)
10356          *
10357          *   - try to find the first unused crtc that can drive this connector,
10358          *     and use that if we find one
10359          */
10360
10361         /* See if we already have a CRTC for this connector */
10362         if (connector->state->crtc) {
10363                 crtc = connector->state->crtc;
10364
10365                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10366                 if (ret)
10367                         goto fail;
10368
10369                 /* Make sure the crtc and connector are running */
10370                 goto found;
10371         }
10372
10373         /* Find an unused one (if possible) */
10374         for_each_crtc(dev, possible_crtc) {
10375                 i++;
10376                 if (!(encoder->possible_crtcs & (1 << i)))
10377                         continue;
10378
10379                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10380                 if (ret)
10381                         goto fail;
10382
10383                 if (possible_crtc->state->enable) {
10384                         drm_modeset_unlock(&possible_crtc->mutex);
10385                         continue;
10386                 }
10387
10388                 crtc = possible_crtc;
10389                 break;
10390         }
10391
10392         /*
10393          * If we didn't find an unused CRTC, don't use any.
10394          */
10395         if (!crtc) {
10396                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10397                 ret = -ENODEV;
10398                 goto fail;
10399         }
10400
10401 found:
10402         intel_crtc = to_intel_crtc(crtc);
10403
10404         state = drm_atomic_state_alloc(dev);
10405         restore_state = drm_atomic_state_alloc(dev);
10406         if (!state || !restore_state) {
10407                 ret = -ENOMEM;
10408                 goto fail;
10409         }
10410
10411         state->acquire_ctx = ctx;
10412         restore_state->acquire_ctx = ctx;
10413
10414         connector_state = drm_atomic_get_connector_state(state, connector);
10415         if (IS_ERR(connector_state)) {
10416                 ret = PTR_ERR(connector_state);
10417                 goto fail;
10418         }
10419
10420         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10421         if (ret)
10422                 goto fail;
10423
10424         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10425         if (IS_ERR(crtc_state)) {
10426                 ret = PTR_ERR(crtc_state);
10427                 goto fail;
10428         }
10429
10430         crtc_state->base.active = crtc_state->base.enable = true;
10431
10432         if (!mode)
10433                 mode = &load_detect_mode;
10434
10435         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10436         if (ret)
10437                 goto fail;
10438
10439         ret = intel_modeset_disable_planes(state, crtc);
10440         if (ret)
10441                 goto fail;
10442
10443         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10444         if (!ret)
10445                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10446         if (!ret)
10447                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10448         if (ret) {
10449                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10450                 goto fail;
10451         }
10452
10453         ret = drm_atomic_commit(state);
10454         if (ret) {
10455                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10456                 goto fail;
10457         }
10458
10459         old->restore_state = restore_state;
10460         drm_atomic_state_put(state);
10461
10462         /* let the connector get through one full cycle before testing */
10463         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10464         return true;
10465
10466 fail:
10467         if (state) {
10468                 drm_atomic_state_put(state);
10469                 state = NULL;
10470         }
10471         if (restore_state) {
10472                 drm_atomic_state_put(restore_state);
10473                 restore_state = NULL;
10474         }
10475
10476         if (ret == -EDEADLK)
10477                 return ret;
10478
10479         return false;
10480 }
10481
10482 void intel_release_load_detect_pipe(struct drm_connector *connector,
10483                                     struct intel_load_detect_pipe *old,
10484                                     struct drm_modeset_acquire_ctx *ctx)
10485 {
10486         struct intel_encoder *intel_encoder =
10487                 intel_attached_encoder(connector);
10488         struct drm_encoder *encoder = &intel_encoder->base;
10489         struct drm_atomic_state *state = old->restore_state;
10490         int ret;
10491
10492         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10493                       connector->base.id, connector->name,
10494                       encoder->base.id, encoder->name);
10495
10496         if (!state)
10497                 return;
10498
10499         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10500         if (ret)
10501                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10502         drm_atomic_state_put(state);
10503 }
10504
10505 static int i9xx_pll_refclk(struct drm_device *dev,
10506                            const struct intel_crtc_state *pipe_config)
10507 {
10508         struct drm_i915_private *dev_priv = to_i915(dev);
10509         u32 dpll = pipe_config->dpll_hw_state.dpll;
10510
10511         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10512                 return dev_priv->vbt.lvds_ssc_freq;
10513         else if (HAS_PCH_SPLIT(dev_priv))
10514                 return 120000;
10515         else if (!IS_GEN(dev_priv, 2))
10516                 return 96000;
10517         else
10518                 return 48000;
10519 }
10520
10521 /* Returns the clock of the currently programmed mode of the given pipe. */
10522 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10523                                 struct intel_crtc_state *pipe_config)
10524 {
10525         struct drm_device *dev = crtc->base.dev;
10526         struct drm_i915_private *dev_priv = to_i915(dev);
10527         int pipe = pipe_config->cpu_transcoder;
10528         u32 dpll = pipe_config->dpll_hw_state.dpll;
10529         u32 fp;
10530         struct dpll clock;
10531         int port_clock;
10532         int refclk = i9xx_pll_refclk(dev, pipe_config);
10533
10534         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10535                 fp = pipe_config->dpll_hw_state.fp0;
10536         else
10537                 fp = pipe_config->dpll_hw_state.fp1;
10538
10539         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10540         if (IS_PINEVIEW(dev_priv)) {
10541                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10542                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10543         } else {
10544                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10545                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10546         }
10547
10548         if (!IS_GEN(dev_priv, 2)) {
10549                 if (IS_PINEVIEW(dev_priv))
10550                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10551                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10552                 else
10553                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10554                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10555
10556                 switch (dpll & DPLL_MODE_MASK) {
10557                 case DPLLB_MODE_DAC_SERIAL:
10558                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10559                                 5 : 10;
10560                         break;
10561                 case DPLLB_MODE_LVDS:
10562                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10563                                 7 : 14;
10564                         break;
10565                 default:
10566                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10567                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10568                         return;
10569                 }
10570
10571                 if (IS_PINEVIEW(dev_priv))
10572                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10573                 else
10574                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10575         } else {
10576                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10577                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10578
10579                 if (is_lvds) {
10580                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10581                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10582
10583                         if (lvds & LVDS_CLKB_POWER_UP)
10584                                 clock.p2 = 7;
10585                         else
10586                                 clock.p2 = 14;
10587                 } else {
10588                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10589                                 clock.p1 = 2;
10590                         else {
10591                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10592                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10593                         }
10594                         if (dpll & PLL_P2_DIVIDE_BY_4)
10595                                 clock.p2 = 4;
10596                         else
10597                                 clock.p2 = 2;
10598                 }
10599
10600                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10601         }
10602
10603         /*
10604          * This value includes pixel_multiplier. We will use
10605          * port_clock to compute adjusted_mode.crtc_clock in the
10606          * encoder's get_config() function.
10607          */
10608         pipe_config->port_clock = port_clock;
10609 }
10610
10611 int intel_dotclock_calculate(int link_freq,
10612                              const struct intel_link_m_n *m_n)
10613 {
10614         /*
10615          * The calculation for the data clock is:
10616          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10617          * But we want to avoid losing precison if possible, so:
10618          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10619          *
10620          * and the link clock is simpler:
10621          * link_clock = (m * link_clock) / n
10622          */
10623
10624         if (!m_n->link_n)
10625                 return 0;
10626
10627         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10628 }
10629
10630 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10631                                    struct intel_crtc_state *pipe_config)
10632 {
10633         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10634
10635         /* read out port_clock from the DPLL */
10636         i9xx_crtc_clock_get(crtc, pipe_config);
10637
10638         /*
10639          * In case there is an active pipe without active ports,
10640          * we may need some idea for the dotclock anyway.
10641          * Calculate one based on the FDI configuration.
10642          */
10643         pipe_config->base.adjusted_mode.crtc_clock =
10644                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10645                                          &pipe_config->fdi_m_n);
10646 }
10647
10648 /* Returns the currently programmed mode of the given encoder. */
10649 struct drm_display_mode *
10650 intel_encoder_current_mode(struct intel_encoder *encoder)
10651 {
10652         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10653         struct intel_crtc_state *crtc_state;
10654         struct drm_display_mode *mode;
10655         struct intel_crtc *crtc;
10656         enum pipe pipe;
10657
10658         if (!encoder->get_hw_state(encoder, &pipe))
10659                 return NULL;
10660
10661         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10662
10663         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10664         if (!mode)
10665                 return NULL;
10666
10667         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10668         if (!crtc_state) {
10669                 kfree(mode);
10670                 return NULL;
10671         }
10672
10673         crtc_state->base.crtc = &crtc->base;
10674
10675         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10676                 kfree(crtc_state);
10677                 kfree(mode);
10678                 return NULL;
10679         }
10680
10681         encoder->get_config(encoder, crtc_state);
10682
10683         intel_mode_from_pipe_config(mode, crtc_state);
10684
10685         kfree(crtc_state);
10686
10687         return mode;
10688 }
10689
10690 static void intel_crtc_destroy(struct drm_crtc *crtc)
10691 {
10692         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10693
10694         drm_crtc_cleanup(crtc);
10695         kfree(intel_crtc);
10696 }
10697
10698 /**
10699  * intel_wm_need_update - Check whether watermarks need updating
10700  * @cur: current plane state
10701  * @new: new plane state
10702  *
10703  * Check current plane state versus the new one to determine whether
10704  * watermarks need to be recalculated.
10705  *
10706  * Returns true or false.
10707  */
10708 static bool intel_wm_need_update(struct intel_plane_state *cur,
10709                                  struct intel_plane_state *new)
10710 {
10711         /* Update watermarks on tiling or size changes. */
10712         if (new->base.visible != cur->base.visible)
10713                 return true;
10714
10715         if (!cur->base.fb || !new->base.fb)
10716                 return false;
10717
10718         if (cur->base.fb->modifier != new->base.fb->modifier ||
10719             cur->base.rotation != new->base.rotation ||
10720             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10721             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10722             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10723             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10724                 return true;
10725
10726         return false;
10727 }
10728
10729 static bool needs_scaling(const struct intel_plane_state *state)
10730 {
10731         int src_w = drm_rect_width(&state->base.src) >> 16;
10732         int src_h = drm_rect_height(&state->base.src) >> 16;
10733         int dst_w = drm_rect_width(&state->base.dst);
10734         int dst_h = drm_rect_height(&state->base.dst);
10735
10736         return (src_w != dst_w || src_h != dst_h);
10737 }
10738
10739 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10740                                     struct drm_crtc_state *crtc_state,
10741                                     const struct intel_plane_state *old_plane_state,
10742                                     struct drm_plane_state *plane_state)
10743 {
10744         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10745         struct drm_crtc *crtc = crtc_state->crtc;
10746         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10747         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10748         struct drm_device *dev = crtc->dev;
10749         struct drm_i915_private *dev_priv = to_i915(dev);
10750         bool mode_changed = needs_modeset(crtc_state);
10751         bool was_crtc_enabled = old_crtc_state->base.active;
10752         bool is_crtc_enabled = crtc_state->active;
10753         bool turn_off, turn_on, visible, was_visible;
10754         struct drm_framebuffer *fb = plane_state->fb;
10755         int ret;
10756
10757         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10758                 ret = skl_update_scaler_plane(
10759                         to_intel_crtc_state(crtc_state),
10760                         to_intel_plane_state(plane_state));
10761                 if (ret)
10762                         return ret;
10763         }
10764
10765         was_visible = old_plane_state->base.visible;
10766         visible = plane_state->visible;
10767
10768         if (!was_crtc_enabled && WARN_ON(was_visible))
10769                 was_visible = false;
10770
10771         /*
10772          * Visibility is calculated as if the crtc was on, but
10773          * after scaler setup everything depends on it being off
10774          * when the crtc isn't active.
10775          *
10776          * FIXME this is wrong for watermarks. Watermarks should also
10777          * be computed as if the pipe would be active. Perhaps move
10778          * per-plane wm computation to the .check_plane() hook, and
10779          * only combine the results from all planes in the current place?
10780          */
10781         if (!is_crtc_enabled) {
10782                 plane_state->visible = visible = false;
10783                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10784         }
10785
10786         if (!was_visible && !visible)
10787                 return 0;
10788
10789         if (fb != old_plane_state->base.fb)
10790                 pipe_config->fb_changed = true;
10791
10792         turn_off = was_visible && (!visible || mode_changed);
10793         turn_on = visible && (!was_visible || mode_changed);
10794
10795         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10796                          intel_crtc->base.base.id, intel_crtc->base.name,
10797                          plane->base.base.id, plane->base.name,
10798                          fb ? fb->base.id : -1);
10799
10800         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10801                          plane->base.base.id, plane->base.name,
10802                          was_visible, visible,
10803                          turn_off, turn_on, mode_changed);
10804
10805         if (turn_on) {
10806                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10807                         pipe_config->update_wm_pre = true;
10808
10809                 /* must disable cxsr around plane enable/disable */
10810                 if (plane->id != PLANE_CURSOR)
10811                         pipe_config->disable_cxsr = true;
10812         } else if (turn_off) {
10813                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10814                         pipe_config->update_wm_post = true;
10815
10816                 /* must disable cxsr around plane enable/disable */
10817                 if (plane->id != PLANE_CURSOR)
10818                         pipe_config->disable_cxsr = true;
10819         } else if (intel_wm_need_update(to_intel_plane_state(plane->base.state),
10820                                         to_intel_plane_state(plane_state))) {
10821                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10822                         /* FIXME bollocks */
10823                         pipe_config->update_wm_pre = true;
10824                         pipe_config->update_wm_post = true;
10825                 }
10826         }
10827
10828         if (visible || was_visible)
10829                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10830
10831         /*
10832          * ILK/SNB DVSACNTR/Sprite Enable
10833          * IVB SPR_CTL/Sprite Enable
10834          * "When in Self Refresh Big FIFO mode, a write to enable the
10835          *  plane will be internally buffered and delayed while Big FIFO
10836          *  mode is exiting."
10837          *
10838          * Which means that enabling the sprite can take an extra frame
10839          * when we start in big FIFO mode (LP1+). Thus we need to drop
10840          * down to LP0 and wait for vblank in order to make sure the
10841          * sprite gets enabled on the next vblank after the register write.
10842          * Doing otherwise would risk enabling the sprite one frame after
10843          * we've already signalled flip completion. We can resume LP1+
10844          * once the sprite has been enabled.
10845          *
10846          *
10847          * WaCxSRDisabledForSpriteScaling:ivb
10848          * IVB SPR_SCALE/Scaling Enable
10849          * "Low Power watermarks must be disabled for at least one
10850          *  frame before enabling sprite scaling, and kept disabled
10851          *  until sprite scaling is disabled."
10852          *
10853          * ILK/SNB DVSASCALE/Scaling Enable
10854          * "When in Self Refresh Big FIFO mode, scaling enable will be
10855          *  masked off while Big FIFO mode is exiting."
10856          *
10857          * Despite the w/a only being listed for IVB we assume that
10858          * the ILK/SNB note has similar ramifications, hence we apply
10859          * the w/a on all three platforms.
10860          *
10861          * With experimental results seems this is needed also for primary
10862          * plane, not only sprite plane.
10863          */
10864         if (plane->id != PLANE_CURSOR &&
10865             (IS_GEN_RANGE(dev_priv, 5, 6) ||
10866              IS_IVYBRIDGE(dev_priv)) &&
10867             (turn_on || (!needs_scaling(old_plane_state) &&
10868                          needs_scaling(to_intel_plane_state(plane_state)))))
10869                 pipe_config->disable_lp_wm = true;
10870
10871         return 0;
10872 }
10873
10874 static bool encoders_cloneable(const struct intel_encoder *a,
10875                                const struct intel_encoder *b)
10876 {
10877         /* masks could be asymmetric, so check both ways */
10878         return a == b || (a->cloneable & (1 << b->type) &&
10879                           b->cloneable & (1 << a->type));
10880 }
10881
10882 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10883                                          struct intel_crtc *crtc,
10884                                          struct intel_encoder *encoder)
10885 {
10886         struct intel_encoder *source_encoder;
10887         struct drm_connector *connector;
10888         struct drm_connector_state *connector_state;
10889         int i;
10890
10891         for_each_new_connector_in_state(state, connector, connector_state, i) {
10892                 if (connector_state->crtc != &crtc->base)
10893                         continue;
10894
10895                 source_encoder =
10896                         to_intel_encoder(connector_state->best_encoder);
10897                 if (!encoders_cloneable(encoder, source_encoder))
10898                         return false;
10899         }
10900
10901         return true;
10902 }
10903
10904 static int icl_add_linked_planes(struct intel_atomic_state *state)
10905 {
10906         struct intel_plane *plane, *linked;
10907         struct intel_plane_state *plane_state, *linked_plane_state;
10908         int i;
10909
10910         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10911                 linked = plane_state->linked_plane;
10912
10913                 if (!linked)
10914                         continue;
10915
10916                 linked_plane_state = intel_atomic_get_plane_state(state, linked);
10917                 if (IS_ERR(linked_plane_state))
10918                         return PTR_ERR(linked_plane_state);
10919
10920                 WARN_ON(linked_plane_state->linked_plane != plane);
10921                 WARN_ON(linked_plane_state->slave == plane_state->slave);
10922         }
10923
10924         return 0;
10925 }
10926
10927 static int icl_check_nv12_planes(struct intel_crtc_state *crtc_state)
10928 {
10929         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10930         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10931         struct intel_atomic_state *state = to_intel_atomic_state(crtc_state->base.state);
10932         struct intel_plane *plane, *linked;
10933         struct intel_plane_state *plane_state;
10934         int i;
10935
10936         if (INTEL_GEN(dev_priv) < 11)
10937                 return 0;
10938
10939         /*
10940          * Destroy all old plane links and make the slave plane invisible
10941          * in the crtc_state->active_planes mask.
10942          */
10943         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10944                 if (plane->pipe != crtc->pipe || !plane_state->linked_plane)
10945                         continue;
10946
10947                 plane_state->linked_plane = NULL;
10948                 if (plane_state->slave && !plane_state->base.visible) {
10949                         crtc_state->active_planes &= ~BIT(plane->id);
10950                         crtc_state->update_planes |= BIT(plane->id);
10951                 }
10952
10953                 plane_state->slave = false;
10954         }
10955
10956         if (!crtc_state->nv12_planes)
10957                 return 0;
10958
10959         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10960                 struct intel_plane_state *linked_state = NULL;
10961
10962                 if (plane->pipe != crtc->pipe ||
10963                     !(crtc_state->nv12_planes & BIT(plane->id)))
10964                         continue;
10965
10966                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, linked) {
10967                         if (!icl_is_nv12_y_plane(linked->id))
10968                                 continue;
10969
10970                         if (crtc_state->active_planes & BIT(linked->id))
10971                                 continue;
10972
10973                         linked_state = intel_atomic_get_plane_state(state, linked);
10974                         if (IS_ERR(linked_state))
10975                                 return PTR_ERR(linked_state);
10976
10977                         break;
10978                 }
10979
10980                 if (!linked_state) {
10981                         DRM_DEBUG_KMS("Need %d free Y planes for NV12\n",
10982                                       hweight8(crtc_state->nv12_planes));
10983
10984                         return -EINVAL;
10985                 }
10986
10987                 plane_state->linked_plane = linked;
10988
10989                 linked_state->slave = true;
10990                 linked_state->linked_plane = plane;
10991                 crtc_state->active_planes |= BIT(linked->id);
10992                 crtc_state->update_planes |= BIT(linked->id);
10993                 DRM_DEBUG_KMS("Using %s as Y plane for %s\n", linked->base.name, plane->base.name);
10994         }
10995
10996         return 0;
10997 }
10998
10999 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11000                                    struct drm_crtc_state *crtc_state)
11001 {
11002         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11003         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11004         struct intel_crtc_state *pipe_config =
11005                 to_intel_crtc_state(crtc_state);
11006         int ret;
11007         bool mode_changed = needs_modeset(crtc_state);
11008
11009         if (mode_changed && !crtc_state->active)
11010                 pipe_config->update_wm_post = true;
11011
11012         if (mode_changed && crtc_state->enable &&
11013             dev_priv->display.crtc_compute_clock &&
11014             !WARN_ON(pipe_config->shared_dpll)) {
11015                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11016                                                            pipe_config);
11017                 if (ret)
11018                         return ret;
11019         }
11020
11021         if (crtc_state->color_mgmt_changed) {
11022                 ret = intel_color_check(pipe_config);
11023                 if (ret)
11024                         return ret;
11025
11026                 /*
11027                  * Changing color management on Intel hardware is
11028                  * handled as part of planes update.
11029                  */
11030                 crtc_state->planes_changed = true;
11031         }
11032
11033         ret = 0;
11034         if (dev_priv->display.compute_pipe_wm) {
11035                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11036                 if (ret) {
11037                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11038                         return ret;
11039                 }
11040         }
11041
11042         if (dev_priv->display.compute_intermediate_wm) {
11043                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11044                         return 0;
11045
11046                 /*
11047                  * Calculate 'intermediate' watermarks that satisfy both the
11048                  * old state and the new state.  We can program these
11049                  * immediately.
11050                  */
11051                 ret = dev_priv->display.compute_intermediate_wm(pipe_config);
11052                 if (ret) {
11053                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11054                         return ret;
11055                 }
11056         }
11057
11058         if (INTEL_GEN(dev_priv) >= 9) {
11059                 if (mode_changed || pipe_config->update_pipe)
11060                         ret = skl_update_scaler_crtc(pipe_config);
11061
11062                 if (!ret)
11063                         ret = icl_check_nv12_planes(pipe_config);
11064                 if (!ret)
11065                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11066                                                             pipe_config);
11067                 if (!ret)
11068                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11069                                                          pipe_config);
11070         }
11071
11072         if (HAS_IPS(dev_priv))
11073                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
11074
11075         return ret;
11076 }
11077
11078 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11079         .atomic_check = intel_crtc_atomic_check,
11080 };
11081
11082 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11083 {
11084         struct intel_connector *connector;
11085         struct drm_connector_list_iter conn_iter;
11086
11087         drm_connector_list_iter_begin(dev, &conn_iter);
11088         for_each_intel_connector_iter(connector, &conn_iter) {
11089                 if (connector->base.state->crtc)
11090                         drm_connector_put(&connector->base);
11091
11092                 if (connector->base.encoder) {
11093                         connector->base.state->best_encoder =
11094                                 connector->base.encoder;
11095                         connector->base.state->crtc =
11096                                 connector->base.encoder->crtc;
11097
11098                         drm_connector_get(&connector->base);
11099                 } else {
11100                         connector->base.state->best_encoder = NULL;
11101                         connector->base.state->crtc = NULL;
11102                 }
11103         }
11104         drm_connector_list_iter_end(&conn_iter);
11105 }
11106
11107 static int
11108 compute_sink_pipe_bpp(const struct drm_connector_state *conn_state,
11109                       struct intel_crtc_state *pipe_config)
11110 {
11111         struct drm_connector *connector = conn_state->connector;
11112         const struct drm_display_info *info = &connector->display_info;
11113         int bpp;
11114
11115         switch (conn_state->max_bpc) {
11116         case 6 ... 7:
11117                 bpp = 6 * 3;
11118                 break;
11119         case 8 ... 9:
11120                 bpp = 8 * 3;
11121                 break;
11122         case 10 ... 11:
11123                 bpp = 10 * 3;
11124                 break;
11125         case 12:
11126                 bpp = 12 * 3;
11127                 break;
11128         default:
11129                 return -EINVAL;
11130         }
11131
11132         if (bpp < pipe_config->pipe_bpp) {
11133                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] Limiting display bpp to %d instead of "
11134                               "EDID bpp %d, requested bpp %d, max platform bpp %d\n",
11135                               connector->base.id, connector->name,
11136                               bpp, 3 * info->bpc, 3 * conn_state->max_requested_bpc,
11137                               pipe_config->pipe_bpp);
11138
11139                 pipe_config->pipe_bpp = bpp;
11140         }
11141
11142         return 0;
11143 }
11144
11145 static int
11146 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11147                           struct intel_crtc_state *pipe_config)
11148 {
11149         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11150         struct drm_atomic_state *state = pipe_config->base.state;
11151         struct drm_connector *connector;
11152         struct drm_connector_state *connector_state;
11153         int bpp, i;
11154
11155         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11156             IS_CHERRYVIEW(dev_priv)))
11157                 bpp = 10*3;
11158         else if (INTEL_GEN(dev_priv) >= 5)
11159                 bpp = 12*3;
11160         else
11161                 bpp = 8*3;
11162
11163         pipe_config->pipe_bpp = bpp;
11164
11165         /* Clamp display bpp to connector max bpp */
11166         for_each_new_connector_in_state(state, connector, connector_state, i) {
11167                 int ret;
11168
11169                 if (connector_state->crtc != &crtc->base)
11170                         continue;
11171
11172                 ret = compute_sink_pipe_bpp(connector_state, pipe_config);
11173                 if (ret)
11174                         return ret;
11175         }
11176
11177         return 0;
11178 }
11179
11180 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11181 {
11182         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11183                         "type: 0x%x flags: 0x%x\n",
11184                 mode->crtc_clock,
11185                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11186                 mode->crtc_hsync_end, mode->crtc_htotal,
11187                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11188                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11189 }
11190
11191 static inline void
11192 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11193                       unsigned int lane_count, struct intel_link_m_n *m_n)
11194 {
11195         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11196                       id, lane_count,
11197                       m_n->gmch_m, m_n->gmch_n,
11198                       m_n->link_m, m_n->link_n, m_n->tu);
11199 }
11200
11201 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
11202
11203 static const char * const output_type_str[] = {
11204         OUTPUT_TYPE(UNUSED),
11205         OUTPUT_TYPE(ANALOG),
11206         OUTPUT_TYPE(DVO),
11207         OUTPUT_TYPE(SDVO),
11208         OUTPUT_TYPE(LVDS),
11209         OUTPUT_TYPE(TVOUT),
11210         OUTPUT_TYPE(HDMI),
11211         OUTPUT_TYPE(DP),
11212         OUTPUT_TYPE(EDP),
11213         OUTPUT_TYPE(DSI),
11214         OUTPUT_TYPE(DDI),
11215         OUTPUT_TYPE(DP_MST),
11216 };
11217
11218 #undef OUTPUT_TYPE
11219
11220 static void snprintf_output_types(char *buf, size_t len,
11221                                   unsigned int output_types)
11222 {
11223         char *str = buf;
11224         int i;
11225
11226         str[0] = '\0';
11227
11228         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11229                 int r;
11230
11231                 if ((output_types & BIT(i)) == 0)
11232                         continue;
11233
11234                 r = snprintf(str, len, "%s%s",
11235                              str != buf ? "," : "", output_type_str[i]);
11236                 if (r >= len)
11237                         break;
11238                 str += r;
11239                 len -= r;
11240
11241                 output_types &= ~BIT(i);
11242         }
11243
11244         WARN_ON_ONCE(output_types != 0);
11245 }
11246
11247 static const char * const output_format_str[] = {
11248         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
11249         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
11250         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
11251         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
11252 };
11253
11254 static const char *output_formats(enum intel_output_format format)
11255 {
11256         if (format >= ARRAY_SIZE(output_format_str))
11257                 format = INTEL_OUTPUT_FORMAT_INVALID;
11258         return output_format_str[format];
11259 }
11260
11261 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11262                                    struct intel_crtc_state *pipe_config,
11263                                    const char *context)
11264 {
11265         struct drm_device *dev = crtc->base.dev;
11266         struct drm_i915_private *dev_priv = to_i915(dev);
11267         struct drm_plane *plane;
11268         struct intel_plane *intel_plane;
11269         struct intel_plane_state *state;
11270         struct drm_framebuffer *fb;
11271         char buf[64];
11272
11273         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11274                       crtc->base.base.id, crtc->base.name, context);
11275
11276         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
11277         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
11278                       buf, pipe_config->output_types);
11279
11280         DRM_DEBUG_KMS("output format: %s\n",
11281                       output_formats(pipe_config->output_format));
11282
11283         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11284                       transcoder_name(pipe_config->cpu_transcoder),
11285                       pipe_config->pipe_bpp, pipe_config->dither);
11286
11287         if (pipe_config->has_pch_encoder)
11288                 intel_dump_m_n_config(pipe_config, "fdi",
11289                                       pipe_config->fdi_lanes,
11290                                       &pipe_config->fdi_m_n);
11291
11292         if (intel_crtc_has_dp_encoder(pipe_config)) {
11293                 intel_dump_m_n_config(pipe_config, "dp m_n",
11294                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11295                 if (pipe_config->has_drrs)
11296                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11297                                               pipe_config->lane_count,
11298                                               &pipe_config->dp_m2_n2);
11299         }
11300
11301         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11302                       pipe_config->has_audio, pipe_config->has_infoframe);
11303
11304         DRM_DEBUG_KMS("requested mode:\n");
11305         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11306         DRM_DEBUG_KMS("adjusted mode:\n");
11307         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11308         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11309         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11310                       pipe_config->port_clock,
11311                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11312                       pipe_config->pixel_rate);
11313
11314         if (INTEL_GEN(dev_priv) >= 9)
11315                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11316                               crtc->num_scalers,
11317                               pipe_config->scaler_state.scaler_users,
11318                               pipe_config->scaler_state.scaler_id);
11319
11320         if (HAS_GMCH_DISPLAY(dev_priv))
11321                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11322                               pipe_config->gmch_pfit.control,
11323                               pipe_config->gmch_pfit.pgm_ratios,
11324                               pipe_config->gmch_pfit.lvds_border_bits);
11325         else
11326                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11327                               pipe_config->pch_pfit.pos,
11328                               pipe_config->pch_pfit.size,
11329                               enableddisabled(pipe_config->pch_pfit.enabled));
11330
11331         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11332                       pipe_config->ips_enabled, pipe_config->double_wide);
11333
11334         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11335
11336         DRM_DEBUG_KMS("planes on this crtc\n");
11337         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11338                 struct drm_format_name_buf format_name;
11339                 intel_plane = to_intel_plane(plane);
11340                 if (intel_plane->pipe != crtc->pipe)
11341                         continue;
11342
11343                 state = to_intel_plane_state(plane->state);
11344                 fb = state->base.fb;
11345                 if (!fb) {
11346                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11347                                       plane->base.id, plane->name, state->scaler_id);
11348                         continue;
11349                 }
11350
11351                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11352                               plane->base.id, plane->name,
11353                               fb->base.id, fb->width, fb->height,
11354                               drm_get_format_name(fb->format->format, &format_name));
11355                 if (INTEL_GEN(dev_priv) >= 9)
11356                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11357                                       state->scaler_id,
11358                                       state->base.src.x1 >> 16,
11359                                       state->base.src.y1 >> 16,
11360                                       drm_rect_width(&state->base.src) >> 16,
11361                                       drm_rect_height(&state->base.src) >> 16,
11362                                       state->base.dst.x1, state->base.dst.y1,
11363                                       drm_rect_width(&state->base.dst),
11364                                       drm_rect_height(&state->base.dst));
11365         }
11366 }
11367
11368 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11369 {
11370         struct drm_device *dev = state->dev;
11371         struct drm_connector *connector;
11372         struct drm_connector_list_iter conn_iter;
11373         unsigned int used_ports = 0;
11374         unsigned int used_mst_ports = 0;
11375         bool ret = true;
11376
11377         /*
11378          * Walk the connector list instead of the encoder
11379          * list to detect the problem on ddi platforms
11380          * where there's just one encoder per digital port.
11381          */
11382         drm_connector_list_iter_begin(dev, &conn_iter);
11383         drm_for_each_connector_iter(connector, &conn_iter) {
11384                 struct drm_connector_state *connector_state;
11385                 struct intel_encoder *encoder;
11386
11387                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11388                 if (!connector_state)
11389                         connector_state = connector->state;
11390
11391                 if (!connector_state->best_encoder)
11392                         continue;
11393
11394                 encoder = to_intel_encoder(connector_state->best_encoder);
11395
11396                 WARN_ON(!connector_state->crtc);
11397
11398                 switch (encoder->type) {
11399                         unsigned int port_mask;
11400                 case INTEL_OUTPUT_DDI:
11401                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11402                                 break;
11403                         /* else: fall through */
11404                 case INTEL_OUTPUT_DP:
11405                 case INTEL_OUTPUT_HDMI:
11406                 case INTEL_OUTPUT_EDP:
11407                         port_mask = 1 << encoder->port;
11408
11409                         /* the same port mustn't appear more than once */
11410                         if (used_ports & port_mask)
11411                                 ret = false;
11412
11413                         used_ports |= port_mask;
11414                         break;
11415                 case INTEL_OUTPUT_DP_MST:
11416                         used_mst_ports |=
11417                                 1 << encoder->port;
11418                         break;
11419                 default:
11420                         break;
11421                 }
11422         }
11423         drm_connector_list_iter_end(&conn_iter);
11424
11425         /* can't mix MST and SST/HDMI on the same port */
11426         if (used_ports & used_mst_ports)
11427                 return false;
11428
11429         return ret;
11430 }
11431
11432 static void
11433 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11434 {
11435         struct drm_i915_private *dev_priv =
11436                 to_i915(crtc_state->base.crtc->dev);
11437         struct intel_crtc_scaler_state scaler_state;
11438         struct intel_dpll_hw_state dpll_hw_state;
11439         struct intel_shared_dpll *shared_dpll;
11440         struct intel_crtc_wm_state wm_state;
11441         bool force_thru, ips_force_disable;
11442
11443         /* FIXME: before the switch to atomic started, a new pipe_config was
11444          * kzalloc'd. Code that depends on any field being zero should be
11445          * fixed, so that the crtc_state can be safely duplicated. For now,
11446          * only fields that are know to not cause problems are preserved. */
11447
11448         scaler_state = crtc_state->scaler_state;
11449         shared_dpll = crtc_state->shared_dpll;
11450         dpll_hw_state = crtc_state->dpll_hw_state;
11451         force_thru = crtc_state->pch_pfit.force_thru;
11452         ips_force_disable = crtc_state->ips_force_disable;
11453         if (IS_G4X(dev_priv) ||
11454             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11455                 wm_state = crtc_state->wm;
11456
11457         /* Keep base drm_crtc_state intact, only clear our extended struct */
11458         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11459         memset(&crtc_state->base + 1, 0,
11460                sizeof(*crtc_state) - sizeof(crtc_state->base));
11461
11462         crtc_state->scaler_state = scaler_state;
11463         crtc_state->shared_dpll = shared_dpll;
11464         crtc_state->dpll_hw_state = dpll_hw_state;
11465         crtc_state->pch_pfit.force_thru = force_thru;
11466         crtc_state->ips_force_disable = ips_force_disable;
11467         if (IS_G4X(dev_priv) ||
11468             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11469                 crtc_state->wm = wm_state;
11470 }
11471
11472 static int
11473 intel_modeset_pipe_config(struct drm_crtc *crtc,
11474                           struct intel_crtc_state *pipe_config)
11475 {
11476         struct drm_atomic_state *state = pipe_config->base.state;
11477         struct intel_encoder *encoder;
11478         struct drm_connector *connector;
11479         struct drm_connector_state *connector_state;
11480         int base_bpp, ret;
11481         int i;
11482         bool retry = true;
11483
11484         clear_intel_crtc_state(pipe_config);
11485
11486         pipe_config->cpu_transcoder =
11487                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11488
11489         /*
11490          * Sanitize sync polarity flags based on requested ones. If neither
11491          * positive or negative polarity is requested, treat this as meaning
11492          * negative polarity.
11493          */
11494         if (!(pipe_config->base.adjusted_mode.flags &
11495               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11496                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11497
11498         if (!(pipe_config->base.adjusted_mode.flags &
11499               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11500                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11501
11502         ret = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11503                                         pipe_config);
11504         if (ret)
11505                 return ret;
11506
11507         base_bpp = pipe_config->pipe_bpp;
11508
11509         /*
11510          * Determine the real pipe dimensions. Note that stereo modes can
11511          * increase the actual pipe size due to the frame doubling and
11512          * insertion of additional space for blanks between the frame. This
11513          * is stored in the crtc timings. We use the requested mode to do this
11514          * computation to clearly distinguish it from the adjusted mode, which
11515          * can be changed by the connectors in the below retry loop.
11516          */
11517         drm_mode_get_hv_timing(&pipe_config->base.mode,
11518                                &pipe_config->pipe_src_w,
11519                                &pipe_config->pipe_src_h);
11520
11521         for_each_new_connector_in_state(state, connector, connector_state, i) {
11522                 if (connector_state->crtc != crtc)
11523                         continue;
11524
11525                 encoder = to_intel_encoder(connector_state->best_encoder);
11526
11527                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11528                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11529                         return -EINVAL;
11530                 }
11531
11532                 /*
11533                  * Determine output_types before calling the .compute_config()
11534                  * hooks so that the hooks can use this information safely.
11535                  */
11536                 if (encoder->compute_output_type)
11537                         pipe_config->output_types |=
11538                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11539                                                                  connector_state));
11540                 else
11541                         pipe_config->output_types |= BIT(encoder->type);
11542         }
11543
11544 encoder_retry:
11545         /* Ensure the port clock defaults are reset when retrying. */
11546         pipe_config->port_clock = 0;
11547         pipe_config->pixel_multiplier = 1;
11548
11549         /* Fill in default crtc timings, allow encoders to overwrite them. */
11550         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11551                               CRTC_STEREO_DOUBLE);
11552
11553         /* Pass our mode to the connectors and the CRTC to give them a chance to
11554          * adjust it according to limitations or connector properties, and also
11555          * a chance to reject the mode entirely.
11556          */
11557         for_each_new_connector_in_state(state, connector, connector_state, i) {
11558                 if (connector_state->crtc != crtc)
11559                         continue;
11560
11561                 encoder = to_intel_encoder(connector_state->best_encoder);
11562                 ret = encoder->compute_config(encoder, pipe_config,
11563                                               connector_state);
11564                 if (ret < 0) {
11565                         if (ret != -EDEADLK)
11566                                 DRM_DEBUG_KMS("Encoder config failure: %d\n",
11567                                               ret);
11568                         return ret;
11569                 }
11570         }
11571
11572         /* Set default port clock if not overwritten by the encoder. Needs to be
11573          * done afterwards in case the encoder adjusts the mode. */
11574         if (!pipe_config->port_clock)
11575                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11576                         * pipe_config->pixel_multiplier;
11577
11578         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11579         if (ret == -EDEADLK)
11580                 return ret;
11581         if (ret < 0) {
11582                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11583                 return ret;
11584         }
11585
11586         if (ret == RETRY) {
11587                 if (WARN(!retry, "loop in pipe configuration computation\n"))
11588                         return -EINVAL;
11589
11590                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11591                 retry = false;
11592                 goto encoder_retry;
11593         }
11594
11595         /* Dithering seems to not pass-through bits correctly when it should, so
11596          * only enable it on 6bpc panels and when its not a compliance
11597          * test requesting 6bpc video pattern.
11598          */
11599         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11600                 !pipe_config->dither_force_disable;
11601         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11602                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11603
11604         return 0;
11605 }
11606
11607 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11608 {
11609         int diff;
11610
11611         if (clock1 == clock2)
11612                 return true;
11613
11614         if (!clock1 || !clock2)
11615                 return false;
11616
11617         diff = abs(clock1 - clock2);
11618
11619         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11620                 return true;
11621
11622         return false;
11623 }
11624
11625 static bool
11626 intel_compare_m_n(unsigned int m, unsigned int n,
11627                   unsigned int m2, unsigned int n2,
11628                   bool exact)
11629 {
11630         if (m == m2 && n == n2)
11631                 return true;
11632
11633         if (exact || !m || !n || !m2 || !n2)
11634                 return false;
11635
11636         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11637
11638         if (n > n2) {
11639                 while (n > n2) {
11640                         m2 <<= 1;
11641                         n2 <<= 1;
11642                 }
11643         } else if (n < n2) {
11644                 while (n < n2) {
11645                         m <<= 1;
11646                         n <<= 1;
11647                 }
11648         }
11649
11650         if (n != n2)
11651                 return false;
11652
11653         return intel_fuzzy_clock_check(m, m2);
11654 }
11655
11656 static bool
11657 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11658                        struct intel_link_m_n *m2_n2,
11659                        bool adjust)
11660 {
11661         if (m_n->tu == m2_n2->tu &&
11662             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11663                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11664             intel_compare_m_n(m_n->link_m, m_n->link_n,
11665                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11666                 if (adjust)
11667                         *m2_n2 = *m_n;
11668
11669                 return true;
11670         }
11671
11672         return false;
11673 }
11674
11675 static void __printf(3, 4)
11676 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11677 {
11678         struct va_format vaf;
11679         va_list args;
11680
11681         va_start(args, format);
11682         vaf.fmt = format;
11683         vaf.va = &args;
11684
11685         if (adjust)
11686                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11687         else
11688                 drm_err("mismatch in %s %pV", name, &vaf);
11689
11690         va_end(args);
11691 }
11692
11693 static bool
11694 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11695                           struct intel_crtc_state *current_config,
11696                           struct intel_crtc_state *pipe_config,
11697                           bool adjust)
11698 {
11699         bool ret = true;
11700         bool fixup_inherited = adjust &&
11701                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11702                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11703
11704         if (fixup_inherited && !i915_modparams.fastboot) {
11705                 DRM_DEBUG_KMS("initial modeset and fastboot not set\n");
11706                 ret = false;
11707         }
11708
11709 #define PIPE_CONF_CHECK_X(name) do { \
11710         if (current_config->name != pipe_config->name) { \
11711                 pipe_config_err(adjust, __stringify(name), \
11712                           "(expected 0x%08x, found 0x%08x)\n", \
11713                           current_config->name, \
11714                           pipe_config->name); \
11715                 ret = false; \
11716         } \
11717 } while (0)
11718
11719 #define PIPE_CONF_CHECK_I(name) do { \
11720         if (current_config->name != pipe_config->name) { \
11721                 pipe_config_err(adjust, __stringify(name), \
11722                           "(expected %i, found %i)\n", \
11723                           current_config->name, \
11724                           pipe_config->name); \
11725                 ret = false; \
11726         } \
11727 } while (0)
11728
11729 #define PIPE_CONF_CHECK_BOOL(name) do { \
11730         if (current_config->name != pipe_config->name) { \
11731                 pipe_config_err(adjust, __stringify(name), \
11732                           "(expected %s, found %s)\n", \
11733                           yesno(current_config->name), \
11734                           yesno(pipe_config->name)); \
11735                 ret = false; \
11736         } \
11737 } while (0)
11738
11739 /*
11740  * Checks state where we only read out the enabling, but not the entire
11741  * state itself (like full infoframes or ELD for audio). These states
11742  * require a full modeset on bootup to fix up.
11743  */
11744 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11745         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11746                 PIPE_CONF_CHECK_BOOL(name); \
11747         } else { \
11748                 pipe_config_err(adjust, __stringify(name), \
11749                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11750                           yesno(current_config->name), \
11751                           yesno(pipe_config->name)); \
11752                 ret = false; \
11753         } \
11754 } while (0)
11755
11756 #define PIPE_CONF_CHECK_P(name) do { \
11757         if (current_config->name != pipe_config->name) { \
11758                 pipe_config_err(adjust, __stringify(name), \
11759                           "(expected %p, found %p)\n", \
11760                           current_config->name, \
11761                           pipe_config->name); \
11762                 ret = false; \
11763         } \
11764 } while (0)
11765
11766 #define PIPE_CONF_CHECK_M_N(name) do { \
11767         if (!intel_compare_link_m_n(&current_config->name, \
11768                                     &pipe_config->name,\
11769                                     adjust)) { \
11770                 pipe_config_err(adjust, __stringify(name), \
11771                           "(expected tu %i gmch %i/%i link %i/%i, " \
11772                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11773                           current_config->name.tu, \
11774                           current_config->name.gmch_m, \
11775                           current_config->name.gmch_n, \
11776                           current_config->name.link_m, \
11777                           current_config->name.link_n, \
11778                           pipe_config->name.tu, \
11779                           pipe_config->name.gmch_m, \
11780                           pipe_config->name.gmch_n, \
11781                           pipe_config->name.link_m, \
11782                           pipe_config->name.link_n); \
11783                 ret = false; \
11784         } \
11785 } while (0)
11786
11787 /* This is required for BDW+ where there is only one set of registers for
11788  * switching between high and low RR.
11789  * This macro can be used whenever a comparison has to be made between one
11790  * hw state and multiple sw state variables.
11791  */
11792 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11793         if (!intel_compare_link_m_n(&current_config->name, \
11794                                     &pipe_config->name, adjust) && \
11795             !intel_compare_link_m_n(&current_config->alt_name, \
11796                                     &pipe_config->name, adjust)) { \
11797                 pipe_config_err(adjust, __stringify(name), \
11798                           "(expected tu %i gmch %i/%i link %i/%i, " \
11799                           "or tu %i gmch %i/%i link %i/%i, " \
11800                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11801                           current_config->name.tu, \
11802                           current_config->name.gmch_m, \
11803                           current_config->name.gmch_n, \
11804                           current_config->name.link_m, \
11805                           current_config->name.link_n, \
11806                           current_config->alt_name.tu, \
11807                           current_config->alt_name.gmch_m, \
11808                           current_config->alt_name.gmch_n, \
11809                           current_config->alt_name.link_m, \
11810                           current_config->alt_name.link_n, \
11811                           pipe_config->name.tu, \
11812                           pipe_config->name.gmch_m, \
11813                           pipe_config->name.gmch_n, \
11814                           pipe_config->name.link_m, \
11815                           pipe_config->name.link_n); \
11816                 ret = false; \
11817         } \
11818 } while (0)
11819
11820 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11821         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11822                 pipe_config_err(adjust, __stringify(name), \
11823                           "(%x) (expected %i, found %i)\n", \
11824                           (mask), \
11825                           current_config->name & (mask), \
11826                           pipe_config->name & (mask)); \
11827                 ret = false; \
11828         } \
11829 } while (0)
11830
11831 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11832         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11833                 pipe_config_err(adjust, __stringify(name), \
11834                           "(expected %i, found %i)\n", \
11835                           current_config->name, \
11836                           pipe_config->name); \
11837                 ret = false; \
11838         } \
11839 } while (0)
11840
11841 #define PIPE_CONF_QUIRK(quirk)  \
11842         ((current_config->quirks | pipe_config->quirks) & (quirk))
11843
11844         PIPE_CONF_CHECK_I(cpu_transcoder);
11845
11846         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11847         PIPE_CONF_CHECK_I(fdi_lanes);
11848         PIPE_CONF_CHECK_M_N(fdi_m_n);
11849
11850         PIPE_CONF_CHECK_I(lane_count);
11851         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11852
11853         if (INTEL_GEN(dev_priv) < 8) {
11854                 PIPE_CONF_CHECK_M_N(dp_m_n);
11855
11856                 if (current_config->has_drrs)
11857                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11858         } else
11859                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11860
11861         PIPE_CONF_CHECK_X(output_types);
11862
11863         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11864         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11865         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11866         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11867         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11868         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11869
11870         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11871         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11872         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11873         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11874         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11875         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11876
11877         PIPE_CONF_CHECK_I(pixel_multiplier);
11878         PIPE_CONF_CHECK_I(output_format);
11879         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11880         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11881             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11882                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11883
11884         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11885         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11886         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11887
11888         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11889
11890         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11891                               DRM_MODE_FLAG_INTERLACE);
11892
11893         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11894                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11895                                       DRM_MODE_FLAG_PHSYNC);
11896                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11897                                       DRM_MODE_FLAG_NHSYNC);
11898                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11899                                       DRM_MODE_FLAG_PVSYNC);
11900                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11901                                       DRM_MODE_FLAG_NVSYNC);
11902         }
11903
11904         PIPE_CONF_CHECK_X(gmch_pfit.control);
11905         /* pfit ratios are autocomputed by the hw on gen4+ */
11906         if (INTEL_GEN(dev_priv) < 4)
11907                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11908         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11909
11910         if (!adjust) {
11911                 PIPE_CONF_CHECK_I(pipe_src_w);
11912                 PIPE_CONF_CHECK_I(pipe_src_h);
11913
11914                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11915                 if (current_config->pch_pfit.enabled) {
11916                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11917                         PIPE_CONF_CHECK_X(pch_pfit.size);
11918                 }
11919
11920                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11921                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11922         }
11923
11924         PIPE_CONF_CHECK_BOOL(double_wide);
11925
11926         PIPE_CONF_CHECK_P(shared_dpll);
11927         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11928         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11929         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11930         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11931         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11932         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11933         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11934         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11935         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11936         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11937         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11938         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11939         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11940         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11941         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11942         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11943         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11944         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11945         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11946         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11947         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11948         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11949         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11950         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11951         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11952         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11953         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11954         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11955         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11956         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11957         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11958
11959         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11960         PIPE_CONF_CHECK_X(dsi_pll.div);
11961
11962         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11963                 PIPE_CONF_CHECK_I(pipe_bpp);
11964
11965         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11966         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11967
11968         PIPE_CONF_CHECK_I(min_voltage_level);
11969
11970 #undef PIPE_CONF_CHECK_X
11971 #undef PIPE_CONF_CHECK_I
11972 #undef PIPE_CONF_CHECK_BOOL
11973 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11974 #undef PIPE_CONF_CHECK_P
11975 #undef PIPE_CONF_CHECK_FLAGS
11976 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11977 #undef PIPE_CONF_QUIRK
11978
11979         return ret;
11980 }
11981
11982 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11983                                            const struct intel_crtc_state *pipe_config)
11984 {
11985         if (pipe_config->has_pch_encoder) {
11986                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11987                                                             &pipe_config->fdi_m_n);
11988                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11989
11990                 /*
11991                  * FDI already provided one idea for the dotclock.
11992                  * Yell if the encoder disagrees.
11993                  */
11994                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11995                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11996                      fdi_dotclock, dotclock);
11997         }
11998 }
11999
12000 static void verify_wm_state(struct drm_crtc *crtc,
12001                             struct drm_crtc_state *new_state)
12002 {
12003         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12004         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12005         struct skl_pipe_wm hw_wm, *sw_wm;
12006         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12007         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12008         struct skl_ddb_entry hw_ddb_y[I915_MAX_PLANES];
12009         struct skl_ddb_entry hw_ddb_uv[I915_MAX_PLANES];
12010         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12011         const enum pipe pipe = intel_crtc->pipe;
12012         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12013
12014         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12015                 return;
12016
12017         skl_pipe_wm_get_hw_state(intel_crtc, &hw_wm);
12018         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12019
12020         skl_pipe_ddb_get_hw_state(intel_crtc, hw_ddb_y, hw_ddb_uv);
12021
12022         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12023         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12024
12025         if (INTEL_GEN(dev_priv) >= 11)
12026                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
12027                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
12028                                   sw_ddb->enabled_slices,
12029                                   hw_ddb.enabled_slices);
12030         /* planes */
12031         for_each_universal_plane(dev_priv, pipe, plane) {
12032                 hw_plane_wm = &hw_wm.planes[plane];
12033                 sw_plane_wm = &sw_wm->planes[plane];
12034
12035                 /* Watermarks */
12036                 for (level = 0; level <= max_level; level++) {
12037                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12038                                                 &sw_plane_wm->wm[level]))
12039                                 continue;
12040
12041                         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",
12042                                   pipe_name(pipe), plane + 1, level,
12043                                   sw_plane_wm->wm[level].plane_en,
12044                                   sw_plane_wm->wm[level].plane_res_b,
12045                                   sw_plane_wm->wm[level].plane_res_l,
12046                                   hw_plane_wm->wm[level].plane_en,
12047                                   hw_plane_wm->wm[level].plane_res_b,
12048                                   hw_plane_wm->wm[level].plane_res_l);
12049                 }
12050
12051                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12052                                          &sw_plane_wm->trans_wm)) {
12053                         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",
12054                                   pipe_name(pipe), plane + 1,
12055                                   sw_plane_wm->trans_wm.plane_en,
12056                                   sw_plane_wm->trans_wm.plane_res_b,
12057                                   sw_plane_wm->trans_wm.plane_res_l,
12058                                   hw_plane_wm->trans_wm.plane_en,
12059                                   hw_plane_wm->trans_wm.plane_res_b,
12060                                   hw_plane_wm->trans_wm.plane_res_l);
12061                 }
12062
12063                 /* DDB */
12064                 hw_ddb_entry = &hw_ddb_y[plane];
12065                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[plane];
12066
12067                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12068                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12069                                   pipe_name(pipe), plane + 1,
12070                                   sw_ddb_entry->start, sw_ddb_entry->end,
12071                                   hw_ddb_entry->start, hw_ddb_entry->end);
12072                 }
12073         }
12074
12075         /*
12076          * cursor
12077          * If the cursor plane isn't active, we may not have updated it's ddb
12078          * allocation. In that case since the ddb allocation will be updated
12079          * once the plane becomes visible, we can skip this check
12080          */
12081         if (1) {
12082                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
12083                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12084
12085                 /* Watermarks */
12086                 for (level = 0; level <= max_level; level++) {
12087                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12088                                                 &sw_plane_wm->wm[level]))
12089                                 continue;
12090
12091                         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",
12092                                   pipe_name(pipe), level,
12093                                   sw_plane_wm->wm[level].plane_en,
12094                                   sw_plane_wm->wm[level].plane_res_b,
12095                                   sw_plane_wm->wm[level].plane_res_l,
12096                                   hw_plane_wm->wm[level].plane_en,
12097                                   hw_plane_wm->wm[level].plane_res_b,
12098                                   hw_plane_wm->wm[level].plane_res_l);
12099                 }
12100
12101                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12102                                          &sw_plane_wm->trans_wm)) {
12103                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12104                                   pipe_name(pipe),
12105                                   sw_plane_wm->trans_wm.plane_en,
12106                                   sw_plane_wm->trans_wm.plane_res_b,
12107                                   sw_plane_wm->trans_wm.plane_res_l,
12108                                   hw_plane_wm->trans_wm.plane_en,
12109                                   hw_plane_wm->trans_wm.plane_res_b,
12110                                   hw_plane_wm->trans_wm.plane_res_l);
12111                 }
12112
12113                 /* DDB */
12114                 hw_ddb_entry = &hw_ddb_y[PLANE_CURSOR];
12115                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[PLANE_CURSOR];
12116
12117                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12118                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12119                                   pipe_name(pipe),
12120                                   sw_ddb_entry->start, sw_ddb_entry->end,
12121                                   hw_ddb_entry->start, hw_ddb_entry->end);
12122                 }
12123         }
12124 }
12125
12126 static void
12127 verify_connector_state(struct drm_device *dev,
12128                        struct drm_atomic_state *state,
12129                        struct drm_crtc *crtc)
12130 {
12131         struct drm_connector *connector;
12132         struct drm_connector_state *new_conn_state;
12133         int i;
12134
12135         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12136                 struct drm_encoder *encoder = connector->encoder;
12137                 struct drm_crtc_state *crtc_state = NULL;
12138
12139                 if (new_conn_state->crtc != crtc)
12140                         continue;
12141
12142                 if (crtc)
12143                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12144
12145                 intel_connector_verify_state(crtc_state, new_conn_state);
12146
12147                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12148                      "connector's atomic encoder doesn't match legacy encoder\n");
12149         }
12150 }
12151
12152 static void
12153 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12154 {
12155         struct intel_encoder *encoder;
12156         struct drm_connector *connector;
12157         struct drm_connector_state *old_conn_state, *new_conn_state;
12158         int i;
12159
12160         for_each_intel_encoder(dev, encoder) {
12161                 bool enabled = false, found = false;
12162                 enum pipe pipe;
12163
12164                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12165                               encoder->base.base.id,
12166                               encoder->base.name);
12167
12168                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12169                                                    new_conn_state, i) {
12170                         if (old_conn_state->best_encoder == &encoder->base)
12171                                 found = true;
12172
12173                         if (new_conn_state->best_encoder != &encoder->base)
12174                                 continue;
12175                         found = enabled = true;
12176
12177                         I915_STATE_WARN(new_conn_state->crtc !=
12178                                         encoder->base.crtc,
12179                              "connector's crtc doesn't match encoder crtc\n");
12180                 }
12181
12182                 if (!found)
12183                         continue;
12184
12185                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12186                      "encoder's enabled state mismatch "
12187                      "(expected %i, found %i)\n",
12188                      !!encoder->base.crtc, enabled);
12189
12190                 if (!encoder->base.crtc) {
12191                         bool active;
12192
12193                         active = encoder->get_hw_state(encoder, &pipe);
12194                         I915_STATE_WARN(active,
12195                              "encoder detached but still enabled on pipe %c.\n",
12196                              pipe_name(pipe));
12197                 }
12198         }
12199 }
12200
12201 static void
12202 verify_crtc_state(struct drm_crtc *crtc,
12203                   struct drm_crtc_state *old_crtc_state,
12204                   struct drm_crtc_state *new_crtc_state)
12205 {
12206         struct drm_device *dev = crtc->dev;
12207         struct drm_i915_private *dev_priv = to_i915(dev);
12208         struct intel_encoder *encoder;
12209         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12210         struct intel_crtc_state *pipe_config, *sw_config;
12211         struct drm_atomic_state *old_state;
12212         bool active;
12213
12214         old_state = old_crtc_state->state;
12215         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12216         pipe_config = to_intel_crtc_state(old_crtc_state);
12217         memset(pipe_config, 0, sizeof(*pipe_config));
12218         pipe_config->base.crtc = crtc;
12219         pipe_config->base.state = old_state;
12220
12221         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12222
12223         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12224
12225         /* we keep both pipes enabled on 830 */
12226         if (IS_I830(dev_priv))
12227                 active = new_crtc_state->active;
12228
12229         I915_STATE_WARN(new_crtc_state->active != active,
12230              "crtc active state doesn't match with hw state "
12231              "(expected %i, found %i)\n", new_crtc_state->active, active);
12232
12233         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12234              "transitional active state does not match atomic hw state "
12235              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12236
12237         for_each_encoder_on_crtc(dev, crtc, encoder) {
12238                 enum pipe pipe;
12239
12240                 active = encoder->get_hw_state(encoder, &pipe);
12241                 I915_STATE_WARN(active != new_crtc_state->active,
12242                         "[ENCODER:%i] active %i with crtc active %i\n",
12243                         encoder->base.base.id, active, new_crtc_state->active);
12244
12245                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12246                                 "Encoder connected to wrong pipe %c\n",
12247                                 pipe_name(pipe));
12248
12249                 if (active)
12250                         encoder->get_config(encoder, pipe_config);
12251         }
12252
12253         intel_crtc_compute_pixel_rate(pipe_config);
12254
12255         if (!new_crtc_state->active)
12256                 return;
12257
12258         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12259
12260         sw_config = to_intel_crtc_state(new_crtc_state);
12261         if (!intel_pipe_config_compare(dev_priv, sw_config,
12262                                        pipe_config, false)) {
12263                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12264                 intel_dump_pipe_config(intel_crtc, pipe_config,
12265                                        "[hw state]");
12266                 intel_dump_pipe_config(intel_crtc, sw_config,
12267                                        "[sw state]");
12268         }
12269 }
12270
12271 static void
12272 intel_verify_planes(struct intel_atomic_state *state)
12273 {
12274         struct intel_plane *plane;
12275         const struct intel_plane_state *plane_state;
12276         int i;
12277
12278         for_each_new_intel_plane_in_state(state, plane,
12279                                           plane_state, i)
12280                 assert_plane(plane, plane_state->base.visible);
12281 }
12282
12283 static void
12284 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12285                          struct intel_shared_dpll *pll,
12286                          struct drm_crtc *crtc,
12287                          struct drm_crtc_state *new_state)
12288 {
12289         struct intel_dpll_hw_state dpll_hw_state;
12290         unsigned int crtc_mask;
12291         bool active;
12292
12293         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12294
12295         DRM_DEBUG_KMS("%s\n", pll->info->name);
12296
12297         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12298
12299         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12300                 I915_STATE_WARN(!pll->on && pll->active_mask,
12301                      "pll in active use but not on in sw tracking\n");
12302                 I915_STATE_WARN(pll->on && !pll->active_mask,
12303                      "pll is on but not used by any active crtc\n");
12304                 I915_STATE_WARN(pll->on != active,
12305                      "pll on state mismatch (expected %i, found %i)\n",
12306                      pll->on, active);
12307         }
12308
12309         if (!crtc) {
12310                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12311                                 "more active pll users than references: %x vs %x\n",
12312                                 pll->active_mask, pll->state.crtc_mask);
12313
12314                 return;
12315         }
12316
12317         crtc_mask = drm_crtc_mask(crtc);
12318
12319         if (new_state->active)
12320                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12321                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12322                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12323         else
12324                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12325                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12326                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12327
12328         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12329                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12330                         crtc_mask, pll->state.crtc_mask);
12331
12332         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12333                                           &dpll_hw_state,
12334                                           sizeof(dpll_hw_state)),
12335                         "pll hw state mismatch\n");
12336 }
12337
12338 static void
12339 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12340                          struct drm_crtc_state *old_crtc_state,
12341                          struct drm_crtc_state *new_crtc_state)
12342 {
12343         struct drm_i915_private *dev_priv = to_i915(dev);
12344         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12345         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12346
12347         if (new_state->shared_dpll)
12348                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12349
12350         if (old_state->shared_dpll &&
12351             old_state->shared_dpll != new_state->shared_dpll) {
12352                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12353                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12354
12355                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12356                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12357                                 pipe_name(drm_crtc_index(crtc)));
12358                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12359                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12360                                 pipe_name(drm_crtc_index(crtc)));
12361         }
12362 }
12363
12364 static void
12365 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12366                           struct drm_atomic_state *state,
12367                           struct drm_crtc_state *old_state,
12368                           struct drm_crtc_state *new_state)
12369 {
12370         if (!needs_modeset(new_state) &&
12371             !to_intel_crtc_state(new_state)->update_pipe)
12372                 return;
12373
12374         verify_wm_state(crtc, new_state);
12375         verify_connector_state(crtc->dev, state, crtc);
12376         verify_crtc_state(crtc, old_state, new_state);
12377         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12378 }
12379
12380 static void
12381 verify_disabled_dpll_state(struct drm_device *dev)
12382 {
12383         struct drm_i915_private *dev_priv = to_i915(dev);
12384         int i;
12385
12386         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12387                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12388 }
12389
12390 static void
12391 intel_modeset_verify_disabled(struct drm_device *dev,
12392                               struct drm_atomic_state *state)
12393 {
12394         verify_encoder_state(dev, state);
12395         verify_connector_state(dev, state, NULL);
12396         verify_disabled_dpll_state(dev);
12397 }
12398
12399 static void update_scanline_offset(const struct intel_crtc_state *crtc_state)
12400 {
12401         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
12402         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12403
12404         /*
12405          * The scanline counter increments at the leading edge of hsync.
12406          *
12407          * On most platforms it starts counting from vtotal-1 on the
12408          * first active line. That means the scanline counter value is
12409          * always one less than what we would expect. Ie. just after
12410          * start of vblank, which also occurs at start of hsync (on the
12411          * last active line), the scanline counter will read vblank_start-1.
12412          *
12413          * On gen2 the scanline counter starts counting from 1 instead
12414          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12415          * to keep the value positive), instead of adding one.
12416          *
12417          * On HSW+ the behaviour of the scanline counter depends on the output
12418          * type. For DP ports it behaves like most other platforms, but on HDMI
12419          * there's an extra 1 line difference. So we need to add two instead of
12420          * one to the value.
12421          *
12422          * On VLV/CHV DSI the scanline counter would appear to increment
12423          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12424          * that means we can't tell whether we're in vblank or not while
12425          * we're on that particular line. We must still set scanline_offset
12426          * to 1 so that the vblank timestamps come out correct when we query
12427          * the scanline counter from within the vblank interrupt handler.
12428          * However if queried just before the start of vblank we'll get an
12429          * answer that's slightly in the future.
12430          */
12431         if (IS_GEN(dev_priv, 2)) {
12432                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
12433                 int vtotal;
12434
12435                 vtotal = adjusted_mode->crtc_vtotal;
12436                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12437                         vtotal /= 2;
12438
12439                 crtc->scanline_offset = vtotal - 1;
12440         } else if (HAS_DDI(dev_priv) &&
12441                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
12442                 crtc->scanline_offset = 2;
12443         } else
12444                 crtc->scanline_offset = 1;
12445 }
12446
12447 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12448 {
12449         struct drm_device *dev = state->dev;
12450         struct drm_i915_private *dev_priv = to_i915(dev);
12451         struct drm_crtc *crtc;
12452         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12453         int i;
12454
12455         if (!dev_priv->display.crtc_compute_clock)
12456                 return;
12457
12458         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12459                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12460                 struct intel_shared_dpll *old_dpll =
12461                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12462
12463                 if (!needs_modeset(new_crtc_state))
12464                         continue;
12465
12466                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12467
12468                 if (!old_dpll)
12469                         continue;
12470
12471                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12472         }
12473 }
12474
12475 /*
12476  * This implements the workaround described in the "notes" section of the mode
12477  * set sequence documentation. When going from no pipes or single pipe to
12478  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12479  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12480  */
12481 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12482 {
12483         struct drm_crtc_state *crtc_state;
12484         struct intel_crtc *intel_crtc;
12485         struct drm_crtc *crtc;
12486         struct intel_crtc_state *first_crtc_state = NULL;
12487         struct intel_crtc_state *other_crtc_state = NULL;
12488         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12489         int i;
12490
12491         /* look at all crtc's that are going to be enabled in during modeset */
12492         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12493                 intel_crtc = to_intel_crtc(crtc);
12494
12495                 if (!crtc_state->active || !needs_modeset(crtc_state))
12496                         continue;
12497
12498                 if (first_crtc_state) {
12499                         other_crtc_state = to_intel_crtc_state(crtc_state);
12500                         break;
12501                 } else {
12502                         first_crtc_state = to_intel_crtc_state(crtc_state);
12503                         first_pipe = intel_crtc->pipe;
12504                 }
12505         }
12506
12507         /* No workaround needed? */
12508         if (!first_crtc_state)
12509                 return 0;
12510
12511         /* w/a possibly needed, check how many crtc's are already enabled. */
12512         for_each_intel_crtc(state->dev, intel_crtc) {
12513                 struct intel_crtc_state *pipe_config;
12514
12515                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12516                 if (IS_ERR(pipe_config))
12517                         return PTR_ERR(pipe_config);
12518
12519                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12520
12521                 if (!pipe_config->base.active ||
12522                     needs_modeset(&pipe_config->base))
12523                         continue;
12524
12525                 /* 2 or more enabled crtcs means no need for w/a */
12526                 if (enabled_pipe != INVALID_PIPE)
12527                         return 0;
12528
12529                 enabled_pipe = intel_crtc->pipe;
12530         }
12531
12532         if (enabled_pipe != INVALID_PIPE)
12533                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12534         else if (other_crtc_state)
12535                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12536
12537         return 0;
12538 }
12539
12540 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12541 {
12542         struct drm_crtc *crtc;
12543
12544         /* Add all pipes to the state */
12545         for_each_crtc(state->dev, crtc) {
12546                 struct drm_crtc_state *crtc_state;
12547
12548                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12549                 if (IS_ERR(crtc_state))
12550                         return PTR_ERR(crtc_state);
12551         }
12552
12553         return 0;
12554 }
12555
12556 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12557 {
12558         struct drm_crtc *crtc;
12559
12560         /*
12561          * Add all pipes to the state, and force
12562          * a modeset on all the active ones.
12563          */
12564         for_each_crtc(state->dev, crtc) {
12565                 struct drm_crtc_state *crtc_state;
12566                 int ret;
12567
12568                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12569                 if (IS_ERR(crtc_state))
12570                         return PTR_ERR(crtc_state);
12571
12572                 if (!crtc_state->active || needs_modeset(crtc_state))
12573                         continue;
12574
12575                 crtc_state->mode_changed = true;
12576
12577                 ret = drm_atomic_add_affected_connectors(state, crtc);
12578                 if (ret)
12579                         return ret;
12580
12581                 ret = drm_atomic_add_affected_planes(state, crtc);
12582                 if (ret)
12583                         return ret;
12584         }
12585
12586         return 0;
12587 }
12588
12589 static int intel_modeset_checks(struct drm_atomic_state *state)
12590 {
12591         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12592         struct drm_i915_private *dev_priv = to_i915(state->dev);
12593         struct drm_crtc *crtc;
12594         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12595         int ret = 0, i;
12596
12597         if (!check_digital_port_conflicts(state)) {
12598                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12599                 return -EINVAL;
12600         }
12601
12602         intel_state->modeset = true;
12603         intel_state->active_crtcs = dev_priv->active_crtcs;
12604         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12605         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12606
12607         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12608                 if (new_crtc_state->active)
12609                         intel_state->active_crtcs |= 1 << i;
12610                 else
12611                         intel_state->active_crtcs &= ~(1 << i);
12612
12613                 if (old_crtc_state->active != new_crtc_state->active)
12614                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12615         }
12616
12617         /*
12618          * See if the config requires any additional preparation, e.g.
12619          * to adjust global state with pipes off.  We need to do this
12620          * here so we can get the modeset_pipe updated config for the new
12621          * mode set on this crtc.  For other crtcs we need to use the
12622          * adjusted_mode bits in the crtc directly.
12623          */
12624         if (dev_priv->display.modeset_calc_cdclk) {
12625                 ret = dev_priv->display.modeset_calc_cdclk(state);
12626                 if (ret < 0)
12627                         return ret;
12628
12629                 /*
12630                  * Writes to dev_priv->cdclk.logical must protected by
12631                  * holding all the crtc locks, even if we don't end up
12632                  * touching the hardware
12633                  */
12634                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12635                                         &intel_state->cdclk.logical)) {
12636                         ret = intel_lock_all_pipes(state);
12637                         if (ret < 0)
12638                                 return ret;
12639                 }
12640
12641                 /* All pipes must be switched off while we change the cdclk. */
12642                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12643                                               &intel_state->cdclk.actual)) {
12644                         ret = intel_modeset_all_pipes(state);
12645                         if (ret < 0)
12646                                 return ret;
12647                 }
12648
12649                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12650                               intel_state->cdclk.logical.cdclk,
12651                               intel_state->cdclk.actual.cdclk);
12652                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12653                               intel_state->cdclk.logical.voltage_level,
12654                               intel_state->cdclk.actual.voltage_level);
12655         } else {
12656                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12657         }
12658
12659         intel_modeset_clear_plls(state);
12660
12661         if (IS_HASWELL(dev_priv))
12662                 return haswell_mode_set_planes_workaround(state);
12663
12664         return 0;
12665 }
12666
12667 /*
12668  * Handle calculation of various watermark data at the end of the atomic check
12669  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12670  * handlers to ensure that all derived state has been updated.
12671  */
12672 static int calc_watermark_data(struct intel_atomic_state *state)
12673 {
12674         struct drm_device *dev = state->base.dev;
12675         struct drm_i915_private *dev_priv = to_i915(dev);
12676
12677         /* Is there platform-specific watermark information to calculate? */
12678         if (dev_priv->display.compute_global_watermarks)
12679                 return dev_priv->display.compute_global_watermarks(state);
12680
12681         return 0;
12682 }
12683
12684 /**
12685  * intel_atomic_check - validate state object
12686  * @dev: drm device
12687  * @state: state to validate
12688  */
12689 static int intel_atomic_check(struct drm_device *dev,
12690                               struct drm_atomic_state *state)
12691 {
12692         struct drm_i915_private *dev_priv = to_i915(dev);
12693         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12694         struct drm_crtc *crtc;
12695         struct drm_crtc_state *old_crtc_state, *crtc_state;
12696         int ret, i;
12697         bool any_ms = false;
12698
12699         /* Catch I915_MODE_FLAG_INHERITED */
12700         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12701                                       crtc_state, i) {
12702                 if (crtc_state->mode.private_flags !=
12703                     old_crtc_state->mode.private_flags)
12704                         crtc_state->mode_changed = true;
12705         }
12706
12707         ret = drm_atomic_helper_check_modeset(dev, state);
12708         if (ret)
12709                 return ret;
12710
12711         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12712                 struct intel_crtc_state *pipe_config =
12713                         to_intel_crtc_state(crtc_state);
12714
12715                 if (!needs_modeset(crtc_state))
12716                         continue;
12717
12718                 if (!crtc_state->enable) {
12719                         any_ms = true;
12720                         continue;
12721                 }
12722
12723                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12724                 if (ret == -EDEADLK)
12725                         return ret;
12726                 if (ret) {
12727                         intel_dump_pipe_config(to_intel_crtc(crtc),
12728                                                pipe_config, "[failed]");
12729                         return ret;
12730                 }
12731
12732                 if (intel_pipe_config_compare(dev_priv,
12733                                         to_intel_crtc_state(old_crtc_state),
12734                                         pipe_config, true)) {
12735                         crtc_state->mode_changed = false;
12736                         pipe_config->update_pipe = true;
12737                 }
12738
12739                 if (needs_modeset(crtc_state))
12740                         any_ms = true;
12741
12742                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12743                                        needs_modeset(crtc_state) ?
12744                                        "[modeset]" : "[fastset]");
12745         }
12746
12747         ret = drm_dp_mst_atomic_check(state);
12748         if (ret)
12749                 return ret;
12750
12751         if (any_ms) {
12752                 ret = intel_modeset_checks(state);
12753
12754                 if (ret)
12755                         return ret;
12756         } else {
12757                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12758         }
12759
12760         ret = icl_add_linked_planes(intel_state);
12761         if (ret)
12762                 return ret;
12763
12764         ret = drm_atomic_helper_check_planes(dev, state);
12765         if (ret)
12766                 return ret;
12767
12768         intel_fbc_choose_crtc(dev_priv, intel_state);
12769         return calc_watermark_data(intel_state);
12770 }
12771
12772 static int intel_atomic_prepare_commit(struct drm_device *dev,
12773                                        struct drm_atomic_state *state)
12774 {
12775         return drm_atomic_helper_prepare_planes(dev, state);
12776 }
12777
12778 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12779 {
12780         struct drm_device *dev = crtc->base.dev;
12781
12782         if (!dev->max_vblank_count)
12783                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12784
12785         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12786 }
12787
12788 static void intel_update_crtc(struct drm_crtc *crtc,
12789                               struct drm_atomic_state *state,
12790                               struct drm_crtc_state *old_crtc_state,
12791                               struct drm_crtc_state *new_crtc_state)
12792 {
12793         struct drm_device *dev = crtc->dev;
12794         struct drm_i915_private *dev_priv = to_i915(dev);
12795         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12796         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12797         bool modeset = needs_modeset(new_crtc_state);
12798         struct intel_plane_state *new_plane_state =
12799                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12800                                                  to_intel_plane(crtc->primary));
12801
12802         if (modeset) {
12803                 update_scanline_offset(pipe_config);
12804                 dev_priv->display.crtc_enable(pipe_config, state);
12805
12806                 /* vblanks work again, re-enable pipe CRC. */
12807                 intel_crtc_enable_pipe_crc(intel_crtc);
12808         } else {
12809                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12810                                        pipe_config);
12811
12812                 if (pipe_config->update_pipe)
12813                         intel_encoders_update_pipe(crtc, pipe_config, state);
12814         }
12815
12816         if (pipe_config->update_pipe && !pipe_config->enable_fbc)
12817                 intel_fbc_disable(intel_crtc);
12818         else if (new_plane_state)
12819                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12820
12821         intel_begin_crtc_commit(crtc, old_crtc_state);
12822
12823         if (INTEL_GEN(dev_priv) >= 9)
12824                 skl_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
12825         else
12826                 i9xx_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
12827
12828         intel_finish_crtc_commit(crtc, old_crtc_state);
12829 }
12830
12831 static void intel_update_crtcs(struct drm_atomic_state *state)
12832 {
12833         struct drm_crtc *crtc;
12834         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12835         int i;
12836
12837         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12838                 if (!new_crtc_state->active)
12839                         continue;
12840
12841                 intel_update_crtc(crtc, state, old_crtc_state,
12842                                   new_crtc_state);
12843         }
12844 }
12845
12846 static void skl_update_crtcs(struct drm_atomic_state *state)
12847 {
12848         struct drm_i915_private *dev_priv = to_i915(state->dev);
12849         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12850         struct drm_crtc *crtc;
12851         struct intel_crtc *intel_crtc;
12852         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12853         struct intel_crtc_state *cstate;
12854         unsigned int updated = 0;
12855         bool progress;
12856         enum pipe pipe;
12857         int i;
12858         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12859         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12860         struct skl_ddb_entry entries[I915_MAX_PIPES] = {};
12861
12862         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12863                 /* ignore allocations for crtc's that have been turned off. */
12864                 if (new_crtc_state->active)
12865                         entries[i] = to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12866
12867         /* If 2nd DBuf slice required, enable it here */
12868         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12869                 icl_dbuf_slices_update(dev_priv, required_slices);
12870
12871         /*
12872          * Whenever the number of active pipes changes, we need to make sure we
12873          * update the pipes in the right order so that their ddb allocations
12874          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12875          * cause pipe underruns and other bad stuff.
12876          */
12877         do {
12878                 progress = false;
12879
12880                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12881                         bool vbl_wait = false;
12882                         unsigned int cmask = drm_crtc_mask(crtc);
12883
12884                         intel_crtc = to_intel_crtc(crtc);
12885                         cstate = to_intel_crtc_state(new_crtc_state);
12886                         pipe = intel_crtc->pipe;
12887
12888                         if (updated & cmask || !cstate->base.active)
12889                                 continue;
12890
12891                         if (skl_ddb_allocation_overlaps(&cstate->wm.skl.ddb,
12892                                                         entries,
12893                                                         INTEL_INFO(dev_priv)->num_pipes, i))
12894                                 continue;
12895
12896                         updated |= cmask;
12897                         entries[i] = cstate->wm.skl.ddb;
12898
12899                         /*
12900                          * If this is an already active pipe, it's DDB changed,
12901                          * and this isn't the last pipe that needs updating
12902                          * then we need to wait for a vblank to pass for the
12903                          * new ddb allocation to take effect.
12904                          */
12905                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12906                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12907                             !new_crtc_state->active_changed &&
12908                             intel_state->wm_results.dirty_pipes != updated)
12909                                 vbl_wait = true;
12910
12911                         intel_update_crtc(crtc, state, old_crtc_state,
12912                                           new_crtc_state);
12913
12914                         if (vbl_wait)
12915                                 intel_wait_for_vblank(dev_priv, pipe);
12916
12917                         progress = true;
12918                 }
12919         } while (progress);
12920
12921         /* If 2nd DBuf slice is no more required disable it */
12922         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12923                 icl_dbuf_slices_update(dev_priv, required_slices);
12924 }
12925
12926 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12927 {
12928         struct intel_atomic_state *state, *next;
12929         struct llist_node *freed;
12930
12931         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12932         llist_for_each_entry_safe(state, next, freed, freed)
12933                 drm_atomic_state_put(&state->base);
12934 }
12935
12936 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12937 {
12938         struct drm_i915_private *dev_priv =
12939                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12940
12941         intel_atomic_helper_free_state(dev_priv);
12942 }
12943
12944 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12945 {
12946         struct wait_queue_entry wait_fence, wait_reset;
12947         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12948
12949         init_wait_entry(&wait_fence, 0);
12950         init_wait_entry(&wait_reset, 0);
12951         for (;;) {
12952                 prepare_to_wait(&intel_state->commit_ready.wait,
12953                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12954                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12955                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12956
12957
12958                 if (i915_sw_fence_done(&intel_state->commit_ready)
12959                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12960                         break;
12961
12962                 schedule();
12963         }
12964         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12965         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12966 }
12967
12968 static void intel_atomic_cleanup_work(struct work_struct *work)
12969 {
12970         struct drm_atomic_state *state =
12971                 container_of(work, struct drm_atomic_state, commit_work);
12972         struct drm_i915_private *i915 = to_i915(state->dev);
12973
12974         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12975         drm_atomic_helper_commit_cleanup_done(state);
12976         drm_atomic_state_put(state);
12977
12978         intel_atomic_helper_free_state(i915);
12979 }
12980
12981 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12982 {
12983         struct drm_device *dev = state->dev;
12984         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12985         struct drm_i915_private *dev_priv = to_i915(dev);
12986         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12987         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
12988         struct drm_crtc *crtc;
12989         struct intel_crtc *intel_crtc;
12990         u64 put_domains[I915_MAX_PIPES] = {};
12991         intel_wakeref_t wakeref = 0;
12992         int i;
12993
12994         intel_atomic_commit_fence_wait(intel_state);
12995
12996         drm_atomic_helper_wait_for_dependencies(state);
12997
12998         if (intel_state->modeset)
12999                 wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13000
13001         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13002                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
13003                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13004                 intel_crtc = to_intel_crtc(crtc);
13005
13006                 if (needs_modeset(new_crtc_state) ||
13007                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13008
13009                         put_domains[intel_crtc->pipe] =
13010                                 modeset_get_crtc_power_domains(crtc,
13011                                         new_intel_crtc_state);
13012                 }
13013
13014                 if (!needs_modeset(new_crtc_state))
13015                         continue;
13016
13017                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
13018
13019                 if (old_crtc_state->active) {
13020                         intel_crtc_disable_planes(intel_state, intel_crtc);
13021
13022                         /*
13023                          * We need to disable pipe CRC before disabling the pipe,
13024                          * or we race against vblank off.
13025                          */
13026                         intel_crtc_disable_pipe_crc(intel_crtc);
13027
13028                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
13029                         intel_crtc->active = false;
13030                         intel_fbc_disable(intel_crtc);
13031                         intel_disable_shared_dpll(old_intel_crtc_state);
13032
13033                         /*
13034                          * Underruns don't always raise
13035                          * interrupts, so check manually.
13036                          */
13037                         intel_check_cpu_fifo_underruns(dev_priv);
13038                         intel_check_pch_fifo_underruns(dev_priv);
13039
13040                         /* FIXME unify this for all platforms */
13041                         if (!new_crtc_state->active &&
13042                             !HAS_GMCH_DISPLAY(dev_priv) &&
13043                             dev_priv->display.initial_watermarks)
13044                                 dev_priv->display.initial_watermarks(intel_state,
13045                                                                      new_intel_crtc_state);
13046                 }
13047         }
13048
13049         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
13050         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
13051                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
13052
13053         if (intel_state->modeset) {
13054                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13055
13056                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
13057
13058                 /*
13059                  * SKL workaround: bspec recommends we disable the SAGV when we
13060                  * have more then one pipe enabled
13061                  */
13062                 if (!intel_can_enable_sagv(state))
13063                         intel_disable_sagv(dev_priv);
13064
13065                 intel_modeset_verify_disabled(dev, state);
13066         }
13067
13068         /* Complete the events for pipes that have now been disabled */
13069         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13070                 bool modeset = needs_modeset(new_crtc_state);
13071
13072                 /* Complete events for now disable pipes here. */
13073                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13074                         spin_lock_irq(&dev->event_lock);
13075                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13076                         spin_unlock_irq(&dev->event_lock);
13077
13078                         new_crtc_state->event = NULL;
13079                 }
13080         }
13081
13082         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13083         dev_priv->display.update_crtcs(state);
13084
13085         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13086          * already, but still need the state for the delayed optimization. To
13087          * fix this:
13088          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13089          * - schedule that vblank worker _before_ calling hw_done
13090          * - at the start of commit_tail, cancel it _synchrously
13091          * - switch over to the vblank wait helper in the core after that since
13092          *   we don't need out special handling any more.
13093          */
13094         drm_atomic_helper_wait_for_flip_done(dev, state);
13095
13096         /*
13097          * Now that the vblank has passed, we can go ahead and program the
13098          * optimal watermarks on platforms that need two-step watermark
13099          * programming.
13100          *
13101          * TODO: Move this (and other cleanup) to an async worker eventually.
13102          */
13103         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13104                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13105
13106                 if (dev_priv->display.optimize_watermarks)
13107                         dev_priv->display.optimize_watermarks(intel_state,
13108                                                               new_intel_crtc_state);
13109         }
13110
13111         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13112                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13113
13114                 if (put_domains[i])
13115                         modeset_put_power_domains(dev_priv, put_domains[i]);
13116
13117                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13118         }
13119
13120         if (intel_state->modeset)
13121                 intel_verify_planes(intel_state);
13122
13123         if (intel_state->modeset && intel_can_enable_sagv(state))
13124                 intel_enable_sagv(dev_priv);
13125
13126         drm_atomic_helper_commit_hw_done(state);
13127
13128         if (intel_state->modeset) {
13129                 /* As one of the primary mmio accessors, KMS has a high
13130                  * likelihood of triggering bugs in unclaimed access. After we
13131                  * finish modesetting, see if an error has been flagged, and if
13132                  * so enable debugging for the next modeset - and hope we catch
13133                  * the culprit.
13134                  */
13135                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13136                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET, wakeref);
13137         }
13138
13139         /*
13140          * Defer the cleanup of the old state to a separate worker to not
13141          * impede the current task (userspace for blocking modesets) that
13142          * are executed inline. For out-of-line asynchronous modesets/flips,
13143          * deferring to a new worker seems overkill, but we would place a
13144          * schedule point (cond_resched()) here anyway to keep latencies
13145          * down.
13146          */
13147         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
13148         queue_work(system_highpri_wq, &state->commit_work);
13149 }
13150
13151 static void intel_atomic_commit_work(struct work_struct *work)
13152 {
13153         struct drm_atomic_state *state =
13154                 container_of(work, struct drm_atomic_state, commit_work);
13155
13156         intel_atomic_commit_tail(state);
13157 }
13158
13159 static int __i915_sw_fence_call
13160 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13161                           enum i915_sw_fence_notify notify)
13162 {
13163         struct intel_atomic_state *state =
13164                 container_of(fence, struct intel_atomic_state, commit_ready);
13165
13166         switch (notify) {
13167         case FENCE_COMPLETE:
13168                 /* we do blocking waits in the worker, nothing to do here */
13169                 break;
13170         case FENCE_FREE:
13171                 {
13172                         struct intel_atomic_helper *helper =
13173                                 &to_i915(state->base.dev)->atomic_helper;
13174
13175                         if (llist_add(&state->freed, &helper->free_list))
13176                                 schedule_work(&helper->free_work);
13177                         break;
13178                 }
13179         }
13180
13181         return NOTIFY_DONE;
13182 }
13183
13184 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13185 {
13186         struct drm_plane_state *old_plane_state, *new_plane_state;
13187         struct drm_plane *plane;
13188         int i;
13189
13190         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13191                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13192                                   intel_fb_obj(new_plane_state->fb),
13193                                   to_intel_plane(plane)->frontbuffer_bit);
13194 }
13195
13196 /**
13197  * intel_atomic_commit - commit validated state object
13198  * @dev: DRM device
13199  * @state: the top-level driver state object
13200  * @nonblock: nonblocking commit
13201  *
13202  * This function commits a top-level state object that has been validated
13203  * with drm_atomic_helper_check().
13204  *
13205  * RETURNS
13206  * Zero for success or -errno.
13207  */
13208 static int intel_atomic_commit(struct drm_device *dev,
13209                                struct drm_atomic_state *state,
13210                                bool nonblock)
13211 {
13212         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13213         struct drm_i915_private *dev_priv = to_i915(dev);
13214         int ret = 0;
13215
13216         drm_atomic_state_get(state);
13217         i915_sw_fence_init(&intel_state->commit_ready,
13218                            intel_atomic_commit_ready);
13219
13220         /*
13221          * The intel_legacy_cursor_update() fast path takes care
13222          * of avoiding the vblank waits for simple cursor
13223          * movement and flips. For cursor on/off and size changes,
13224          * we want to perform the vblank waits so that watermark
13225          * updates happen during the correct frames. Gen9+ have
13226          * double buffered watermarks and so shouldn't need this.
13227          *
13228          * Unset state->legacy_cursor_update before the call to
13229          * drm_atomic_helper_setup_commit() because otherwise
13230          * drm_atomic_helper_wait_for_flip_done() is a noop and
13231          * we get FIFO underruns because we didn't wait
13232          * for vblank.
13233          *
13234          * FIXME doing watermarks and fb cleanup from a vblank worker
13235          * (assuming we had any) would solve these problems.
13236          */
13237         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
13238                 struct intel_crtc_state *new_crtc_state;
13239                 struct intel_crtc *crtc;
13240                 int i;
13241
13242                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
13243                         if (new_crtc_state->wm.need_postvbl_update ||
13244                             new_crtc_state->update_wm_post)
13245                                 state->legacy_cursor_update = false;
13246         }
13247
13248         ret = intel_atomic_prepare_commit(dev, state);
13249         if (ret) {
13250                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13251                 i915_sw_fence_commit(&intel_state->commit_ready);
13252                 return ret;
13253         }
13254
13255         ret = drm_atomic_helper_setup_commit(state, nonblock);
13256         if (!ret)
13257                 ret = drm_atomic_helper_swap_state(state, true);
13258
13259         if (ret) {
13260                 i915_sw_fence_commit(&intel_state->commit_ready);
13261
13262                 drm_atomic_helper_cleanup_planes(dev, state);
13263                 return ret;
13264         }
13265         dev_priv->wm.distrust_bios_wm = false;
13266         intel_shared_dpll_swap_state(state);
13267         intel_atomic_track_fbs(state);
13268
13269         if (intel_state->modeset) {
13270                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
13271                        sizeof(intel_state->min_cdclk));
13272                 memcpy(dev_priv->min_voltage_level,
13273                        intel_state->min_voltage_level,
13274                        sizeof(intel_state->min_voltage_level));
13275                 dev_priv->active_crtcs = intel_state->active_crtcs;
13276                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
13277                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
13278         }
13279
13280         drm_atomic_state_get(state);
13281         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13282
13283         i915_sw_fence_commit(&intel_state->commit_ready);
13284         if (nonblock && intel_state->modeset) {
13285                 queue_work(dev_priv->modeset_wq, &state->commit_work);
13286         } else if (nonblock) {
13287                 queue_work(system_unbound_wq, &state->commit_work);
13288         } else {
13289                 if (intel_state->modeset)
13290                         flush_workqueue(dev_priv->modeset_wq);
13291                 intel_atomic_commit_tail(state);
13292         }
13293
13294         return 0;
13295 }
13296
13297 static const struct drm_crtc_funcs intel_crtc_funcs = {
13298         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13299         .set_config = drm_atomic_helper_set_config,
13300         .destroy = intel_crtc_destroy,
13301         .page_flip = drm_atomic_helper_page_flip,
13302         .atomic_duplicate_state = intel_crtc_duplicate_state,
13303         .atomic_destroy_state = intel_crtc_destroy_state,
13304         .set_crc_source = intel_crtc_set_crc_source,
13305         .verify_crc_source = intel_crtc_verify_crc_source,
13306         .get_crc_sources = intel_crtc_get_crc_sources,
13307 };
13308
13309 struct wait_rps_boost {
13310         struct wait_queue_entry wait;
13311
13312         struct drm_crtc *crtc;
13313         struct i915_request *request;
13314 };
13315
13316 static int do_rps_boost(struct wait_queue_entry *_wait,
13317                         unsigned mode, int sync, void *key)
13318 {
13319         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13320         struct i915_request *rq = wait->request;
13321
13322         /*
13323          * If we missed the vblank, but the request is already running it
13324          * is reasonable to assume that it will complete before the next
13325          * vblank without our intervention, so leave RPS alone.
13326          */
13327         if (!i915_request_started(rq))
13328                 gen6_rps_boost(rq, NULL);
13329         i915_request_put(rq);
13330
13331         drm_crtc_vblank_put(wait->crtc);
13332
13333         list_del(&wait->wait.entry);
13334         kfree(wait);
13335         return 1;
13336 }
13337
13338 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13339                                        struct dma_fence *fence)
13340 {
13341         struct wait_rps_boost *wait;
13342
13343         if (!dma_fence_is_i915(fence))
13344                 return;
13345
13346         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13347                 return;
13348
13349         if (drm_crtc_vblank_get(crtc))
13350                 return;
13351
13352         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13353         if (!wait) {
13354                 drm_crtc_vblank_put(crtc);
13355                 return;
13356         }
13357
13358         wait->request = to_request(dma_fence_get(fence));
13359         wait->crtc = crtc;
13360
13361         wait->wait.func = do_rps_boost;
13362         wait->wait.flags = 0;
13363
13364         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13365 }
13366
13367 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13368 {
13369         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13370         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13371         struct drm_framebuffer *fb = plane_state->base.fb;
13372         struct i915_vma *vma;
13373
13374         if (plane->id == PLANE_CURSOR &&
13375             INTEL_INFO(dev_priv)->display.cursor_needs_physical) {
13376                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13377                 const int align = intel_cursor_alignment(dev_priv);
13378                 int err;
13379
13380                 err = i915_gem_object_attach_phys(obj, align);
13381                 if (err)
13382                         return err;
13383         }
13384
13385         vma = intel_pin_and_fence_fb_obj(fb,
13386                                          &plane_state->view,
13387                                          intel_plane_uses_fence(plane_state),
13388                                          &plane_state->flags);
13389         if (IS_ERR(vma))
13390                 return PTR_ERR(vma);
13391
13392         plane_state->vma = vma;
13393
13394         return 0;
13395 }
13396
13397 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13398 {
13399         struct i915_vma *vma;
13400
13401         vma = fetch_and_zero(&old_plane_state->vma);
13402         if (vma)
13403                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13404 }
13405
13406 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13407 {
13408         struct i915_sched_attr attr = {
13409                 .priority = I915_PRIORITY_DISPLAY,
13410         };
13411
13412         i915_gem_object_wait_priority(obj, 0, &attr);
13413 }
13414
13415 /**
13416  * intel_prepare_plane_fb - Prepare fb for usage on plane
13417  * @plane: drm plane to prepare for
13418  * @new_state: the plane state being prepared
13419  *
13420  * Prepares a framebuffer for usage on a display plane.  Generally this
13421  * involves pinning the underlying object and updating the frontbuffer tracking
13422  * bits.  Some older platforms need special physical address handling for
13423  * cursor planes.
13424  *
13425  * Must be called with struct_mutex held.
13426  *
13427  * Returns 0 on success, negative error code on failure.
13428  */
13429 int
13430 intel_prepare_plane_fb(struct drm_plane *plane,
13431                        struct drm_plane_state *new_state)
13432 {
13433         struct intel_atomic_state *intel_state =
13434                 to_intel_atomic_state(new_state->state);
13435         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13436         struct drm_framebuffer *fb = new_state->fb;
13437         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13438         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13439         int ret;
13440
13441         if (old_obj) {
13442                 struct drm_crtc_state *crtc_state =
13443                         drm_atomic_get_new_crtc_state(new_state->state,
13444                                                       plane->state->crtc);
13445
13446                 /* Big Hammer, we also need to ensure that any pending
13447                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13448                  * current scanout is retired before unpinning the old
13449                  * framebuffer. Note that we rely on userspace rendering
13450                  * into the buffer attached to the pipe they are waiting
13451                  * on. If not, userspace generates a GPU hang with IPEHR
13452                  * point to the MI_WAIT_FOR_EVENT.
13453                  *
13454                  * This should only fail upon a hung GPU, in which case we
13455                  * can safely continue.
13456                  */
13457                 if (needs_modeset(crtc_state)) {
13458                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13459                                                               old_obj->resv, NULL,
13460                                                               false, 0,
13461                                                               GFP_KERNEL);
13462                         if (ret < 0)
13463                                 return ret;
13464                 }
13465         }
13466
13467         if (new_state->fence) { /* explicit fencing */
13468                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13469                                                     new_state->fence,
13470                                                     I915_FENCE_TIMEOUT,
13471                                                     GFP_KERNEL);
13472                 if (ret < 0)
13473                         return ret;
13474         }
13475
13476         if (!obj)
13477                 return 0;
13478
13479         ret = i915_gem_object_pin_pages(obj);
13480         if (ret)
13481                 return ret;
13482
13483         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13484         if (ret) {
13485                 i915_gem_object_unpin_pages(obj);
13486                 return ret;
13487         }
13488
13489         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13490
13491         mutex_unlock(&dev_priv->drm.struct_mutex);
13492         i915_gem_object_unpin_pages(obj);
13493         if (ret)
13494                 return ret;
13495
13496         fb_obj_bump_render_priority(obj);
13497         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13498
13499         if (!new_state->fence) { /* implicit fencing */
13500                 struct dma_fence *fence;
13501
13502                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13503                                                       obj->resv, NULL,
13504                                                       false, I915_FENCE_TIMEOUT,
13505                                                       GFP_KERNEL);
13506                 if (ret < 0)
13507                         return ret;
13508
13509                 fence = reservation_object_get_excl_rcu(obj->resv);
13510                 if (fence) {
13511                         add_rps_boost_after_vblank(new_state->crtc, fence);
13512                         dma_fence_put(fence);
13513                 }
13514         } else {
13515                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13516         }
13517
13518         /*
13519          * We declare pageflips to be interactive and so merit a small bias
13520          * towards upclocking to deliver the frame on time. By only changing
13521          * the RPS thresholds to sample more regularly and aim for higher
13522          * clocks we can hopefully deliver low power workloads (like kodi)
13523          * that are not quite steady state without resorting to forcing
13524          * maximum clocks following a vblank miss (see do_rps_boost()).
13525          */
13526         if (!intel_state->rps_interactive) {
13527                 intel_rps_mark_interactive(dev_priv, true);
13528                 intel_state->rps_interactive = true;
13529         }
13530
13531         return 0;
13532 }
13533
13534 /**
13535  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13536  * @plane: drm plane to clean up for
13537  * @old_state: the state from the previous modeset
13538  *
13539  * Cleans up a framebuffer that has just been removed from a plane.
13540  *
13541  * Must be called with struct_mutex held.
13542  */
13543 void
13544 intel_cleanup_plane_fb(struct drm_plane *plane,
13545                        struct drm_plane_state *old_state)
13546 {
13547         struct intel_atomic_state *intel_state =
13548                 to_intel_atomic_state(old_state->state);
13549         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13550
13551         if (intel_state->rps_interactive) {
13552                 intel_rps_mark_interactive(dev_priv, false);
13553                 intel_state->rps_interactive = false;
13554         }
13555
13556         /* Should only be called after a successful intel_prepare_plane_fb()! */
13557         mutex_lock(&dev_priv->drm.struct_mutex);
13558         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13559         mutex_unlock(&dev_priv->drm.struct_mutex);
13560 }
13561
13562 int
13563 skl_max_scale(const struct intel_crtc_state *crtc_state,
13564               u32 pixel_format)
13565 {
13566         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13567         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13568         int max_scale, mult;
13569         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13570
13571         if (!crtc_state->base.enable)
13572                 return DRM_PLANE_HELPER_NO_SCALING;
13573
13574         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13575         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13576
13577         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13578                 max_dotclk *= 2;
13579
13580         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13581                 return DRM_PLANE_HELPER_NO_SCALING;
13582
13583         /*
13584          * skl max scale is lower of:
13585          *    close to 3 but not 3, -1 is for that purpose
13586          *            or
13587          *    cdclk/crtc_clock
13588          */
13589         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13590         tmpclk1 = (1 << 16) * mult - 1;
13591         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13592         max_scale = min(tmpclk1, tmpclk2);
13593
13594         return max_scale;
13595 }
13596
13597 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13598                                     struct drm_crtc_state *old_crtc_state)
13599 {
13600         struct drm_device *dev = crtc->dev;
13601         struct drm_i915_private *dev_priv = to_i915(dev);
13602         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13603         struct intel_crtc_state *old_intel_cstate =
13604                 to_intel_crtc_state(old_crtc_state);
13605         struct intel_atomic_state *old_intel_state =
13606                 to_intel_atomic_state(old_crtc_state->state);
13607         struct intel_crtc_state *intel_cstate =
13608                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13609         bool modeset = needs_modeset(&intel_cstate->base);
13610
13611         if (!modeset &&
13612             (intel_cstate->base.color_mgmt_changed ||
13613              intel_cstate->update_pipe)) {
13614                 intel_color_set_csc(intel_cstate);
13615                 intel_color_load_luts(intel_cstate);
13616         }
13617
13618         /* Perform vblank evasion around commit operation */
13619         intel_pipe_update_start(intel_cstate);
13620
13621         if (modeset)
13622                 goto out;
13623
13624         if (intel_cstate->update_pipe)
13625                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13626         else if (INTEL_GEN(dev_priv) >= 9)
13627                 skl_detach_scalers(intel_cstate);
13628
13629 out:
13630         if (dev_priv->display.atomic_update_watermarks)
13631                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13632                                                            intel_cstate);
13633 }
13634
13635 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13636                                   struct intel_crtc_state *crtc_state)
13637 {
13638         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13639
13640         if (!IS_GEN(dev_priv, 2))
13641                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13642
13643         if (crtc_state->has_pch_encoder) {
13644                 enum pipe pch_transcoder =
13645                         intel_crtc_pch_transcoder(crtc);
13646
13647                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13648         }
13649 }
13650
13651 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13652                                      struct drm_crtc_state *old_crtc_state)
13653 {
13654         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13655         struct intel_atomic_state *old_intel_state =
13656                 to_intel_atomic_state(old_crtc_state->state);
13657         struct intel_crtc_state *new_crtc_state =
13658                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13659
13660         intel_pipe_update_end(new_crtc_state);
13661
13662         if (new_crtc_state->update_pipe &&
13663             !needs_modeset(&new_crtc_state->base) &&
13664             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13665                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13666 }
13667
13668 /**
13669  * intel_plane_destroy - destroy a plane
13670  * @plane: plane to destroy
13671  *
13672  * Common destruction function for all types of planes (primary, cursor,
13673  * sprite).
13674  */
13675 void intel_plane_destroy(struct drm_plane *plane)
13676 {
13677         drm_plane_cleanup(plane);
13678         kfree(to_intel_plane(plane));
13679 }
13680
13681 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13682                                             u32 format, u64 modifier)
13683 {
13684         switch (modifier) {
13685         case DRM_FORMAT_MOD_LINEAR:
13686         case I915_FORMAT_MOD_X_TILED:
13687                 break;
13688         default:
13689                 return false;
13690         }
13691
13692         switch (format) {
13693         case DRM_FORMAT_C8:
13694         case DRM_FORMAT_RGB565:
13695         case DRM_FORMAT_XRGB1555:
13696         case DRM_FORMAT_XRGB8888:
13697                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13698                         modifier == I915_FORMAT_MOD_X_TILED;
13699         default:
13700                 return false;
13701         }
13702 }
13703
13704 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13705                                             u32 format, u64 modifier)
13706 {
13707         switch (modifier) {
13708         case DRM_FORMAT_MOD_LINEAR:
13709         case I915_FORMAT_MOD_X_TILED:
13710                 break;
13711         default:
13712                 return false;
13713         }
13714
13715         switch (format) {
13716         case DRM_FORMAT_C8:
13717         case DRM_FORMAT_RGB565:
13718         case DRM_FORMAT_XRGB8888:
13719         case DRM_FORMAT_XBGR8888:
13720         case DRM_FORMAT_XRGB2101010:
13721         case DRM_FORMAT_XBGR2101010:
13722                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13723                         modifier == I915_FORMAT_MOD_X_TILED;
13724         default:
13725                 return false;
13726         }
13727 }
13728
13729 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13730                                               u32 format, u64 modifier)
13731 {
13732         return modifier == DRM_FORMAT_MOD_LINEAR &&
13733                 format == DRM_FORMAT_ARGB8888;
13734 }
13735
13736 static const struct drm_plane_funcs i965_plane_funcs = {
13737         .update_plane = drm_atomic_helper_update_plane,
13738         .disable_plane = drm_atomic_helper_disable_plane,
13739         .destroy = intel_plane_destroy,
13740         .atomic_get_property = intel_plane_atomic_get_property,
13741         .atomic_set_property = intel_plane_atomic_set_property,
13742         .atomic_duplicate_state = intel_plane_duplicate_state,
13743         .atomic_destroy_state = intel_plane_destroy_state,
13744         .format_mod_supported = i965_plane_format_mod_supported,
13745 };
13746
13747 static const struct drm_plane_funcs i8xx_plane_funcs = {
13748         .update_plane = drm_atomic_helper_update_plane,
13749         .disable_plane = drm_atomic_helper_disable_plane,
13750         .destroy = intel_plane_destroy,
13751         .atomic_get_property = intel_plane_atomic_get_property,
13752         .atomic_set_property = intel_plane_atomic_set_property,
13753         .atomic_duplicate_state = intel_plane_duplicate_state,
13754         .atomic_destroy_state = intel_plane_destroy_state,
13755         .format_mod_supported = i8xx_plane_format_mod_supported,
13756 };
13757
13758 static int
13759 intel_legacy_cursor_update(struct drm_plane *plane,
13760                            struct drm_crtc *crtc,
13761                            struct drm_framebuffer *fb,
13762                            int crtc_x, int crtc_y,
13763                            unsigned int crtc_w, unsigned int crtc_h,
13764                            u32 src_x, u32 src_y,
13765                            u32 src_w, u32 src_h,
13766                            struct drm_modeset_acquire_ctx *ctx)
13767 {
13768         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13769         int ret;
13770         struct drm_plane_state *old_plane_state, *new_plane_state;
13771         struct intel_plane *intel_plane = to_intel_plane(plane);
13772         struct drm_framebuffer *old_fb;
13773         struct intel_crtc_state *crtc_state =
13774                 to_intel_crtc_state(crtc->state);
13775         struct intel_crtc_state *new_crtc_state;
13776
13777         /*
13778          * When crtc is inactive or there is a modeset pending,
13779          * wait for it to complete in the slowpath
13780          */
13781         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
13782             crtc_state->update_pipe)
13783                 goto slow;
13784
13785         old_plane_state = plane->state;
13786         /*
13787          * Don't do an async update if there is an outstanding commit modifying
13788          * the plane.  This prevents our async update's changes from getting
13789          * overridden by a previous synchronous update's state.
13790          */
13791         if (old_plane_state->commit &&
13792             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13793                 goto slow;
13794
13795         /*
13796          * If any parameters change that may affect watermarks,
13797          * take the slowpath. Only changing fb or position should be
13798          * in the fastpath.
13799          */
13800         if (old_plane_state->crtc != crtc ||
13801             old_plane_state->src_w != src_w ||
13802             old_plane_state->src_h != src_h ||
13803             old_plane_state->crtc_w != crtc_w ||
13804             old_plane_state->crtc_h != crtc_h ||
13805             !old_plane_state->fb != !fb)
13806                 goto slow;
13807
13808         new_plane_state = intel_plane_duplicate_state(plane);
13809         if (!new_plane_state)
13810                 return -ENOMEM;
13811
13812         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
13813         if (!new_crtc_state) {
13814                 ret = -ENOMEM;
13815                 goto out_free;
13816         }
13817
13818         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13819
13820         new_plane_state->src_x = src_x;
13821         new_plane_state->src_y = src_y;
13822         new_plane_state->src_w = src_w;
13823         new_plane_state->src_h = src_h;
13824         new_plane_state->crtc_x = crtc_x;
13825         new_plane_state->crtc_y = crtc_y;
13826         new_plane_state->crtc_w = crtc_w;
13827         new_plane_state->crtc_h = crtc_h;
13828
13829         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
13830                                                   to_intel_plane_state(old_plane_state),
13831                                                   to_intel_plane_state(new_plane_state));
13832         if (ret)
13833                 goto out_free;
13834
13835         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13836         if (ret)
13837                 goto out_free;
13838
13839         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13840         if (ret)
13841                 goto out_unlock;
13842
13843         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13844
13845         old_fb = old_plane_state->fb;
13846         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13847                           intel_plane->frontbuffer_bit);
13848
13849         /* Swap plane state */
13850         plane->state = new_plane_state;
13851
13852         /*
13853          * We cannot swap crtc_state as it may be in use by an atomic commit or
13854          * page flip that's running simultaneously. If we swap crtc_state and
13855          * destroy the old state, we will cause a use-after-free there.
13856          *
13857          * Only update active_planes, which is needed for our internal
13858          * bookkeeping. Either value will do the right thing when updating
13859          * planes atomically. If the cursor was part of the atomic update then
13860          * we would have taken the slowpath.
13861          */
13862         crtc_state->active_planes = new_crtc_state->active_planes;
13863
13864         if (plane->state->visible) {
13865                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13866                 intel_plane->update_plane(intel_plane, crtc_state,
13867                                           to_intel_plane_state(plane->state));
13868         } else {
13869                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13870                 intel_plane->disable_plane(intel_plane, crtc_state);
13871         }
13872
13873         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13874
13875 out_unlock:
13876         mutex_unlock(&dev_priv->drm.struct_mutex);
13877 out_free:
13878         if (new_crtc_state)
13879                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
13880         if (ret)
13881                 intel_plane_destroy_state(plane, new_plane_state);
13882         else
13883                 intel_plane_destroy_state(plane, old_plane_state);
13884         return ret;
13885
13886 slow:
13887         return drm_atomic_helper_update_plane(plane, crtc, fb,
13888                                               crtc_x, crtc_y, crtc_w, crtc_h,
13889                                               src_x, src_y, src_w, src_h, ctx);
13890 }
13891
13892 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13893         .update_plane = intel_legacy_cursor_update,
13894         .disable_plane = drm_atomic_helper_disable_plane,
13895         .destroy = intel_plane_destroy,
13896         .atomic_get_property = intel_plane_atomic_get_property,
13897         .atomic_set_property = intel_plane_atomic_set_property,
13898         .atomic_duplicate_state = intel_plane_duplicate_state,
13899         .atomic_destroy_state = intel_plane_destroy_state,
13900         .format_mod_supported = intel_cursor_format_mod_supported,
13901 };
13902
13903 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13904                                enum i9xx_plane_id i9xx_plane)
13905 {
13906         if (!HAS_FBC(dev_priv))
13907                 return false;
13908
13909         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13910                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13911         else if (IS_IVYBRIDGE(dev_priv))
13912                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13913                         i9xx_plane == PLANE_C;
13914         else if (INTEL_GEN(dev_priv) >= 4)
13915                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13916         else
13917                 return i9xx_plane == PLANE_A;
13918 }
13919
13920 static struct intel_plane *
13921 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13922 {
13923         struct intel_plane *plane;
13924         const struct drm_plane_funcs *plane_funcs;
13925         unsigned int supported_rotations;
13926         unsigned int possible_crtcs;
13927         const u64 *modifiers;
13928         const u32 *formats;
13929         int num_formats;
13930         int ret;
13931
13932         if (INTEL_GEN(dev_priv) >= 9)
13933                 return skl_universal_plane_create(dev_priv, pipe,
13934                                                   PLANE_PRIMARY);
13935
13936         plane = intel_plane_alloc();
13937         if (IS_ERR(plane))
13938                 return plane;
13939
13940         plane->pipe = pipe;
13941         /*
13942          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13943          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13944          */
13945         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13946                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
13947         else
13948                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
13949         plane->id = PLANE_PRIMARY;
13950         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
13951
13952         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
13953         if (plane->has_fbc) {
13954                 struct intel_fbc *fbc = &dev_priv->fbc;
13955
13956                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
13957         }
13958
13959         if (INTEL_GEN(dev_priv) >= 4) {
13960                 formats = i965_primary_formats;
13961                 num_formats = ARRAY_SIZE(i965_primary_formats);
13962                 modifiers = i9xx_format_modifiers;
13963
13964                 plane->max_stride = i9xx_plane_max_stride;
13965                 plane->update_plane = i9xx_update_plane;
13966                 plane->disable_plane = i9xx_disable_plane;
13967                 plane->get_hw_state = i9xx_plane_get_hw_state;
13968                 plane->check_plane = i9xx_plane_check;
13969
13970                 plane_funcs = &i965_plane_funcs;
13971         } else {
13972                 formats = i8xx_primary_formats;
13973                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13974                 modifiers = i9xx_format_modifiers;
13975
13976                 plane->max_stride = i9xx_plane_max_stride;
13977                 plane->update_plane = i9xx_update_plane;
13978                 plane->disable_plane = i9xx_disable_plane;
13979                 plane->get_hw_state = i9xx_plane_get_hw_state;
13980                 plane->check_plane = i9xx_plane_check;
13981
13982                 plane_funcs = &i8xx_plane_funcs;
13983         }
13984
13985         possible_crtcs = BIT(pipe);
13986
13987         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13988                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13989                                                possible_crtcs, plane_funcs,
13990                                                formats, num_formats, modifiers,
13991                                                DRM_PLANE_TYPE_PRIMARY,
13992                                                "primary %c", pipe_name(pipe));
13993         else
13994                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13995                                                possible_crtcs, plane_funcs,
13996                                                formats, num_formats, modifiers,
13997                                                DRM_PLANE_TYPE_PRIMARY,
13998                                                "plane %c",
13999                                                plane_name(plane->i9xx_plane));
14000         if (ret)
14001                 goto fail;
14002
14003         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
14004                 supported_rotations =
14005                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
14006                         DRM_MODE_REFLECT_X;
14007         } else if (INTEL_GEN(dev_priv) >= 4) {
14008                 supported_rotations =
14009                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
14010         } else {
14011                 supported_rotations = DRM_MODE_ROTATE_0;
14012         }
14013
14014         if (INTEL_GEN(dev_priv) >= 4)
14015                 drm_plane_create_rotation_property(&plane->base,
14016                                                    DRM_MODE_ROTATE_0,
14017                                                    supported_rotations);
14018
14019         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
14020
14021         return plane;
14022
14023 fail:
14024         intel_plane_free(plane);
14025
14026         return ERR_PTR(ret);
14027 }
14028
14029 static struct intel_plane *
14030 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
14031                           enum pipe pipe)
14032 {
14033         unsigned int possible_crtcs;
14034         struct intel_plane *cursor;
14035         int ret;
14036
14037         cursor = intel_plane_alloc();
14038         if (IS_ERR(cursor))
14039                 return cursor;
14040
14041         cursor->pipe = pipe;
14042         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
14043         cursor->id = PLANE_CURSOR;
14044         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
14045
14046         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14047                 cursor->max_stride = i845_cursor_max_stride;
14048                 cursor->update_plane = i845_update_cursor;
14049                 cursor->disable_plane = i845_disable_cursor;
14050                 cursor->get_hw_state = i845_cursor_get_hw_state;
14051                 cursor->check_plane = i845_check_cursor;
14052         } else {
14053                 cursor->max_stride = i9xx_cursor_max_stride;
14054                 cursor->update_plane = i9xx_update_cursor;
14055                 cursor->disable_plane = i9xx_disable_cursor;
14056                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
14057                 cursor->check_plane = i9xx_check_cursor;
14058         }
14059
14060         cursor->cursor.base = ~0;
14061         cursor->cursor.cntl = ~0;
14062
14063         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
14064                 cursor->cursor.size = ~0;
14065
14066         possible_crtcs = BIT(pipe);
14067
14068         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
14069                                        possible_crtcs, &intel_cursor_plane_funcs,
14070                                        intel_cursor_formats,
14071                                        ARRAY_SIZE(intel_cursor_formats),
14072                                        cursor_format_modifiers,
14073                                        DRM_PLANE_TYPE_CURSOR,
14074                                        "cursor %c", pipe_name(pipe));
14075         if (ret)
14076                 goto fail;
14077
14078         if (INTEL_GEN(dev_priv) >= 4)
14079                 drm_plane_create_rotation_property(&cursor->base,
14080                                                    DRM_MODE_ROTATE_0,
14081                                                    DRM_MODE_ROTATE_0 |
14082                                                    DRM_MODE_ROTATE_180);
14083
14084         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14085
14086         return cursor;
14087
14088 fail:
14089         intel_plane_free(cursor);
14090
14091         return ERR_PTR(ret);
14092 }
14093
14094 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
14095                                     struct intel_crtc_state *crtc_state)
14096 {
14097         struct intel_crtc_scaler_state *scaler_state =
14098                 &crtc_state->scaler_state;
14099         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14100         int i;
14101
14102         crtc->num_scalers = RUNTIME_INFO(dev_priv)->num_scalers[crtc->pipe];
14103         if (!crtc->num_scalers)
14104                 return;
14105
14106         for (i = 0; i < crtc->num_scalers; i++) {
14107                 struct intel_scaler *scaler = &scaler_state->scalers[i];
14108
14109                 scaler->in_use = 0;
14110                 scaler->mode = 0;
14111         }
14112
14113         scaler_state->scaler_id = -1;
14114 }
14115
14116 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
14117 {
14118         struct intel_crtc *intel_crtc;
14119         struct intel_crtc_state *crtc_state = NULL;
14120         struct intel_plane *primary = NULL;
14121         struct intel_plane *cursor = NULL;
14122         int sprite, ret;
14123
14124         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14125         if (!intel_crtc)
14126                 return -ENOMEM;
14127
14128         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14129         if (!crtc_state) {
14130                 ret = -ENOMEM;
14131                 goto fail;
14132         }
14133         intel_crtc->config = crtc_state;
14134         intel_crtc->base.state = &crtc_state->base;
14135         crtc_state->base.crtc = &intel_crtc->base;
14136
14137         primary = intel_primary_plane_create(dev_priv, pipe);
14138         if (IS_ERR(primary)) {
14139                 ret = PTR_ERR(primary);
14140                 goto fail;
14141         }
14142         intel_crtc->plane_ids_mask |= BIT(primary->id);
14143
14144         for_each_sprite(dev_priv, pipe, sprite) {
14145                 struct intel_plane *plane;
14146
14147                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
14148                 if (IS_ERR(plane)) {
14149                         ret = PTR_ERR(plane);
14150                         goto fail;
14151                 }
14152                 intel_crtc->plane_ids_mask |= BIT(plane->id);
14153         }
14154
14155         cursor = intel_cursor_plane_create(dev_priv, pipe);
14156         if (IS_ERR(cursor)) {
14157                 ret = PTR_ERR(cursor);
14158                 goto fail;
14159         }
14160         intel_crtc->plane_ids_mask |= BIT(cursor->id);
14161
14162         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
14163                                         &primary->base, &cursor->base,
14164                                         &intel_crtc_funcs,
14165                                         "pipe %c", pipe_name(pipe));
14166         if (ret)
14167                 goto fail;
14168
14169         intel_crtc->pipe = pipe;
14170
14171         /* initialize shared scalers */
14172         intel_crtc_init_scalers(intel_crtc, crtc_state);
14173
14174         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14175                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14176         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14177
14178         if (INTEL_GEN(dev_priv) < 9) {
14179                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14180
14181                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14182                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14183                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14184         }
14185
14186         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14187
14188         intel_color_init(intel_crtc);
14189
14190         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14191
14192         return 0;
14193
14194 fail:
14195         /*
14196          * drm_mode_config_cleanup() will free up any
14197          * crtcs/planes already initialized.
14198          */
14199         kfree(crtc_state);
14200         kfree(intel_crtc);
14201
14202         return ret;
14203 }
14204
14205 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14206                                       struct drm_file *file)
14207 {
14208         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14209         struct drm_crtc *drmmode_crtc;
14210         struct intel_crtc *crtc;
14211
14212         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14213         if (!drmmode_crtc)
14214                 return -ENOENT;
14215
14216         crtc = to_intel_crtc(drmmode_crtc);
14217         pipe_from_crtc_id->pipe = crtc->pipe;
14218
14219         return 0;
14220 }
14221
14222 static int intel_encoder_clones(struct intel_encoder *encoder)
14223 {
14224         struct drm_device *dev = encoder->base.dev;
14225         struct intel_encoder *source_encoder;
14226         int index_mask = 0;
14227         int entry = 0;
14228
14229         for_each_intel_encoder(dev, source_encoder) {
14230                 if (encoders_cloneable(encoder, source_encoder))
14231                         index_mask |= (1 << entry);
14232
14233                 entry++;
14234         }
14235
14236         return index_mask;
14237 }
14238
14239 static bool ilk_has_edp_a(struct drm_i915_private *dev_priv)
14240 {
14241         if (!IS_MOBILE(dev_priv))
14242                 return false;
14243
14244         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14245                 return false;
14246
14247         if (IS_GEN(dev_priv, 5) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14248                 return false;
14249
14250         return true;
14251 }
14252
14253 static bool intel_ddi_crt_present(struct drm_i915_private *dev_priv)
14254 {
14255         if (INTEL_GEN(dev_priv) >= 9)
14256                 return false;
14257
14258         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14259                 return false;
14260
14261         if (HAS_PCH_LPT_H(dev_priv) &&
14262             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14263                 return false;
14264
14265         /* DDI E can't be used if DDI A requires 4 lanes */
14266         if (I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14267                 return false;
14268
14269         if (!dev_priv->vbt.int_crt_support)
14270                 return false;
14271
14272         return true;
14273 }
14274
14275 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14276 {
14277         int pps_num;
14278         int pps_idx;
14279
14280         if (HAS_DDI(dev_priv))
14281                 return;
14282         /*
14283          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14284          * everywhere where registers can be write protected.
14285          */
14286         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14287                 pps_num = 2;
14288         else
14289                 pps_num = 1;
14290
14291         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14292                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14293
14294                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14295                 I915_WRITE(PP_CONTROL(pps_idx), val);
14296         }
14297 }
14298
14299 static void intel_pps_init(struct drm_i915_private *dev_priv)
14300 {
14301         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14302                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14303         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14304                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14305         else
14306                 dev_priv->pps_mmio_base = PPS_BASE;
14307
14308         intel_pps_unlock_regs_wa(dev_priv);
14309 }
14310
14311 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14312 {
14313         struct intel_encoder *encoder;
14314         bool dpd_is_edp = false;
14315
14316         intel_pps_init(dev_priv);
14317
14318         if (!HAS_DISPLAY(dev_priv))
14319                 return;
14320
14321         if (IS_ICELAKE(dev_priv)) {
14322                 intel_ddi_init(dev_priv, PORT_A);
14323                 intel_ddi_init(dev_priv, PORT_B);
14324                 intel_ddi_init(dev_priv, PORT_C);
14325                 intel_ddi_init(dev_priv, PORT_D);
14326                 intel_ddi_init(dev_priv, PORT_E);
14327                 /*
14328                  * On some ICL SKUs port F is not present. No strap bits for
14329                  * this, so rely on VBT.
14330                  */
14331                 if (intel_bios_is_port_present(dev_priv, PORT_F))
14332                         intel_ddi_init(dev_priv, PORT_F);
14333
14334                 icl_dsi_init(dev_priv);
14335         } else if (IS_GEN9_LP(dev_priv)) {
14336                 /*
14337                  * FIXME: Broxton doesn't support port detection via the
14338                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14339                  * detect the ports.
14340                  */
14341                 intel_ddi_init(dev_priv, PORT_A);
14342                 intel_ddi_init(dev_priv, PORT_B);
14343                 intel_ddi_init(dev_priv, PORT_C);
14344
14345                 vlv_dsi_init(dev_priv);
14346         } else if (HAS_DDI(dev_priv)) {
14347                 int found;
14348
14349                 if (intel_ddi_crt_present(dev_priv))
14350                         intel_crt_init(dev_priv);
14351
14352                 /*
14353                  * Haswell uses DDI functions to detect digital outputs.
14354                  * On SKL pre-D0 the strap isn't connected, so we assume
14355                  * it's there.
14356                  */
14357                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14358                 /* WaIgnoreDDIAStrap: skl */
14359                 if (found || IS_GEN9_BC(dev_priv))
14360                         intel_ddi_init(dev_priv, PORT_A);
14361
14362                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14363                  * register */
14364                 found = I915_READ(SFUSE_STRAP);
14365
14366                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14367                         intel_ddi_init(dev_priv, PORT_B);
14368                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14369                         intel_ddi_init(dev_priv, PORT_C);
14370                 if (found & SFUSE_STRAP_DDID_DETECTED)
14371                         intel_ddi_init(dev_priv, PORT_D);
14372                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14373                         intel_ddi_init(dev_priv, PORT_F);
14374                 /*
14375                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14376                  */
14377                 if (IS_GEN9_BC(dev_priv) &&
14378                     intel_bios_is_port_present(dev_priv, PORT_E))
14379                         intel_ddi_init(dev_priv, PORT_E);
14380
14381         } else if (HAS_PCH_SPLIT(dev_priv)) {
14382                 int found;
14383
14384                 /*
14385                  * intel_edp_init_connector() depends on this completing first,
14386                  * to prevent the registration of both eDP and LVDS and the
14387                  * incorrect sharing of the PPS.
14388                  */
14389                 intel_lvds_init(dev_priv);
14390                 intel_crt_init(dev_priv);
14391
14392                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14393
14394                 if (ilk_has_edp_a(dev_priv))
14395                         intel_dp_init(dev_priv, DP_A, PORT_A);
14396
14397                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14398                         /* PCH SDVOB multiplex with HDMIB */
14399                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14400                         if (!found)
14401                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14402                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14403                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14404                 }
14405
14406                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14407                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14408
14409                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14410                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14411
14412                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14413                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14414
14415                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14416                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14417         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14418                 bool has_edp, has_port;
14419
14420                 if (IS_VALLEYVIEW(dev_priv) && dev_priv->vbt.int_crt_support)
14421                         intel_crt_init(dev_priv);
14422
14423                 /*
14424                  * The DP_DETECTED bit is the latched state of the DDC
14425                  * SDA pin at boot. However since eDP doesn't require DDC
14426                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14427                  * eDP ports may have been muxed to an alternate function.
14428                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14429                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14430                  * detect eDP ports.
14431                  *
14432                  * Sadly the straps seem to be missing sometimes even for HDMI
14433                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14434                  * and VBT for the presence of the port. Additionally we can't
14435                  * trust the port type the VBT declares as we've seen at least
14436                  * HDMI ports that the VBT claim are DP or eDP.
14437                  */
14438                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14439                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14440                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14441                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14442                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14443                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14444
14445                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14446                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14447                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14448                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14449                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14450                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14451
14452                 if (IS_CHERRYVIEW(dev_priv)) {
14453                         /*
14454                          * eDP not supported on port D,
14455                          * so no need to worry about it
14456                          */
14457                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14458                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14459                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14460                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14461                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14462                 }
14463
14464                 vlv_dsi_init(dev_priv);
14465         } else if (IS_PINEVIEW(dev_priv)) {
14466                 intel_lvds_init(dev_priv);
14467                 intel_crt_init(dev_priv);
14468         } else if (IS_GEN_RANGE(dev_priv, 3, 4)) {
14469                 bool found = false;
14470
14471                 if (IS_MOBILE(dev_priv))
14472                         intel_lvds_init(dev_priv);
14473
14474                 intel_crt_init(dev_priv);
14475
14476                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14477                         DRM_DEBUG_KMS("probing SDVOB\n");
14478                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14479                         if (!found && IS_G4X(dev_priv)) {
14480                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14481                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14482                         }
14483
14484                         if (!found && IS_G4X(dev_priv))
14485                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14486                 }
14487
14488                 /* Before G4X SDVOC doesn't have its own detect register */
14489
14490                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14491                         DRM_DEBUG_KMS("probing SDVOC\n");
14492                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14493                 }
14494
14495                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14496
14497                         if (IS_G4X(dev_priv)) {
14498                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14499                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14500                         }
14501                         if (IS_G4X(dev_priv))
14502                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14503                 }
14504
14505                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14506                         intel_dp_init(dev_priv, DP_D, PORT_D);
14507
14508                 if (SUPPORTS_TV(dev_priv))
14509                         intel_tv_init(dev_priv);
14510         } else if (IS_GEN(dev_priv, 2)) {
14511                 if (IS_I85X(dev_priv))
14512                         intel_lvds_init(dev_priv);
14513
14514                 intel_crt_init(dev_priv);
14515                 intel_dvo_init(dev_priv);
14516         }
14517
14518         intel_psr_init(dev_priv);
14519
14520         for_each_intel_encoder(&dev_priv->drm, encoder) {
14521                 encoder->base.possible_crtcs = encoder->crtc_mask;
14522                 encoder->base.possible_clones =
14523                         intel_encoder_clones(encoder);
14524         }
14525
14526         intel_init_pch_refclk(dev_priv);
14527
14528         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14529 }
14530
14531 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14532 {
14533         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14534         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14535
14536         drm_framebuffer_cleanup(fb);
14537
14538         i915_gem_object_lock(obj);
14539         WARN_ON(!obj->framebuffer_references--);
14540         i915_gem_object_unlock(obj);
14541
14542         i915_gem_object_put(obj);
14543
14544         kfree(intel_fb);
14545 }
14546
14547 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14548                                                 struct drm_file *file,
14549                                                 unsigned int *handle)
14550 {
14551         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14552
14553         if (obj->userptr.mm) {
14554                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14555                 return -EINVAL;
14556         }
14557
14558         return drm_gem_handle_create(file, &obj->base, handle);
14559 }
14560
14561 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14562                                         struct drm_file *file,
14563                                         unsigned flags, unsigned color,
14564                                         struct drm_clip_rect *clips,
14565                                         unsigned num_clips)
14566 {
14567         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14568
14569         i915_gem_object_flush_if_display(obj);
14570         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14571
14572         return 0;
14573 }
14574
14575 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14576         .destroy = intel_user_framebuffer_destroy,
14577         .create_handle = intel_user_framebuffer_create_handle,
14578         .dirty = intel_user_framebuffer_dirty,
14579 };
14580
14581 static
14582 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14583                          u32 pixel_format, u64 fb_modifier)
14584 {
14585         struct intel_crtc *crtc;
14586         struct intel_plane *plane;
14587
14588         /*
14589          * We assume the primary plane for pipe A has
14590          * the highest stride limits of them all.
14591          */
14592         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14593         plane = to_intel_plane(crtc->base.primary);
14594
14595         return plane->max_stride(plane, pixel_format, fb_modifier,
14596                                  DRM_MODE_ROTATE_0);
14597 }
14598
14599 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14600                                   struct drm_i915_gem_object *obj,
14601                                   struct drm_mode_fb_cmd2 *mode_cmd)
14602 {
14603         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14604         struct drm_framebuffer *fb = &intel_fb->base;
14605         u32 pitch_limit;
14606         unsigned int tiling, stride;
14607         int ret = -EINVAL;
14608         int i;
14609
14610         i915_gem_object_lock(obj);
14611         obj->framebuffer_references++;
14612         tiling = i915_gem_object_get_tiling(obj);
14613         stride = i915_gem_object_get_stride(obj);
14614         i915_gem_object_unlock(obj);
14615
14616         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14617                 /*
14618                  * If there's a fence, enforce that
14619                  * the fb modifier and tiling mode match.
14620                  */
14621                 if (tiling != I915_TILING_NONE &&
14622                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14623                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14624                         goto err;
14625                 }
14626         } else {
14627                 if (tiling == I915_TILING_X) {
14628                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14629                 } else if (tiling == I915_TILING_Y) {
14630                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14631                         goto err;
14632                 }
14633         }
14634
14635         if (!drm_any_plane_has_format(&dev_priv->drm,
14636                                       mode_cmd->pixel_format,
14637                                       mode_cmd->modifier[0])) {
14638                 struct drm_format_name_buf format_name;
14639
14640                 DRM_DEBUG_KMS("unsupported pixel format %s / modifier 0x%llx\n",
14641                               drm_get_format_name(mode_cmd->pixel_format,
14642                                                   &format_name),
14643                               mode_cmd->modifier[0]);
14644                 goto err;
14645         }
14646
14647         /*
14648          * gen2/3 display engine uses the fence if present,
14649          * so the tiling mode must match the fb modifier exactly.
14650          */
14651         if (INTEL_GEN(dev_priv) < 4 &&
14652             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14653                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14654                 goto err;
14655         }
14656
14657         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->pixel_format,
14658                                            mode_cmd->modifier[0]);
14659         if (mode_cmd->pitches[0] > pitch_limit) {
14660                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14661                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14662                               "tiled" : "linear",
14663                               mode_cmd->pitches[0], pitch_limit);
14664                 goto err;
14665         }
14666
14667         /*
14668          * If there's a fence, enforce that
14669          * the fb pitch and fence stride match.
14670          */
14671         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14672                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14673                               mode_cmd->pitches[0], stride);
14674                 goto err;
14675         }
14676
14677         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14678         if (mode_cmd->offsets[0] != 0)
14679                 goto err;
14680
14681         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14682
14683         if (fb->format->format == DRM_FORMAT_NV12 &&
14684             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14685              fb->height < SKL_MIN_YUV_420_SRC_H ||
14686              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14687                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14688                 goto err;
14689         }
14690
14691         for (i = 0; i < fb->format->num_planes; i++) {
14692                 u32 stride_alignment;
14693
14694                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14695                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14696                         goto err;
14697                 }
14698
14699                 stride_alignment = intel_fb_stride_alignment(fb, i);
14700
14701                 /*
14702                  * Display WA #0531: skl,bxt,kbl,glk
14703                  *
14704                  * Render decompression and plane width > 3840
14705                  * combined with horizontal panning requires the
14706                  * plane stride to be a multiple of 4. We'll just
14707                  * require the entire fb to accommodate that to avoid
14708                  * potential runtime errors at plane configuration time.
14709                  */
14710                 if (IS_GEN(dev_priv, 9) && i == 0 && fb->width > 3840 &&
14711                     is_ccs_modifier(fb->modifier))
14712                         stride_alignment *= 4;
14713
14714                 if (fb->pitches[i] & (stride_alignment - 1)) {
14715                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14716                                       i, fb->pitches[i], stride_alignment);
14717                         goto err;
14718                 }
14719
14720                 fb->obj[i] = &obj->base;
14721         }
14722
14723         ret = intel_fill_fb_info(dev_priv, fb);
14724         if (ret)
14725                 goto err;
14726
14727         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14728         if (ret) {
14729                 DRM_ERROR("framebuffer init failed %d\n", ret);
14730                 goto err;
14731         }
14732
14733         return 0;
14734
14735 err:
14736         i915_gem_object_lock(obj);
14737         obj->framebuffer_references--;
14738         i915_gem_object_unlock(obj);
14739         return ret;
14740 }
14741
14742 static struct drm_framebuffer *
14743 intel_user_framebuffer_create(struct drm_device *dev,
14744                               struct drm_file *filp,
14745                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14746 {
14747         struct drm_framebuffer *fb;
14748         struct drm_i915_gem_object *obj;
14749         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14750
14751         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14752         if (!obj)
14753                 return ERR_PTR(-ENOENT);
14754
14755         fb = intel_framebuffer_create(obj, &mode_cmd);
14756         if (IS_ERR(fb))
14757                 i915_gem_object_put(obj);
14758
14759         return fb;
14760 }
14761
14762 static void intel_atomic_state_free(struct drm_atomic_state *state)
14763 {
14764         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14765
14766         drm_atomic_state_default_release(state);
14767
14768         i915_sw_fence_fini(&intel_state->commit_ready);
14769
14770         kfree(state);
14771 }
14772
14773 static enum drm_mode_status
14774 intel_mode_valid(struct drm_device *dev,
14775                  const struct drm_display_mode *mode)
14776 {
14777         struct drm_i915_private *dev_priv = to_i915(dev);
14778         int hdisplay_max, htotal_max;
14779         int vdisplay_max, vtotal_max;
14780
14781         /*
14782          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14783          * of DBLSCAN modes to the output's mode list when they detect
14784          * the scaling mode property on the connector. And they don't
14785          * ask the kernel to validate those modes in any way until
14786          * modeset time at which point the client gets a protocol error.
14787          * So in order to not upset those clients we silently ignore the
14788          * DBLSCAN flag on such connectors. For other connectors we will
14789          * reject modes with the DBLSCAN flag in encoder->compute_config().
14790          * And we always reject DBLSCAN modes in connector->mode_valid()
14791          * as we never want such modes on the connector's mode list.
14792          */
14793
14794         if (mode->vscan > 1)
14795                 return MODE_NO_VSCAN;
14796
14797         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14798                 return MODE_H_ILLEGAL;
14799
14800         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14801                            DRM_MODE_FLAG_NCSYNC |
14802                            DRM_MODE_FLAG_PCSYNC))
14803                 return MODE_HSYNC;
14804
14805         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14806                            DRM_MODE_FLAG_PIXMUX |
14807                            DRM_MODE_FLAG_CLKDIV2))
14808                 return MODE_BAD;
14809
14810         if (INTEL_GEN(dev_priv) >= 9 ||
14811             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14812                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14813                 vdisplay_max = 4096;
14814                 htotal_max = 8192;
14815                 vtotal_max = 8192;
14816         } else if (INTEL_GEN(dev_priv) >= 3) {
14817                 hdisplay_max = 4096;
14818                 vdisplay_max = 4096;
14819                 htotal_max = 8192;
14820                 vtotal_max = 8192;
14821         } else {
14822                 hdisplay_max = 2048;
14823                 vdisplay_max = 2048;
14824                 htotal_max = 4096;
14825                 vtotal_max = 4096;
14826         }
14827
14828         if (mode->hdisplay > hdisplay_max ||
14829             mode->hsync_start > htotal_max ||
14830             mode->hsync_end > htotal_max ||
14831             mode->htotal > htotal_max)
14832                 return MODE_H_ILLEGAL;
14833
14834         if (mode->vdisplay > vdisplay_max ||
14835             mode->vsync_start > vtotal_max ||
14836             mode->vsync_end > vtotal_max ||
14837             mode->vtotal > vtotal_max)
14838                 return MODE_V_ILLEGAL;
14839
14840         return MODE_OK;
14841 }
14842
14843 static const struct drm_mode_config_funcs intel_mode_funcs = {
14844         .fb_create = intel_user_framebuffer_create,
14845         .get_format_info = intel_get_format_info,
14846         .output_poll_changed = intel_fbdev_output_poll_changed,
14847         .mode_valid = intel_mode_valid,
14848         .atomic_check = intel_atomic_check,
14849         .atomic_commit = intel_atomic_commit,
14850         .atomic_state_alloc = intel_atomic_state_alloc,
14851         .atomic_state_clear = intel_atomic_state_clear,
14852         .atomic_state_free = intel_atomic_state_free,
14853 };
14854
14855 /**
14856  * intel_init_display_hooks - initialize the display modesetting hooks
14857  * @dev_priv: device private
14858  */
14859 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14860 {
14861         intel_init_cdclk_hooks(dev_priv);
14862
14863         if (INTEL_GEN(dev_priv) >= 9) {
14864                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14865                 dev_priv->display.get_initial_plane_config =
14866                         skylake_get_initial_plane_config;
14867                 dev_priv->display.crtc_compute_clock =
14868                         haswell_crtc_compute_clock;
14869                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14870                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14871         } else if (HAS_DDI(dev_priv)) {
14872                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14873                 dev_priv->display.get_initial_plane_config =
14874                         i9xx_get_initial_plane_config;
14875                 dev_priv->display.crtc_compute_clock =
14876                         haswell_crtc_compute_clock;
14877                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14878                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14879         } else if (HAS_PCH_SPLIT(dev_priv)) {
14880                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14881                 dev_priv->display.get_initial_plane_config =
14882                         i9xx_get_initial_plane_config;
14883                 dev_priv->display.crtc_compute_clock =
14884                         ironlake_crtc_compute_clock;
14885                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14886                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14887         } else if (IS_CHERRYVIEW(dev_priv)) {
14888                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14889                 dev_priv->display.get_initial_plane_config =
14890                         i9xx_get_initial_plane_config;
14891                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14892                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14893                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14894         } else if (IS_VALLEYVIEW(dev_priv)) {
14895                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14896                 dev_priv->display.get_initial_plane_config =
14897                         i9xx_get_initial_plane_config;
14898                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14899                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14900                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14901         } else if (IS_G4X(dev_priv)) {
14902                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14903                 dev_priv->display.get_initial_plane_config =
14904                         i9xx_get_initial_plane_config;
14905                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14906                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14907                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14908         } else if (IS_PINEVIEW(dev_priv)) {
14909                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14910                 dev_priv->display.get_initial_plane_config =
14911                         i9xx_get_initial_plane_config;
14912                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14913                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14914                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14915         } else if (!IS_GEN(dev_priv, 2)) {
14916                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14917                 dev_priv->display.get_initial_plane_config =
14918                         i9xx_get_initial_plane_config;
14919                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14920                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14921                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14922         } else {
14923                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14924                 dev_priv->display.get_initial_plane_config =
14925                         i9xx_get_initial_plane_config;
14926                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14927                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14928                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14929         }
14930
14931         if (IS_GEN(dev_priv, 5)) {
14932                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14933         } else if (IS_GEN(dev_priv, 6)) {
14934                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14935         } else if (IS_IVYBRIDGE(dev_priv)) {
14936                 /* FIXME: detect B0+ stepping and use auto training */
14937                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14938         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14939                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14940         }
14941
14942         if (INTEL_GEN(dev_priv) >= 9)
14943                 dev_priv->display.update_crtcs = skl_update_crtcs;
14944         else
14945                 dev_priv->display.update_crtcs = intel_update_crtcs;
14946 }
14947
14948 /* Disable the VGA plane that we never use */
14949 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14950 {
14951         struct pci_dev *pdev = dev_priv->drm.pdev;
14952         u8 sr1;
14953         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14954
14955         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14956         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14957         outb(SR01, VGA_SR_INDEX);
14958         sr1 = inb(VGA_SR_DATA);
14959         outb(sr1 | 1<<5, VGA_SR_DATA);
14960         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14961         udelay(300);
14962
14963         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14964         POSTING_READ(vga_reg);
14965 }
14966
14967 void intel_modeset_init_hw(struct drm_device *dev)
14968 {
14969         struct drm_i915_private *dev_priv = to_i915(dev);
14970
14971         intel_update_cdclk(dev_priv);
14972         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14973         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14974 }
14975
14976 /*
14977  * Calculate what we think the watermarks should be for the state we've read
14978  * out of the hardware and then immediately program those watermarks so that
14979  * we ensure the hardware settings match our internal state.
14980  *
14981  * We can calculate what we think WM's should be by creating a duplicate of the
14982  * current state (which was constructed during hardware readout) and running it
14983  * through the atomic check code to calculate new watermark values in the
14984  * state object.
14985  */
14986 static void sanitize_watermarks(struct drm_device *dev)
14987 {
14988         struct drm_i915_private *dev_priv = to_i915(dev);
14989         struct drm_atomic_state *state;
14990         struct intel_atomic_state *intel_state;
14991         struct drm_crtc *crtc;
14992         struct drm_crtc_state *cstate;
14993         struct drm_modeset_acquire_ctx ctx;
14994         int ret;
14995         int i;
14996
14997         /* Only supported on platforms that use atomic watermark design */
14998         if (!dev_priv->display.optimize_watermarks)
14999                 return;
15000
15001         /*
15002          * We need to hold connection_mutex before calling duplicate_state so
15003          * that the connector loop is protected.
15004          */
15005         drm_modeset_acquire_init(&ctx, 0);
15006 retry:
15007         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15008         if (ret == -EDEADLK) {
15009                 drm_modeset_backoff(&ctx);
15010                 goto retry;
15011         } else if (WARN_ON(ret)) {
15012                 goto fail;
15013         }
15014
15015         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15016         if (WARN_ON(IS_ERR(state)))
15017                 goto fail;
15018
15019         intel_state = to_intel_atomic_state(state);
15020
15021         /*
15022          * Hardware readout is the only time we don't want to calculate
15023          * intermediate watermarks (since we don't trust the current
15024          * watermarks).
15025          */
15026         if (!HAS_GMCH_DISPLAY(dev_priv))
15027                 intel_state->skip_intermediate_wm = true;
15028
15029         ret = intel_atomic_check(dev, state);
15030         if (ret) {
15031                 /*
15032                  * If we fail here, it means that the hardware appears to be
15033                  * programmed in a way that shouldn't be possible, given our
15034                  * understanding of watermark requirements.  This might mean a
15035                  * mistake in the hardware readout code or a mistake in the
15036                  * watermark calculations for a given platform.  Raise a WARN
15037                  * so that this is noticeable.
15038                  *
15039                  * If this actually happens, we'll have to just leave the
15040                  * BIOS-programmed watermarks untouched and hope for the best.
15041                  */
15042                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15043                 goto put_state;
15044         }
15045
15046         /* Write calculated watermark values back */
15047         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15048                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15049
15050                 cs->wm.need_postvbl_update = true;
15051                 dev_priv->display.optimize_watermarks(intel_state, cs);
15052
15053                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15054         }
15055
15056 put_state:
15057         drm_atomic_state_put(state);
15058 fail:
15059         drm_modeset_drop_locks(&ctx);
15060         drm_modeset_acquire_fini(&ctx);
15061 }
15062
15063 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15064 {
15065         if (IS_GEN(dev_priv, 5)) {
15066                 u32 fdi_pll_clk =
15067                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15068
15069                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15070         } else if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv)) {
15071                 dev_priv->fdi_pll_freq = 270000;
15072         } else {
15073                 return;
15074         }
15075
15076         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15077 }
15078
15079 static int intel_initial_commit(struct drm_device *dev)
15080 {
15081         struct drm_atomic_state *state = NULL;
15082         struct drm_modeset_acquire_ctx ctx;
15083         struct drm_crtc *crtc;
15084         struct drm_crtc_state *crtc_state;
15085         int ret = 0;
15086
15087         state = drm_atomic_state_alloc(dev);
15088         if (!state)
15089                 return -ENOMEM;
15090
15091         drm_modeset_acquire_init(&ctx, 0);
15092
15093 retry:
15094         state->acquire_ctx = &ctx;
15095
15096         drm_for_each_crtc(crtc, dev) {
15097                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15098                 if (IS_ERR(crtc_state)) {
15099                         ret = PTR_ERR(crtc_state);
15100                         goto out;
15101                 }
15102
15103                 if (crtc_state->active) {
15104                         ret = drm_atomic_add_affected_planes(state, crtc);
15105                         if (ret)
15106                                 goto out;
15107
15108                         /*
15109                          * FIXME hack to force a LUT update to avoid the
15110                          * plane update forcing the pipe gamma on without
15111                          * having a proper LUT loaded. Remove once we
15112                          * have readout for pipe gamma enable.
15113                          */
15114                         crtc_state->color_mgmt_changed = true;
15115                 }
15116         }
15117
15118         ret = drm_atomic_commit(state);
15119
15120 out:
15121         if (ret == -EDEADLK) {
15122                 drm_atomic_state_clear(state);
15123                 drm_modeset_backoff(&ctx);
15124                 goto retry;
15125         }
15126
15127         drm_atomic_state_put(state);
15128
15129         drm_modeset_drop_locks(&ctx);
15130         drm_modeset_acquire_fini(&ctx);
15131
15132         return ret;
15133 }
15134
15135 int intel_modeset_init(struct drm_device *dev)
15136 {
15137         struct drm_i915_private *dev_priv = to_i915(dev);
15138         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15139         enum pipe pipe;
15140         struct intel_crtc *crtc;
15141         int ret;
15142
15143         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15144
15145         drm_mode_config_init(dev);
15146
15147         dev->mode_config.min_width = 0;
15148         dev->mode_config.min_height = 0;
15149
15150         dev->mode_config.preferred_depth = 24;
15151         dev->mode_config.prefer_shadow = 1;
15152
15153         dev->mode_config.allow_fb_modifiers = true;
15154
15155         dev->mode_config.funcs = &intel_mode_funcs;
15156
15157         init_llist_head(&dev_priv->atomic_helper.free_list);
15158         INIT_WORK(&dev_priv->atomic_helper.free_work,
15159                   intel_atomic_helper_free_state_worker);
15160
15161         intel_init_quirks(dev_priv);
15162
15163         intel_fbc_init(dev_priv);
15164
15165         intel_init_pm(dev_priv);
15166
15167         /*
15168          * There may be no VBT; and if the BIOS enabled SSC we can
15169          * just keep using it to avoid unnecessary flicker.  Whereas if the
15170          * BIOS isn't using it, don't assume it will work even if the VBT
15171          * indicates as much.
15172          */
15173         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15174                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15175                                             DREF_SSC1_ENABLE);
15176
15177                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15178                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15179                                      bios_lvds_use_ssc ? "en" : "dis",
15180                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15181                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15182                 }
15183         }
15184
15185         /* maximum framebuffer dimensions */
15186         if (IS_GEN(dev_priv, 2)) {
15187                 dev->mode_config.max_width = 2048;
15188                 dev->mode_config.max_height = 2048;
15189         } else if (IS_GEN(dev_priv, 3)) {
15190                 dev->mode_config.max_width = 4096;
15191                 dev->mode_config.max_height = 4096;
15192         } else {
15193                 dev->mode_config.max_width = 8192;
15194                 dev->mode_config.max_height = 8192;
15195         }
15196
15197         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15198                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15199                 dev->mode_config.cursor_height = 1023;
15200         } else if (IS_GEN(dev_priv, 2)) {
15201                 dev->mode_config.cursor_width = 64;
15202                 dev->mode_config.cursor_height = 64;
15203         } else {
15204                 dev->mode_config.cursor_width = 256;
15205                 dev->mode_config.cursor_height = 256;
15206         }
15207
15208         dev->mode_config.fb_base = ggtt->gmadr.start;
15209
15210         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15211                       INTEL_INFO(dev_priv)->num_pipes,
15212                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15213
15214         for_each_pipe(dev_priv, pipe) {
15215                 ret = intel_crtc_init(dev_priv, pipe);
15216                 if (ret) {
15217                         drm_mode_config_cleanup(dev);
15218                         return ret;
15219                 }
15220         }
15221
15222         intel_shared_dpll_init(dev);
15223         intel_update_fdi_pll_freq(dev_priv);
15224
15225         intel_update_czclk(dev_priv);
15226         intel_modeset_init_hw(dev);
15227
15228         if (dev_priv->max_cdclk_freq == 0)
15229                 intel_update_max_cdclk(dev_priv);
15230
15231         /* Just disable it once at startup */
15232         i915_disable_vga(dev_priv);
15233         intel_setup_outputs(dev_priv);
15234
15235         drm_modeset_lock_all(dev);
15236         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15237         drm_modeset_unlock_all(dev);
15238
15239         for_each_intel_crtc(dev, crtc) {
15240                 struct intel_initial_plane_config plane_config = {};
15241
15242                 if (!crtc->active)
15243                         continue;
15244
15245                 /*
15246                  * Note that reserving the BIOS fb up front prevents us
15247                  * from stuffing other stolen allocations like the ring
15248                  * on top.  This prevents some ugliness at boot time, and
15249                  * can even allow for smooth boot transitions if the BIOS
15250                  * fb is large enough for the active pipe configuration.
15251                  */
15252                 dev_priv->display.get_initial_plane_config(crtc,
15253                                                            &plane_config);
15254
15255                 /*
15256                  * If the fb is shared between multiple heads, we'll
15257                  * just get the first one.
15258                  */
15259                 intel_find_initial_plane_obj(crtc, &plane_config);
15260         }
15261
15262         /*
15263          * Make sure hardware watermarks really match the state we read out.
15264          * Note that we need to do this after reconstructing the BIOS fb's
15265          * since the watermark calculation done here will use pstate->fb.
15266          */
15267         if (!HAS_GMCH_DISPLAY(dev_priv))
15268                 sanitize_watermarks(dev);
15269
15270         /*
15271          * Force all active planes to recompute their states. So that on
15272          * mode_setcrtc after probe, all the intel_plane_state variables
15273          * are already calculated and there is no assert_plane warnings
15274          * during bootup.
15275          */
15276         ret = intel_initial_commit(dev);
15277         if (ret)
15278                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15279
15280         return 0;
15281 }
15282
15283 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15284 {
15285         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15286         /* 640x480@60Hz, ~25175 kHz */
15287         struct dpll clock = {
15288                 .m1 = 18,
15289                 .m2 = 7,
15290                 .p1 = 13,
15291                 .p2 = 4,
15292                 .n = 2,
15293         };
15294         u32 dpll, fp;
15295         int i;
15296
15297         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15298
15299         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15300                       pipe_name(pipe), clock.vco, clock.dot);
15301
15302         fp = i9xx_dpll_compute_fp(&clock);
15303         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15304                 DPLL_VGA_MODE_DIS |
15305                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15306                 PLL_P2_DIVIDE_BY_4 |
15307                 PLL_REF_INPUT_DREFCLK |
15308                 DPLL_VCO_ENABLE;
15309
15310         I915_WRITE(FP0(pipe), fp);
15311         I915_WRITE(FP1(pipe), fp);
15312
15313         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15314         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15315         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15316         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15317         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15318         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15319         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15320
15321         /*
15322          * Apparently we need to have VGA mode enabled prior to changing
15323          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15324          * dividers, even though the register value does change.
15325          */
15326         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15327         I915_WRITE(DPLL(pipe), dpll);
15328
15329         /* Wait for the clocks to stabilize. */
15330         POSTING_READ(DPLL(pipe));
15331         udelay(150);
15332
15333         /* The pixel multiplier can only be updated once the
15334          * DPLL is enabled and the clocks are stable.
15335          *
15336          * So write it again.
15337          */
15338         I915_WRITE(DPLL(pipe), dpll);
15339
15340         /* We do this three times for luck */
15341         for (i = 0; i < 3 ; i++) {
15342                 I915_WRITE(DPLL(pipe), dpll);
15343                 POSTING_READ(DPLL(pipe));
15344                 udelay(150); /* wait for warmup */
15345         }
15346
15347         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15348         POSTING_READ(PIPECONF(pipe));
15349
15350         intel_wait_for_pipe_scanline_moving(crtc);
15351 }
15352
15353 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15354 {
15355         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15356
15357         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15358                       pipe_name(pipe));
15359
15360         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15361         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15362         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15363         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15364         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15365
15366         I915_WRITE(PIPECONF(pipe), 0);
15367         POSTING_READ(PIPECONF(pipe));
15368
15369         intel_wait_for_pipe_scanline_stopped(crtc);
15370
15371         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15372         POSTING_READ(DPLL(pipe));
15373 }
15374
15375 static void
15376 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15377 {
15378         struct intel_crtc *crtc;
15379
15380         if (INTEL_GEN(dev_priv) >= 4)
15381                 return;
15382
15383         for_each_intel_crtc(&dev_priv->drm, crtc) {
15384                 struct intel_plane *plane =
15385                         to_intel_plane(crtc->base.primary);
15386                 struct intel_crtc *plane_crtc;
15387                 enum pipe pipe;
15388
15389                 if (!plane->get_hw_state(plane, &pipe))
15390                         continue;
15391
15392                 if (pipe == crtc->pipe)
15393                         continue;
15394
15395                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
15396                               plane->base.base.id, plane->base.name);
15397
15398                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15399                 intel_plane_disable_noatomic(plane_crtc, plane);
15400         }
15401 }
15402
15403 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15404 {
15405         struct drm_device *dev = crtc->base.dev;
15406         struct intel_encoder *encoder;
15407
15408         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15409                 return true;
15410
15411         return false;
15412 }
15413
15414 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15415 {
15416         struct drm_device *dev = encoder->base.dev;
15417         struct intel_connector *connector;
15418
15419         for_each_connector_on_encoder(dev, &encoder->base, connector)
15420                 return connector;
15421
15422         return NULL;
15423 }
15424
15425 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15426                               enum pipe pch_transcoder)
15427 {
15428         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15429                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15430 }
15431
15432 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15433                                 struct drm_modeset_acquire_ctx *ctx)
15434 {
15435         struct drm_device *dev = crtc->base.dev;
15436         struct drm_i915_private *dev_priv = to_i915(dev);
15437         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
15438         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
15439
15440         /* Clear any frame start delays used for debugging left by the BIOS */
15441         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15442                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15443
15444                 I915_WRITE(reg,
15445                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15446         }
15447
15448         if (crtc_state->base.active) {
15449                 struct intel_plane *plane;
15450
15451                 /* Disable everything but the primary plane */
15452                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15453                         const struct intel_plane_state *plane_state =
15454                                 to_intel_plane_state(plane->base.state);
15455
15456                         if (plane_state->base.visible &&
15457                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15458                                 intel_plane_disable_noatomic(crtc, plane);
15459                 }
15460         }
15461
15462         /* Adjust the state of the output pipe according to whether we
15463          * have active connectors/encoders. */
15464         if (crtc_state->base.active && !intel_crtc_has_encoders(crtc))
15465                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15466
15467         if (crtc_state->base.active || HAS_GMCH_DISPLAY(dev_priv)) {
15468                 /*
15469                  * We start out with underrun reporting disabled to avoid races.
15470                  * For correct bookkeeping mark this on active crtcs.
15471                  *
15472                  * Also on gmch platforms we dont have any hardware bits to
15473                  * disable the underrun reporting. Which means we need to start
15474                  * out with underrun reporting disabled also on inactive pipes,
15475                  * since otherwise we'll complain about the garbage we read when
15476                  * e.g. coming up after runtime pm.
15477                  *
15478                  * No protection against concurrent access is required - at
15479                  * worst a fifo underrun happens which also sets this to false.
15480                  */
15481                 crtc->cpu_fifo_underrun_disabled = true;
15482                 /*
15483                  * We track the PCH trancoder underrun reporting state
15484                  * within the crtc. With crtc for pipe A housing the underrun
15485                  * reporting state for PCH transcoder A, crtc for pipe B housing
15486                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15487                  * and marking underrun reporting as disabled for the non-existing
15488                  * PCH transcoders B and C would prevent enabling the south
15489                  * error interrupt (see cpt_can_enable_serr_int()).
15490                  */
15491                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15492                         crtc->pch_fifo_underrun_disabled = true;
15493         }
15494 }
15495
15496 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15497 {
15498         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
15499         struct intel_connector *connector;
15500
15501         /* We need to check both for a crtc link (meaning that the
15502          * encoder is active and trying to read from a pipe) and the
15503          * pipe itself being active. */
15504         bool has_active_crtc = encoder->base.crtc &&
15505                 to_intel_crtc(encoder->base.crtc)->active;
15506
15507         connector = intel_encoder_find_connector(encoder);
15508         if (connector && !has_active_crtc) {
15509                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15510                               encoder->base.base.id,
15511                               encoder->base.name);
15512
15513                 /* Connector is active, but has no active pipe. This is
15514                  * fallout from our resume register restoring. Disable
15515                  * the encoder manually again. */
15516                 if (encoder->base.crtc) {
15517                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15518
15519                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15520                                       encoder->base.base.id,
15521                                       encoder->base.name);
15522                         if (encoder->disable)
15523                                 encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15524                         if (encoder->post_disable)
15525                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15526                 }
15527                 encoder->base.crtc = NULL;
15528
15529                 /* Inconsistent output/port/pipe state happens presumably due to
15530                  * a bug in one of the get_hw_state functions. Or someplace else
15531                  * in our code, like the register restore mess on resume. Clamp
15532                  * things to off as a safer default. */
15533
15534                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15535                 connector->base.encoder = NULL;
15536         }
15537
15538         /* notify opregion of the sanitized encoder state */
15539         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15540
15541         if (INTEL_GEN(dev_priv) >= 11)
15542                 icl_sanitize_encoder_pll_mapping(encoder);
15543 }
15544
15545 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15546 {
15547         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15548
15549         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15550                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15551                 i915_disable_vga(dev_priv);
15552         }
15553 }
15554
15555 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15556 {
15557         intel_wakeref_t wakeref;
15558
15559         /*
15560          * This function can be called both from intel_modeset_setup_hw_state or
15561          * at a very early point in our resume sequence, where the power well
15562          * structures are not yet restored. Since this function is at a very
15563          * paranoid "someone might have enabled VGA while we were not looking"
15564          * level, just check if the power well is enabled instead of trying to
15565          * follow the "don't touch the power well if we don't need it" policy
15566          * the rest of the driver uses.
15567          */
15568         wakeref = intel_display_power_get_if_enabled(dev_priv,
15569                                                      POWER_DOMAIN_VGA);
15570         if (!wakeref)
15571                 return;
15572
15573         i915_redisable_vga_power_on(dev_priv);
15574
15575         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA, wakeref);
15576 }
15577
15578 /* FIXME read out full plane state for all planes */
15579 static void readout_plane_state(struct drm_i915_private *dev_priv)
15580 {
15581         struct intel_plane *plane;
15582         struct intel_crtc *crtc;
15583
15584         for_each_intel_plane(&dev_priv->drm, plane) {
15585                 struct intel_plane_state *plane_state =
15586                         to_intel_plane_state(plane->base.state);
15587                 struct intel_crtc_state *crtc_state;
15588                 enum pipe pipe = PIPE_A;
15589                 bool visible;
15590
15591                 visible = plane->get_hw_state(plane, &pipe);
15592
15593                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15594                 crtc_state = to_intel_crtc_state(crtc->base.state);
15595
15596                 intel_set_plane_visible(crtc_state, plane_state, visible);
15597
15598                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
15599                               plane->base.base.id, plane->base.name,
15600                               enableddisabled(visible), pipe_name(pipe));
15601         }
15602
15603         for_each_intel_crtc(&dev_priv->drm, crtc) {
15604                 struct intel_crtc_state *crtc_state =
15605                         to_intel_crtc_state(crtc->base.state);
15606
15607                 fixup_active_planes(crtc_state);
15608         }
15609 }
15610
15611 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15612 {
15613         struct drm_i915_private *dev_priv = to_i915(dev);
15614         enum pipe pipe;
15615         struct intel_crtc *crtc;
15616         struct intel_encoder *encoder;
15617         struct intel_connector *connector;
15618         struct drm_connector_list_iter conn_iter;
15619         int i;
15620
15621         dev_priv->active_crtcs = 0;
15622
15623         for_each_intel_crtc(dev, crtc) {
15624                 struct intel_crtc_state *crtc_state =
15625                         to_intel_crtc_state(crtc->base.state);
15626
15627                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15628                 memset(crtc_state, 0, sizeof(*crtc_state));
15629                 crtc_state->base.crtc = &crtc->base;
15630
15631                 crtc_state->base.active = crtc_state->base.enable =
15632                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15633
15634                 crtc->base.enabled = crtc_state->base.enable;
15635                 crtc->active = crtc_state->base.active;
15636
15637                 if (crtc_state->base.active)
15638                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15639
15640                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15641                               crtc->base.base.id, crtc->base.name,
15642                               enableddisabled(crtc_state->base.active));
15643         }
15644
15645         readout_plane_state(dev_priv);
15646
15647         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15648                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15649
15650                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15651                                                         &pll->state.hw_state);
15652                 pll->state.crtc_mask = 0;
15653                 for_each_intel_crtc(dev, crtc) {
15654                         struct intel_crtc_state *crtc_state =
15655                                 to_intel_crtc_state(crtc->base.state);
15656
15657                         if (crtc_state->base.active &&
15658                             crtc_state->shared_dpll == pll)
15659                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15660                 }
15661                 pll->active_mask = pll->state.crtc_mask;
15662
15663                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15664                               pll->info->name, pll->state.crtc_mask, pll->on);
15665         }
15666
15667         for_each_intel_encoder(dev, encoder) {
15668                 pipe = 0;
15669
15670                 if (encoder->get_hw_state(encoder, &pipe)) {
15671                         struct intel_crtc_state *crtc_state;
15672
15673                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15674                         crtc_state = to_intel_crtc_state(crtc->base.state);
15675
15676                         encoder->base.crtc = &crtc->base;
15677                         encoder->get_config(encoder, crtc_state);
15678                 } else {
15679                         encoder->base.crtc = NULL;
15680                 }
15681
15682                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15683                               encoder->base.base.id, encoder->base.name,
15684                               enableddisabled(encoder->base.crtc),
15685                               pipe_name(pipe));
15686         }
15687
15688         drm_connector_list_iter_begin(dev, &conn_iter);
15689         for_each_intel_connector_iter(connector, &conn_iter) {
15690                 if (connector->get_hw_state(connector)) {
15691                         connector->base.dpms = DRM_MODE_DPMS_ON;
15692
15693                         encoder = connector->encoder;
15694                         connector->base.encoder = &encoder->base;
15695
15696                         if (encoder->base.crtc &&
15697                             encoder->base.crtc->state->active) {
15698                                 /*
15699                                  * This has to be done during hardware readout
15700                                  * because anything calling .crtc_disable may
15701                                  * rely on the connector_mask being accurate.
15702                                  */
15703                                 encoder->base.crtc->state->connector_mask |=
15704                                         drm_connector_mask(&connector->base);
15705                                 encoder->base.crtc->state->encoder_mask |=
15706                                         drm_encoder_mask(&encoder->base);
15707                         }
15708
15709                 } else {
15710                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15711                         connector->base.encoder = NULL;
15712                 }
15713                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15714                               connector->base.base.id, connector->base.name,
15715                               enableddisabled(connector->base.encoder));
15716         }
15717         drm_connector_list_iter_end(&conn_iter);
15718
15719         for_each_intel_crtc(dev, crtc) {
15720                 struct intel_crtc_state *crtc_state =
15721                         to_intel_crtc_state(crtc->base.state);
15722                 int min_cdclk = 0;
15723
15724                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15725                 if (crtc_state->base.active) {
15726                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15727                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15728                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15729                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15730                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15731
15732                         /*
15733                          * The initial mode needs to be set in order to keep
15734                          * the atomic core happy. It wants a valid mode if the
15735                          * crtc's enabled, so we do the above call.
15736                          *
15737                          * But we don't set all the derived state fully, hence
15738                          * set a flag to indicate that a full recalculation is
15739                          * needed on the next commit.
15740                          */
15741                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15742
15743                         intel_crtc_compute_pixel_rate(crtc_state);
15744
15745                         if (dev_priv->display.modeset_calc_cdclk) {
15746                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15747                                 if (WARN_ON(min_cdclk < 0))
15748                                         min_cdclk = 0;
15749                         }
15750
15751                         drm_calc_timestamping_constants(&crtc->base,
15752                                                         &crtc_state->base.adjusted_mode);
15753                         update_scanline_offset(crtc_state);
15754                 }
15755
15756                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15757                 dev_priv->min_voltage_level[crtc->pipe] =
15758                         crtc_state->min_voltage_level;
15759
15760                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15761         }
15762 }
15763
15764 static void
15765 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15766 {
15767         struct intel_encoder *encoder;
15768
15769         for_each_intel_encoder(&dev_priv->drm, encoder) {
15770                 u64 get_domains;
15771                 enum intel_display_power_domain domain;
15772                 struct intel_crtc_state *crtc_state;
15773
15774                 if (!encoder->get_power_domains)
15775                         continue;
15776
15777                 /*
15778                  * MST-primary and inactive encoders don't have a crtc state
15779                  * and neither of these require any power domain references.
15780                  */
15781                 if (!encoder->base.crtc)
15782                         continue;
15783
15784                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15785                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15786                 for_each_power_domain(domain, get_domains)
15787                         intel_display_power_get(dev_priv, domain);
15788         }
15789 }
15790
15791 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15792 {
15793         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15794         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15795                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15796                            DARBF_GATING_DIS);
15797
15798         if (IS_HASWELL(dev_priv)) {
15799                 /*
15800                  * WaRsPkgCStateDisplayPMReq:hsw
15801                  * System hang if this isn't done before disabling all planes!
15802                  */
15803                 I915_WRITE(CHICKEN_PAR1_1,
15804                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15805         }
15806 }
15807
15808 static void ibx_sanitize_pch_hdmi_port(struct drm_i915_private *dev_priv,
15809                                        enum port port, i915_reg_t hdmi_reg)
15810 {
15811         u32 val = I915_READ(hdmi_reg);
15812
15813         if (val & SDVO_ENABLE ||
15814             (val & SDVO_PIPE_SEL_MASK) == SDVO_PIPE_SEL(PIPE_A))
15815                 return;
15816
15817         DRM_DEBUG_KMS("Sanitizing transcoder select for HDMI %c\n",
15818                       port_name(port));
15819
15820         val &= ~SDVO_PIPE_SEL_MASK;
15821         val |= SDVO_PIPE_SEL(PIPE_A);
15822
15823         I915_WRITE(hdmi_reg, val);
15824 }
15825
15826 static void ibx_sanitize_pch_dp_port(struct drm_i915_private *dev_priv,
15827                                      enum port port, i915_reg_t dp_reg)
15828 {
15829         u32 val = I915_READ(dp_reg);
15830
15831         if (val & DP_PORT_EN ||
15832             (val & DP_PIPE_SEL_MASK) == DP_PIPE_SEL(PIPE_A))
15833                 return;
15834
15835         DRM_DEBUG_KMS("Sanitizing transcoder select for DP %c\n",
15836                       port_name(port));
15837
15838         val &= ~DP_PIPE_SEL_MASK;
15839         val |= DP_PIPE_SEL(PIPE_A);
15840
15841         I915_WRITE(dp_reg, val);
15842 }
15843
15844 static void ibx_sanitize_pch_ports(struct drm_i915_private *dev_priv)
15845 {
15846         /*
15847          * The BIOS may select transcoder B on some of the PCH
15848          * ports even it doesn't enable the port. This would trip
15849          * assert_pch_dp_disabled() and assert_pch_hdmi_disabled().
15850          * Sanitize the transcoder select bits to prevent that. We
15851          * assume that the BIOS never actually enabled the port,
15852          * because if it did we'd actually have to toggle the port
15853          * on and back off to make the transcoder A select stick
15854          * (see. intel_dp_link_down(), intel_disable_hdmi(),
15855          * intel_disable_sdvo()).
15856          */
15857         ibx_sanitize_pch_dp_port(dev_priv, PORT_B, PCH_DP_B);
15858         ibx_sanitize_pch_dp_port(dev_priv, PORT_C, PCH_DP_C);
15859         ibx_sanitize_pch_dp_port(dev_priv, PORT_D, PCH_DP_D);
15860
15861         /* PCH SDVOB multiplex with HDMIB */
15862         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_B, PCH_HDMIB);
15863         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_C, PCH_HDMIC);
15864         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_D, PCH_HDMID);
15865 }
15866
15867 /* Scan out the current hw modeset state,
15868  * and sanitizes it to the current state
15869  */
15870 static void
15871 intel_modeset_setup_hw_state(struct drm_device *dev,
15872                              struct drm_modeset_acquire_ctx *ctx)
15873 {
15874         struct drm_i915_private *dev_priv = to_i915(dev);
15875         struct intel_crtc_state *crtc_state;
15876         struct intel_encoder *encoder;
15877         struct intel_crtc *crtc;
15878         intel_wakeref_t wakeref;
15879         int i;
15880
15881         wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15882
15883         intel_early_display_was(dev_priv);
15884         intel_modeset_readout_hw_state(dev);
15885
15886         /* HW state is read out, now we need to sanitize this mess. */
15887         get_encoder_power_domains(dev_priv);
15888
15889         if (HAS_PCH_IBX(dev_priv))
15890                 ibx_sanitize_pch_ports(dev_priv);
15891
15892         /*
15893          * intel_sanitize_plane_mapping() may need to do vblank
15894          * waits, so we need vblank interrupts restored beforehand.
15895          */
15896         for_each_intel_crtc(&dev_priv->drm, crtc) {
15897                 drm_crtc_vblank_reset(&crtc->base);
15898
15899                 if (crtc->base.state->active)
15900                         drm_crtc_vblank_on(&crtc->base);
15901         }
15902
15903         intel_sanitize_plane_mapping(dev_priv);
15904
15905         for_each_intel_encoder(dev, encoder)
15906                 intel_sanitize_encoder(encoder);
15907
15908         for_each_intel_crtc(&dev_priv->drm, crtc) {
15909                 crtc_state = to_intel_crtc_state(crtc->base.state);
15910                 intel_sanitize_crtc(crtc, ctx);
15911                 intel_dump_pipe_config(crtc, crtc_state,
15912                                        "[setup_hw_state]");
15913         }
15914
15915         intel_modeset_update_connector_atomic_state(dev);
15916
15917         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15918                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15919
15920                 if (!pll->on || pll->active_mask)
15921                         continue;
15922
15923                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15924                               pll->info->name);
15925
15926                 pll->info->funcs->disable(dev_priv, pll);
15927                 pll->on = false;
15928         }
15929
15930         if (IS_G4X(dev_priv)) {
15931                 g4x_wm_get_hw_state(dev_priv);
15932                 g4x_wm_sanitize(dev_priv);
15933         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15934                 vlv_wm_get_hw_state(dev_priv);
15935                 vlv_wm_sanitize(dev_priv);
15936         } else if (INTEL_GEN(dev_priv) >= 9) {
15937                 skl_wm_get_hw_state(dev_priv);
15938         } else if (HAS_PCH_SPLIT(dev_priv)) {
15939                 ilk_wm_get_hw_state(dev_priv);
15940         }
15941
15942         for_each_intel_crtc(dev, crtc) {
15943                 u64 put_domains;
15944
15945                 crtc_state = to_intel_crtc_state(crtc->base.state);
15946                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc_state);
15947                 if (WARN_ON(put_domains))
15948                         modeset_put_power_domains(dev_priv, put_domains);
15949         }
15950
15951         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT, wakeref);
15952
15953         intel_fbc_init_pipe_state(dev_priv);
15954 }
15955
15956 void intel_display_resume(struct drm_device *dev)
15957 {
15958         struct drm_i915_private *dev_priv = to_i915(dev);
15959         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15960         struct drm_modeset_acquire_ctx ctx;
15961         int ret;
15962
15963         dev_priv->modeset_restore_state = NULL;
15964         if (state)
15965                 state->acquire_ctx = &ctx;
15966
15967         drm_modeset_acquire_init(&ctx, 0);
15968
15969         while (1) {
15970                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15971                 if (ret != -EDEADLK)
15972                         break;
15973
15974                 drm_modeset_backoff(&ctx);
15975         }
15976
15977         if (!ret)
15978                 ret = __intel_display_resume(dev, state, &ctx);
15979
15980         intel_enable_ipc(dev_priv);
15981         drm_modeset_drop_locks(&ctx);
15982         drm_modeset_acquire_fini(&ctx);
15983
15984         if (ret)
15985                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15986         if (state)
15987                 drm_atomic_state_put(state);
15988 }
15989
15990 static void intel_hpd_poll_fini(struct drm_device *dev)
15991 {
15992         struct intel_connector *connector;
15993         struct drm_connector_list_iter conn_iter;
15994
15995         /* Kill all the work that may have been queued by hpd. */
15996         drm_connector_list_iter_begin(dev, &conn_iter);
15997         for_each_intel_connector_iter(connector, &conn_iter) {
15998                 if (connector->modeset_retry_work.func)
15999                         cancel_work_sync(&connector->modeset_retry_work);
16000                 if (connector->hdcp.shim) {
16001                         cancel_delayed_work_sync(&connector->hdcp.check_work);
16002                         cancel_work_sync(&connector->hdcp.prop_work);
16003                 }
16004         }
16005         drm_connector_list_iter_end(&conn_iter);
16006 }
16007
16008 void intel_modeset_cleanup(struct drm_device *dev)
16009 {
16010         struct drm_i915_private *dev_priv = to_i915(dev);
16011
16012         flush_workqueue(dev_priv->modeset_wq);
16013
16014         flush_work(&dev_priv->atomic_helper.free_work);
16015         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16016
16017         /*
16018          * Interrupts and polling as the first thing to avoid creating havoc.
16019          * Too much stuff here (turning of connectors, ...) would
16020          * experience fancy races otherwise.
16021          */
16022         intel_irq_uninstall(dev_priv);
16023
16024         /*
16025          * Due to the hpd irq storm handling the hotplug work can re-arm the
16026          * poll handlers. Hence disable polling after hpd handling is shut down.
16027          */
16028         intel_hpd_poll_fini(dev);
16029
16030         /* poll work can call into fbdev, hence clean that up afterwards */
16031         intel_fbdev_fini(dev_priv);
16032
16033         intel_unregister_dsm_handler();
16034
16035         intel_fbc_global_disable(dev_priv);
16036
16037         /* flush any delayed tasks or pending work */
16038         flush_scheduled_work();
16039
16040         drm_mode_config_cleanup(dev);
16041
16042         intel_overlay_cleanup(dev_priv);
16043
16044         intel_teardown_gmbus(dev_priv);
16045
16046         destroy_workqueue(dev_priv->modeset_wq);
16047
16048         intel_fbc_cleanup_cfb(dev_priv);
16049 }
16050
16051 /*
16052  * set vga decode state - true == enable VGA decode
16053  */
16054 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16055 {
16056         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16057         u16 gmch_ctrl;
16058
16059         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16060                 DRM_ERROR("failed to read control word\n");
16061                 return -EIO;
16062         }
16063
16064         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16065                 return 0;
16066
16067         if (state)
16068                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16069         else
16070                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16071
16072         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16073                 DRM_ERROR("failed to write control word\n");
16074                 return -EIO;
16075         }
16076
16077         return 0;
16078 }
16079
16080 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16081
16082 struct intel_display_error_state {
16083
16084         u32 power_well_driver;
16085
16086         int num_transcoders;
16087
16088         struct intel_cursor_error_state {
16089                 u32 control;
16090                 u32 position;
16091                 u32 base;
16092                 u32 size;
16093         } cursor[I915_MAX_PIPES];
16094
16095         struct intel_pipe_error_state {
16096                 bool power_domain_on;
16097                 u32 source;
16098                 u32 stat;
16099         } pipe[I915_MAX_PIPES];
16100
16101         struct intel_plane_error_state {
16102                 u32 control;
16103                 u32 stride;
16104                 u32 size;
16105                 u32 pos;
16106                 u32 addr;
16107                 u32 surface;
16108                 u32 tile_offset;
16109         } plane[I915_MAX_PIPES];
16110
16111         struct intel_transcoder_error_state {
16112                 bool power_domain_on;
16113                 enum transcoder cpu_transcoder;
16114
16115                 u32 conf;
16116
16117                 u32 htotal;
16118                 u32 hblank;
16119                 u32 hsync;
16120                 u32 vtotal;
16121                 u32 vblank;
16122                 u32 vsync;
16123         } transcoder[4];
16124 };
16125
16126 struct intel_display_error_state *
16127 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16128 {
16129         struct intel_display_error_state *error;
16130         int transcoders[] = {
16131                 TRANSCODER_A,
16132                 TRANSCODER_B,
16133                 TRANSCODER_C,
16134                 TRANSCODER_EDP,
16135         };
16136         int i;
16137
16138         if (!HAS_DISPLAY(dev_priv))
16139                 return NULL;
16140
16141         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16142         if (error == NULL)
16143                 return NULL;
16144
16145         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16146                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16147
16148         for_each_pipe(dev_priv, i) {
16149                 error->pipe[i].power_domain_on =
16150                         __intel_display_power_is_enabled(dev_priv,
16151                                                          POWER_DOMAIN_PIPE(i));
16152                 if (!error->pipe[i].power_domain_on)
16153                         continue;
16154
16155                 error->cursor[i].control = I915_READ(CURCNTR(i));
16156                 error->cursor[i].position = I915_READ(CURPOS(i));
16157                 error->cursor[i].base = I915_READ(CURBASE(i));
16158
16159                 error->plane[i].control = I915_READ(DSPCNTR(i));
16160                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16161                 if (INTEL_GEN(dev_priv) <= 3) {
16162                         error->plane[i].size = I915_READ(DSPSIZE(i));
16163                         error->plane[i].pos = I915_READ(DSPPOS(i));
16164                 }
16165                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16166                         error->plane[i].addr = I915_READ(DSPADDR(i));
16167                 if (INTEL_GEN(dev_priv) >= 4) {
16168                         error->plane[i].surface = I915_READ(DSPSURF(i));
16169                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16170                 }
16171
16172                 error->pipe[i].source = I915_READ(PIPESRC(i));
16173
16174                 if (HAS_GMCH_DISPLAY(dev_priv))
16175                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16176         }
16177
16178         /* Note: this does not include DSI transcoders. */
16179         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16180         if (HAS_DDI(dev_priv))
16181                 error->num_transcoders++; /* Account for eDP. */
16182
16183         for (i = 0; i < error->num_transcoders; i++) {
16184                 enum transcoder cpu_transcoder = transcoders[i];
16185
16186                 error->transcoder[i].power_domain_on =
16187                         __intel_display_power_is_enabled(dev_priv,
16188                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16189                 if (!error->transcoder[i].power_domain_on)
16190                         continue;
16191
16192                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16193
16194                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16195                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16196                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16197                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16198                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16199                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16200                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16201         }
16202
16203         return error;
16204 }
16205
16206 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16207
16208 void
16209 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16210                                 struct intel_display_error_state *error)
16211 {
16212         struct drm_i915_private *dev_priv = m->i915;
16213         int i;
16214
16215         if (!error)
16216                 return;
16217
16218         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16219         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16220                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16221                            error->power_well_driver);
16222         for_each_pipe(dev_priv, i) {
16223                 err_printf(m, "Pipe [%d]:\n", i);
16224                 err_printf(m, "  Power: %s\n",
16225                            onoff(error->pipe[i].power_domain_on));
16226                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16227                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16228
16229                 err_printf(m, "Plane [%d]:\n", i);
16230                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16231                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16232                 if (INTEL_GEN(dev_priv) <= 3) {
16233                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16234                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16235                 }
16236                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16237                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16238                 if (INTEL_GEN(dev_priv) >= 4) {
16239                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16240                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16241                 }
16242
16243                 err_printf(m, "Cursor [%d]:\n", i);
16244                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16245                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16246                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16247         }
16248
16249         for (i = 0; i < error->num_transcoders; i++) {
16250                 err_printf(m, "CPU transcoder: %s\n",
16251                            transcoder_name(error->transcoder[i].cpu_transcoder));
16252                 err_printf(m, "  Power: %s\n",
16253                            onoff(error->transcoder[i].power_domain_on));
16254                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16255                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16256                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16257                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16258                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16259                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16260                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16261         }
16262 }
16263
16264 #endif