drm/i915: Pass the new crtc_state to ->disable_plane()
[linux-2.6-block.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/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/drmP.h>
35 #include "intel_drv.h"
36 #include "intel_frontbuffer.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_gem_clflush.h"
40 #include "intel_dsi.h"
41 #include "i915_trace.h"
42 #include <drm/drm_atomic.h>
43 #include <drm/drm_atomic_helper.h>
44 #include <drm/drm_dp_helper.h>
45 #include <drm/drm_crtc_helper.h>
46 #include <drm/drm_plane_helper.h>
47 #include <drm/drm_rect.h>
48 #include <drm/drm_atomic_uapi.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 /* Primary plane formats for gen <= 3 */
53 static const uint32_t i8xx_primary_formats[] = {
54         DRM_FORMAT_C8,
55         DRM_FORMAT_RGB565,
56         DRM_FORMAT_XRGB1555,
57         DRM_FORMAT_XRGB8888,
58 };
59
60 /* Primary plane formats for gen >= 4 */
61 static const uint32_t i965_primary_formats[] = {
62         DRM_FORMAT_C8,
63         DRM_FORMAT_RGB565,
64         DRM_FORMAT_XRGB8888,
65         DRM_FORMAT_XBGR8888,
66         DRM_FORMAT_XRGB2101010,
67         DRM_FORMAT_XBGR2101010,
68 };
69
70 static const uint64_t i9xx_format_modifiers[] = {
71         I915_FORMAT_MOD_X_TILED,
72         DRM_FORMAT_MOD_LINEAR,
73         DRM_FORMAT_MOD_INVALID
74 };
75
76 /* Cursor formats */
77 static const uint32_t intel_cursor_formats[] = {
78         DRM_FORMAT_ARGB8888,
79 };
80
81 static const uint64_t cursor_format_modifiers[] = {
82         DRM_FORMAT_MOD_LINEAR,
83         DRM_FORMAT_MOD_INVALID
84 };
85
86 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
87                                 struct intel_crtc_state *pipe_config);
88 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
89                                    struct intel_crtc_state *pipe_config);
90
91 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
92                                   struct drm_i915_gem_object *obj,
93                                   struct drm_mode_fb_cmd2 *mode_cmd);
94 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state);
95 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state);
96 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
97                                          const struct intel_link_m_n *m_n,
98                                          const struct intel_link_m_n *m2_n2);
99 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state);
100 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state);
101 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state);
102 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state);
103 static void vlv_prepare_pll(struct intel_crtc *crtc,
104                             const struct intel_crtc_state *pipe_config);
105 static void chv_prepare_pll(struct intel_crtc *crtc,
106                             const struct intel_crtc_state *pipe_config);
107 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
108 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
109 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
110                                     struct intel_crtc_state *crtc_state);
111 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state);
112 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state);
113 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state);
114 static void intel_modeset_setup_hw_state(struct drm_device *dev,
115                                          struct drm_modeset_acquire_ctx *ctx);
116 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
117
118 struct intel_limit {
119         struct {
120                 int min, max;
121         } dot, vco, n, m, m1, m2, p, p1;
122
123         struct {
124                 int dot_limit;
125                 int p2_slow, p2_fast;
126         } p2;
127 };
128
129 /* returns HPLL frequency in kHz */
130 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
131 {
132         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
133
134         /* Obtain SKU information */
135         mutex_lock(&dev_priv->sb_lock);
136         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
137                 CCK_FUSE_HPLL_FREQ_MASK;
138         mutex_unlock(&dev_priv->sb_lock);
139
140         return vco_freq[hpll_freq] * 1000;
141 }
142
143 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
144                       const char *name, u32 reg, int ref_freq)
145 {
146         u32 val;
147         int divider;
148
149         mutex_lock(&dev_priv->sb_lock);
150         val = vlv_cck_read(dev_priv, reg);
151         mutex_unlock(&dev_priv->sb_lock);
152
153         divider = val & CCK_FREQUENCY_VALUES;
154
155         WARN((val & CCK_FREQUENCY_STATUS) !=
156              (divider << CCK_FREQUENCY_STATUS_SHIFT),
157              "%s change in progress\n", name);
158
159         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
160 }
161
162 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
163                            const char *name, u32 reg)
164 {
165         if (dev_priv->hpll_freq == 0)
166                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
167
168         return vlv_get_cck_clock(dev_priv, name, reg,
169                                  dev_priv->hpll_freq);
170 }
171
172 static void intel_update_czclk(struct drm_i915_private *dev_priv)
173 {
174         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
175                 return;
176
177         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
178                                                       CCK_CZ_CLOCK_CONTROL);
179
180         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
181 }
182
183 static inline u32 /* units of 100MHz */
184 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
185                     const struct intel_crtc_state *pipe_config)
186 {
187         if (HAS_DDI(dev_priv))
188                 return pipe_config->port_clock; /* SPLL */
189         else
190                 return dev_priv->fdi_pll_freq;
191 }
192
193 static const struct intel_limit intel_limits_i8xx_dac = {
194         .dot = { .min = 25000, .max = 350000 },
195         .vco = { .min = 908000, .max = 1512000 },
196         .n = { .min = 2, .max = 16 },
197         .m = { .min = 96, .max = 140 },
198         .m1 = { .min = 18, .max = 26 },
199         .m2 = { .min = 6, .max = 16 },
200         .p = { .min = 4, .max = 128 },
201         .p1 = { .min = 2, .max = 33 },
202         .p2 = { .dot_limit = 165000,
203                 .p2_slow = 4, .p2_fast = 2 },
204 };
205
206 static const struct intel_limit intel_limits_i8xx_dvo = {
207         .dot = { .min = 25000, .max = 350000 },
208         .vco = { .min = 908000, .max = 1512000 },
209         .n = { .min = 2, .max = 16 },
210         .m = { .min = 96, .max = 140 },
211         .m1 = { .min = 18, .max = 26 },
212         .m2 = { .min = 6, .max = 16 },
213         .p = { .min = 4, .max = 128 },
214         .p1 = { .min = 2, .max = 33 },
215         .p2 = { .dot_limit = 165000,
216                 .p2_slow = 4, .p2_fast = 4 },
217 };
218
219 static const struct intel_limit intel_limits_i8xx_lvds = {
220         .dot = { .min = 25000, .max = 350000 },
221         .vco = { .min = 908000, .max = 1512000 },
222         .n = { .min = 2, .max = 16 },
223         .m = { .min = 96, .max = 140 },
224         .m1 = { .min = 18, .max = 26 },
225         .m2 = { .min = 6, .max = 16 },
226         .p = { .min = 4, .max = 128 },
227         .p1 = { .min = 1, .max = 6 },
228         .p2 = { .dot_limit = 165000,
229                 .p2_slow = 14, .p2_fast = 7 },
230 };
231
232 static const struct intel_limit intel_limits_i9xx_sdvo = {
233         .dot = { .min = 20000, .max = 400000 },
234         .vco = { .min = 1400000, .max = 2800000 },
235         .n = { .min = 1, .max = 6 },
236         .m = { .min = 70, .max = 120 },
237         .m1 = { .min = 8, .max = 18 },
238         .m2 = { .min = 3, .max = 7 },
239         .p = { .min = 5, .max = 80 },
240         .p1 = { .min = 1, .max = 8 },
241         .p2 = { .dot_limit = 200000,
242                 .p2_slow = 10, .p2_fast = 5 },
243 };
244
245 static const struct intel_limit intel_limits_i9xx_lvds = {
246         .dot = { .min = 20000, .max = 400000 },
247         .vco = { .min = 1400000, .max = 2800000 },
248         .n = { .min = 1, .max = 6 },
249         .m = { .min = 70, .max = 120 },
250         .m1 = { .min = 8, .max = 18 },
251         .m2 = { .min = 3, .max = 7 },
252         .p = { .min = 7, .max = 98 },
253         .p1 = { .min = 1, .max = 8 },
254         .p2 = { .dot_limit = 112000,
255                 .p2_slow = 14, .p2_fast = 7 },
256 };
257
258
259 static const struct intel_limit intel_limits_g4x_sdvo = {
260         .dot = { .min = 25000, .max = 270000 },
261         .vco = { .min = 1750000, .max = 3500000},
262         .n = { .min = 1, .max = 4 },
263         .m = { .min = 104, .max = 138 },
264         .m1 = { .min = 17, .max = 23 },
265         .m2 = { .min = 5, .max = 11 },
266         .p = { .min = 10, .max = 30 },
267         .p1 = { .min = 1, .max = 3},
268         .p2 = { .dot_limit = 270000,
269                 .p2_slow = 10,
270                 .p2_fast = 10
271         },
272 };
273
274 static const struct intel_limit intel_limits_g4x_hdmi = {
275         .dot = { .min = 22000, .max = 400000 },
276         .vco = { .min = 1750000, .max = 3500000},
277         .n = { .min = 1, .max = 4 },
278         .m = { .min = 104, .max = 138 },
279         .m1 = { .min = 16, .max = 23 },
280         .m2 = { .min = 5, .max = 11 },
281         .p = { .min = 5, .max = 80 },
282         .p1 = { .min = 1, .max = 8},
283         .p2 = { .dot_limit = 165000,
284                 .p2_slow = 10, .p2_fast = 5 },
285 };
286
287 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
288         .dot = { .min = 20000, .max = 115000 },
289         .vco = { .min = 1750000, .max = 3500000 },
290         .n = { .min = 1, .max = 3 },
291         .m = { .min = 104, .max = 138 },
292         .m1 = { .min = 17, .max = 23 },
293         .m2 = { .min = 5, .max = 11 },
294         .p = { .min = 28, .max = 112 },
295         .p1 = { .min = 2, .max = 8 },
296         .p2 = { .dot_limit = 0,
297                 .p2_slow = 14, .p2_fast = 14
298         },
299 };
300
301 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
302         .dot = { .min = 80000, .max = 224000 },
303         .vco = { .min = 1750000, .max = 3500000 },
304         .n = { .min = 1, .max = 3 },
305         .m = { .min = 104, .max = 138 },
306         .m1 = { .min = 17, .max = 23 },
307         .m2 = { .min = 5, .max = 11 },
308         .p = { .min = 14, .max = 42 },
309         .p1 = { .min = 2, .max = 6 },
310         .p2 = { .dot_limit = 0,
311                 .p2_slow = 7, .p2_fast = 7
312         },
313 };
314
315 static const struct intel_limit intel_limits_pineview_sdvo = {
316         .dot = { .min = 20000, .max = 400000},
317         .vco = { .min = 1700000, .max = 3500000 },
318         /* Pineview's Ncounter is a ring counter */
319         .n = { .min = 3, .max = 6 },
320         .m = { .min = 2, .max = 256 },
321         /* Pineview only has one combined m divider, which we treat as m2. */
322         .m1 = { .min = 0, .max = 0 },
323         .m2 = { .min = 0, .max = 254 },
324         .p = { .min = 5, .max = 80 },
325         .p1 = { .min = 1, .max = 8 },
326         .p2 = { .dot_limit = 200000,
327                 .p2_slow = 10, .p2_fast = 5 },
328 };
329
330 static const struct intel_limit intel_limits_pineview_lvds = {
331         .dot = { .min = 20000, .max = 400000 },
332         .vco = { .min = 1700000, .max = 3500000 },
333         .n = { .min = 3, .max = 6 },
334         .m = { .min = 2, .max = 256 },
335         .m1 = { .min = 0, .max = 0 },
336         .m2 = { .min = 0, .max = 254 },
337         .p = { .min = 7, .max = 112 },
338         .p1 = { .min = 1, .max = 8 },
339         .p2 = { .dot_limit = 112000,
340                 .p2_slow = 14, .p2_fast = 14 },
341 };
342
343 /* Ironlake / Sandybridge
344  *
345  * We calculate clock using (register_value + 2) for N/M1/M2, so here
346  * the range value for them is (actual_value - 2).
347  */
348 static const struct intel_limit intel_limits_ironlake_dac = {
349         .dot = { .min = 25000, .max = 350000 },
350         .vco = { .min = 1760000, .max = 3510000 },
351         .n = { .min = 1, .max = 5 },
352         .m = { .min = 79, .max = 127 },
353         .m1 = { .min = 12, .max = 22 },
354         .m2 = { .min = 5, .max = 9 },
355         .p = { .min = 5, .max = 80 },
356         .p1 = { .min = 1, .max = 8 },
357         .p2 = { .dot_limit = 225000,
358                 .p2_slow = 10, .p2_fast = 5 },
359 };
360
361 static const struct intel_limit intel_limits_ironlake_single_lvds = {
362         .dot = { .min = 25000, .max = 350000 },
363         .vco = { .min = 1760000, .max = 3510000 },
364         .n = { .min = 1, .max = 3 },
365         .m = { .min = 79, .max = 118 },
366         .m1 = { .min = 12, .max = 22 },
367         .m2 = { .min = 5, .max = 9 },
368         .p = { .min = 28, .max = 112 },
369         .p1 = { .min = 2, .max = 8 },
370         .p2 = { .dot_limit = 225000,
371                 .p2_slow = 14, .p2_fast = 14 },
372 };
373
374 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
375         .dot = { .min = 25000, .max = 350000 },
376         .vco = { .min = 1760000, .max = 3510000 },
377         .n = { .min = 1, .max = 3 },
378         .m = { .min = 79, .max = 127 },
379         .m1 = { .min = 12, .max = 22 },
380         .m2 = { .min = 5, .max = 9 },
381         .p = { .min = 14, .max = 56 },
382         .p1 = { .min = 2, .max = 8 },
383         .p2 = { .dot_limit = 225000,
384                 .p2_slow = 7, .p2_fast = 7 },
385 };
386
387 /* LVDS 100mhz refclk limits. */
388 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
389         .dot = { .min = 25000, .max = 350000 },
390         .vco = { .min = 1760000, .max = 3510000 },
391         .n = { .min = 1, .max = 2 },
392         .m = { .min = 79, .max = 126 },
393         .m1 = { .min = 12, .max = 22 },
394         .m2 = { .min = 5, .max = 9 },
395         .p = { .min = 28, .max = 112 },
396         .p1 = { .min = 2, .max = 8 },
397         .p2 = { .dot_limit = 225000,
398                 .p2_slow = 14, .p2_fast = 14 },
399 };
400
401 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
402         .dot = { .min = 25000, .max = 350000 },
403         .vco = { .min = 1760000, .max = 3510000 },
404         .n = { .min = 1, .max = 3 },
405         .m = { .min = 79, .max = 126 },
406         .m1 = { .min = 12, .max = 22 },
407         .m2 = { .min = 5, .max = 9 },
408         .p = { .min = 14, .max = 42 },
409         .p1 = { .min = 2, .max = 6 },
410         .p2 = { .dot_limit = 225000,
411                 .p2_slow = 7, .p2_fast = 7 },
412 };
413
414 static const struct intel_limit intel_limits_vlv = {
415          /*
416           * These are the data rate limits (measured in fast clocks)
417           * since those are the strictest limits we have. The fast
418           * clock and actual rate limits are more relaxed, so checking
419           * them would make no difference.
420           */
421         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
422         .vco = { .min = 4000000, .max = 6000000 },
423         .n = { .min = 1, .max = 7 },
424         .m1 = { .min = 2, .max = 3 },
425         .m2 = { .min = 11, .max = 156 },
426         .p1 = { .min = 2, .max = 3 },
427         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
428 };
429
430 static const struct intel_limit intel_limits_chv = {
431         /*
432          * These are the data rate limits (measured in fast clocks)
433          * since those are the strictest limits we have.  The fast
434          * clock and actual rate limits are more relaxed, so checking
435          * them would make no difference.
436          */
437         .dot = { .min = 25000 * 5, .max = 540000 * 5},
438         .vco = { .min = 4800000, .max = 6480000 },
439         .n = { .min = 1, .max = 1 },
440         .m1 = { .min = 2, .max = 2 },
441         .m2 = { .min = 24 << 22, .max = 175 << 22 },
442         .p1 = { .min = 2, .max = 4 },
443         .p2 = { .p2_slow = 1, .p2_fast = 14 },
444 };
445
446 static const struct intel_limit intel_limits_bxt = {
447         /* FIXME: find real dot limits */
448         .dot = { .min = 0, .max = INT_MAX },
449         .vco = { .min = 4800000, .max = 6700000 },
450         .n = { .min = 1, .max = 1 },
451         .m1 = { .min = 2, .max = 2 },
452         /* FIXME: find real m2 limits */
453         .m2 = { .min = 2 << 22, .max = 255 << 22 },
454         .p1 = { .min = 2, .max = 4 },
455         .p2 = { .p2_slow = 1, .p2_fast = 20 },
456 };
457
458 static void
459 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
460 {
461         if (enable)
462                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
463                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
464         else
465                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
466                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
467                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
468 }
469
470 static bool
471 needs_modeset(const struct drm_crtc_state *state)
472 {
473         return drm_atomic_crtc_needs_modeset(state);
474 }
475
476 /*
477  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
478  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
479  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
480  * The helpers' return value is the rate of the clock that is fed to the
481  * display engine's pipe which can be the above fast dot clock rate or a
482  * divided-down version of it.
483  */
484 /* m1 is reserved as 0 in Pineview, n is a ring counter */
485 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
486 {
487         clock->m = clock->m2 + 2;
488         clock->p = clock->p1 * clock->p2;
489         if (WARN_ON(clock->n == 0 || clock->p == 0))
490                 return 0;
491         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
492         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
493
494         return clock->dot;
495 }
496
497 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
498 {
499         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
500 }
501
502 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
503 {
504         clock->m = i9xx_dpll_compute_m(clock);
505         clock->p = clock->p1 * clock->p2;
506         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
507                 return 0;
508         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
509         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
510
511         return clock->dot;
512 }
513
514 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
515 {
516         clock->m = clock->m1 * clock->m2;
517         clock->p = clock->p1 * clock->p2;
518         if (WARN_ON(clock->n == 0 || clock->p == 0))
519                 return 0;
520         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
521         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
522
523         return clock->dot / 5;
524 }
525
526 int chv_calc_dpll_params(int refclk, struct dpll *clock)
527 {
528         clock->m = clock->m1 * clock->m2;
529         clock->p = clock->p1 * clock->p2;
530         if (WARN_ON(clock->n == 0 || clock->p == 0))
531                 return 0;
532         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
533                         clock->n << 22);
534         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
535
536         return clock->dot / 5;
537 }
538
539 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
540
541 /*
542  * Returns whether the given set of divisors are valid for a given refclk with
543  * the given connectors.
544  */
545 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
546                                const struct intel_limit *limit,
547                                const struct dpll *clock)
548 {
549         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
550                 INTELPllInvalid("n out of range\n");
551         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
552                 INTELPllInvalid("p1 out of range\n");
553         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
554                 INTELPllInvalid("m2 out of range\n");
555         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
556                 INTELPllInvalid("m1 out of range\n");
557
558         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
559             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
560                 if (clock->m1 <= clock->m2)
561                         INTELPllInvalid("m1 <= m2\n");
562
563         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
564             !IS_GEN9_LP(dev_priv)) {
565                 if (clock->p < limit->p.min || limit->p.max < clock->p)
566                         INTELPllInvalid("p out of range\n");
567                 if (clock->m < limit->m.min || limit->m.max < clock->m)
568                         INTELPllInvalid("m out of range\n");
569         }
570
571         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
572                 INTELPllInvalid("vco out of range\n");
573         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
574          * connector, etc., rather than just a single range.
575          */
576         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
577                 INTELPllInvalid("dot out of range\n");
578
579         return true;
580 }
581
582 static int
583 i9xx_select_p2_div(const struct intel_limit *limit,
584                    const struct intel_crtc_state *crtc_state,
585                    int target)
586 {
587         struct drm_device *dev = crtc_state->base.crtc->dev;
588
589         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
590                 /*
591                  * For LVDS just rely on its current settings for dual-channel.
592                  * We haven't figured out how to reliably set up different
593                  * single/dual channel state, if we even can.
594                  */
595                 if (intel_is_dual_link_lvds(dev))
596                         return limit->p2.p2_fast;
597                 else
598                         return limit->p2.p2_slow;
599         } else {
600                 if (target < limit->p2.dot_limit)
601                         return limit->p2.p2_slow;
602                 else
603                         return limit->p2.p2_fast;
604         }
605 }
606
607 /*
608  * Returns a set of divisors for the desired target clock with the given
609  * refclk, or FALSE.  The returned values represent the clock equation:
610  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
611  *
612  * Target and reference clocks are specified in kHz.
613  *
614  * If match_clock is provided, then best_clock P divider must match the P
615  * divider from @match_clock used for LVDS downclocking.
616  */
617 static bool
618 i9xx_find_best_dpll(const struct intel_limit *limit,
619                     struct intel_crtc_state *crtc_state,
620                     int target, int refclk, struct dpll *match_clock,
621                     struct dpll *best_clock)
622 {
623         struct drm_device *dev = crtc_state->base.crtc->dev;
624         struct dpll clock;
625         int err = target;
626
627         memset(best_clock, 0, sizeof(*best_clock));
628
629         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
630
631         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
632              clock.m1++) {
633                 for (clock.m2 = limit->m2.min;
634                      clock.m2 <= limit->m2.max; clock.m2++) {
635                         if (clock.m2 >= clock.m1)
636                                 break;
637                         for (clock.n = limit->n.min;
638                              clock.n <= limit->n.max; clock.n++) {
639                                 for (clock.p1 = limit->p1.min;
640                                         clock.p1 <= limit->p1.max; clock.p1++) {
641                                         int this_err;
642
643                                         i9xx_calc_dpll_params(refclk, &clock);
644                                         if (!intel_PLL_is_valid(to_i915(dev),
645                                                                 limit,
646                                                                 &clock))
647                                                 continue;
648                                         if (match_clock &&
649                                             clock.p != match_clock->p)
650                                                 continue;
651
652                                         this_err = abs(clock.dot - target);
653                                         if (this_err < err) {
654                                                 *best_clock = clock;
655                                                 err = this_err;
656                                         }
657                                 }
658                         }
659                 }
660         }
661
662         return (err != target);
663 }
664
665 /*
666  * Returns a set of divisors for the desired target clock with the given
667  * refclk, or FALSE.  The returned values represent the clock equation:
668  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
669  *
670  * Target and reference clocks are specified in kHz.
671  *
672  * If match_clock is provided, then best_clock P divider must match the P
673  * divider from @match_clock used for LVDS downclocking.
674  */
675 static bool
676 pnv_find_best_dpll(const struct intel_limit *limit,
677                    struct intel_crtc_state *crtc_state,
678                    int target, int refclk, struct dpll *match_clock,
679                    struct dpll *best_clock)
680 {
681         struct drm_device *dev = crtc_state->base.crtc->dev;
682         struct dpll clock;
683         int err = target;
684
685         memset(best_clock, 0, sizeof(*best_clock));
686
687         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
688
689         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
690              clock.m1++) {
691                 for (clock.m2 = limit->m2.min;
692                      clock.m2 <= limit->m2.max; clock.m2++) {
693                         for (clock.n = limit->n.min;
694                              clock.n <= limit->n.max; clock.n++) {
695                                 for (clock.p1 = limit->p1.min;
696                                         clock.p1 <= limit->p1.max; clock.p1++) {
697                                         int this_err;
698
699                                         pnv_calc_dpll_params(refclk, &clock);
700                                         if (!intel_PLL_is_valid(to_i915(dev),
701                                                                 limit,
702                                                                 &clock))
703                                                 continue;
704                                         if (match_clock &&
705                                             clock.p != match_clock->p)
706                                                 continue;
707
708                                         this_err = abs(clock.dot - target);
709                                         if (this_err < err) {
710                                                 *best_clock = clock;
711                                                 err = this_err;
712                                         }
713                                 }
714                         }
715                 }
716         }
717
718         return (err != target);
719 }
720
721 /*
722  * Returns a set of divisors for the desired target clock with the given
723  * refclk, or FALSE.  The returned values represent the clock equation:
724  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
725  *
726  * Target and reference clocks are specified in kHz.
727  *
728  * If match_clock is provided, then best_clock P divider must match the P
729  * divider from @match_clock used for LVDS downclocking.
730  */
731 static bool
732 g4x_find_best_dpll(const struct intel_limit *limit,
733                    struct intel_crtc_state *crtc_state,
734                    int target, int refclk, struct dpll *match_clock,
735                    struct dpll *best_clock)
736 {
737         struct drm_device *dev = crtc_state->base.crtc->dev;
738         struct dpll clock;
739         int max_n;
740         bool found = false;
741         /* approximately equals target * 0.00585 */
742         int err_most = (target >> 8) + (target >> 9);
743
744         memset(best_clock, 0, sizeof(*best_clock));
745
746         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
747
748         max_n = limit->n.max;
749         /* based on hardware requirement, prefer smaller n to precision */
750         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
751                 /* based on hardware requirement, prefere larger m1,m2 */
752                 for (clock.m1 = limit->m1.max;
753                      clock.m1 >= limit->m1.min; clock.m1--) {
754                         for (clock.m2 = limit->m2.max;
755                              clock.m2 >= limit->m2.min; clock.m2--) {
756                                 for (clock.p1 = limit->p1.max;
757                                      clock.p1 >= limit->p1.min; clock.p1--) {
758                                         int this_err;
759
760                                         i9xx_calc_dpll_params(refclk, &clock);
761                                         if (!intel_PLL_is_valid(to_i915(dev),
762                                                                 limit,
763                                                                 &clock))
764                                                 continue;
765
766                                         this_err = abs(clock.dot - target);
767                                         if (this_err < err_most) {
768                                                 *best_clock = clock;
769                                                 err_most = this_err;
770                                                 max_n = clock.n;
771                                                 found = true;
772                                         }
773                                 }
774                         }
775                 }
776         }
777         return found;
778 }
779
780 /*
781  * Check if the calculated PLL configuration is more optimal compared to the
782  * best configuration and error found so far. Return the calculated error.
783  */
784 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
785                                const struct dpll *calculated_clock,
786                                const struct dpll *best_clock,
787                                unsigned int best_error_ppm,
788                                unsigned int *error_ppm)
789 {
790         /*
791          * For CHV ignore the error and consider only the P value.
792          * Prefer a bigger P value based on HW requirements.
793          */
794         if (IS_CHERRYVIEW(to_i915(dev))) {
795                 *error_ppm = 0;
796
797                 return calculated_clock->p > best_clock->p;
798         }
799
800         if (WARN_ON_ONCE(!target_freq))
801                 return false;
802
803         *error_ppm = div_u64(1000000ULL *
804                                 abs(target_freq - calculated_clock->dot),
805                              target_freq);
806         /*
807          * Prefer a better P value over a better (smaller) error if the error
808          * is small. Ensure this preference for future configurations too by
809          * setting the error to 0.
810          */
811         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
812                 *error_ppm = 0;
813
814                 return true;
815         }
816
817         return *error_ppm + 10 < best_error_ppm;
818 }
819
820 /*
821  * Returns a set of divisors for the desired target clock with the given
822  * refclk, or FALSE.  The returned values represent the clock equation:
823  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
824  */
825 static bool
826 vlv_find_best_dpll(const struct intel_limit *limit,
827                    struct intel_crtc_state *crtc_state,
828                    int target, int refclk, struct dpll *match_clock,
829                    struct dpll *best_clock)
830 {
831         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
832         struct drm_device *dev = crtc->base.dev;
833         struct dpll clock;
834         unsigned int bestppm = 1000000;
835         /* min update 19.2 MHz */
836         int max_n = min(limit->n.max, refclk / 19200);
837         bool found = false;
838
839         target *= 5; /* fast clock */
840
841         memset(best_clock, 0, sizeof(*best_clock));
842
843         /* based on hardware requirement, prefer smaller n to precision */
844         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
845                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
846                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
847                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
848                                 clock.p = clock.p1 * clock.p2;
849                                 /* based on hardware requirement, prefer bigger m1,m2 values */
850                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
851                                         unsigned int ppm;
852
853                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
854                                                                      refclk * clock.m1);
855
856                                         vlv_calc_dpll_params(refclk, &clock);
857
858                                         if (!intel_PLL_is_valid(to_i915(dev),
859                                                                 limit,
860                                                                 &clock))
861                                                 continue;
862
863                                         if (!vlv_PLL_is_optimal(dev, target,
864                                                                 &clock,
865                                                                 best_clock,
866                                                                 bestppm, &ppm))
867                                                 continue;
868
869                                         *best_clock = clock;
870                                         bestppm = ppm;
871                                         found = true;
872                                 }
873                         }
874                 }
875         }
876
877         return found;
878 }
879
880 /*
881  * Returns a set of divisors for the desired target clock with the given
882  * refclk, or FALSE.  The returned values represent the clock equation:
883  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
884  */
885 static bool
886 chv_find_best_dpll(const struct intel_limit *limit,
887                    struct intel_crtc_state *crtc_state,
888                    int target, int refclk, struct dpll *match_clock,
889                    struct dpll *best_clock)
890 {
891         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
892         struct drm_device *dev = crtc->base.dev;
893         unsigned int best_error_ppm;
894         struct dpll clock;
895         uint64_t m2;
896         int found = false;
897
898         memset(best_clock, 0, sizeof(*best_clock));
899         best_error_ppm = 1000000;
900
901         /*
902          * Based on hardware doc, the n always set to 1, and m1 always
903          * set to 2.  If requires to support 200Mhz refclk, we need to
904          * revisit this because n may not 1 anymore.
905          */
906         clock.n = 1, clock.m1 = 2;
907         target *= 5;    /* fast clock */
908
909         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
910                 for (clock.p2 = limit->p2.p2_fast;
911                                 clock.p2 >= limit->p2.p2_slow;
912                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
913                         unsigned int error_ppm;
914
915                         clock.p = clock.p1 * clock.p2;
916
917                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
918                                         clock.n) << 22, refclk * clock.m1);
919
920                         if (m2 > INT_MAX/clock.m1)
921                                 continue;
922
923                         clock.m2 = m2;
924
925                         chv_calc_dpll_params(refclk, &clock);
926
927                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
928                                 continue;
929
930                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
931                                                 best_error_ppm, &error_ppm))
932                                 continue;
933
934                         *best_clock = clock;
935                         best_error_ppm = error_ppm;
936                         found = true;
937                 }
938         }
939
940         return found;
941 }
942
943 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
944                         struct dpll *best_clock)
945 {
946         int refclk = 100000;
947         const struct intel_limit *limit = &intel_limits_bxt;
948
949         return chv_find_best_dpll(limit, crtc_state,
950                                   target_clock, refclk, NULL, best_clock);
951 }
952
953 bool intel_crtc_active(struct intel_crtc *crtc)
954 {
955         /* Be paranoid as we can arrive here with only partial
956          * state retrieved from the hardware during setup.
957          *
958          * We can ditch the adjusted_mode.crtc_clock check as soon
959          * as Haswell has gained clock readout/fastboot support.
960          *
961          * We can ditch the crtc->primary->state->fb check as soon as we can
962          * properly reconstruct framebuffers.
963          *
964          * FIXME: The intel_crtc->active here should be switched to
965          * crtc->state->active once we have proper CRTC states wired up
966          * for atomic.
967          */
968         return crtc->active && crtc->base.primary->state->fb &&
969                 crtc->config->base.adjusted_mode.crtc_clock;
970 }
971
972 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
973                                              enum pipe pipe)
974 {
975         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
976
977         return crtc->config->cpu_transcoder;
978 }
979
980 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
981                                     enum pipe pipe)
982 {
983         i915_reg_t reg = PIPEDSL(pipe);
984         u32 line1, line2;
985         u32 line_mask;
986
987         if (IS_GEN2(dev_priv))
988                 line_mask = DSL_LINEMASK_GEN2;
989         else
990                 line_mask = DSL_LINEMASK_GEN3;
991
992         line1 = I915_READ(reg) & line_mask;
993         msleep(5);
994         line2 = I915_READ(reg) & line_mask;
995
996         return line1 != line2;
997 }
998
999 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1000 {
1001         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1002         enum pipe pipe = crtc->pipe;
1003
1004         /* Wait for the display line to settle/start moving */
1005         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1006                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1007                           pipe_name(pipe), onoff(state));
1008 }
1009
1010 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1011 {
1012         wait_for_pipe_scanline_moving(crtc, false);
1013 }
1014
1015 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1016 {
1017         wait_for_pipe_scanline_moving(crtc, true);
1018 }
1019
1020 static void
1021 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1022 {
1023         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1024         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1025
1026         if (INTEL_GEN(dev_priv) >= 4) {
1027                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1028                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1029
1030                 /* Wait for the Pipe State to go off */
1031                 if (intel_wait_for_register(dev_priv,
1032                                             reg, I965_PIPECONF_ACTIVE, 0,
1033                                             100))
1034                         WARN(1, "pipe_off wait timed out\n");
1035         } else {
1036                 intel_wait_for_pipe_scanline_stopped(crtc);
1037         }
1038 }
1039
1040 /* Only for pre-ILK configs */
1041 void assert_pll(struct drm_i915_private *dev_priv,
1042                 enum pipe pipe, bool state)
1043 {
1044         u32 val;
1045         bool cur_state;
1046
1047         val = I915_READ(DPLL(pipe));
1048         cur_state = !!(val & DPLL_VCO_ENABLE);
1049         I915_STATE_WARN(cur_state != state,
1050              "PLL state assertion failure (expected %s, current %s)\n",
1051                         onoff(state), onoff(cur_state));
1052 }
1053
1054 /* XXX: the dsi pll is shared between MIPI DSI ports */
1055 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1056 {
1057         u32 val;
1058         bool cur_state;
1059
1060         mutex_lock(&dev_priv->sb_lock);
1061         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1062         mutex_unlock(&dev_priv->sb_lock);
1063
1064         cur_state = val & DSI_PLL_VCO_EN;
1065         I915_STATE_WARN(cur_state != state,
1066              "DSI PLL state assertion failure (expected %s, current %s)\n",
1067                         onoff(state), onoff(cur_state));
1068 }
1069
1070 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1071                           enum pipe pipe, bool state)
1072 {
1073         bool cur_state;
1074         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1075                                                                       pipe);
1076
1077         if (HAS_DDI(dev_priv)) {
1078                 /* DDI does not have a specific FDI_TX register */
1079                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1080                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1081         } else {
1082                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1083                 cur_state = !!(val & FDI_TX_ENABLE);
1084         }
1085         I915_STATE_WARN(cur_state != state,
1086              "FDI TX state assertion failure (expected %s, current %s)\n",
1087                         onoff(state), onoff(cur_state));
1088 }
1089 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1090 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1091
1092 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1093                           enum pipe pipe, bool state)
1094 {
1095         u32 val;
1096         bool cur_state;
1097
1098         val = I915_READ(FDI_RX_CTL(pipe));
1099         cur_state = !!(val & FDI_RX_ENABLE);
1100         I915_STATE_WARN(cur_state != state,
1101              "FDI RX state assertion failure (expected %s, current %s)\n",
1102                         onoff(state), onoff(cur_state));
1103 }
1104 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1105 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1106
1107 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1108                                       enum pipe pipe)
1109 {
1110         u32 val;
1111
1112         /* ILK FDI PLL is always enabled */
1113         if (IS_GEN5(dev_priv))
1114                 return;
1115
1116         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1117         if (HAS_DDI(dev_priv))
1118                 return;
1119
1120         val = I915_READ(FDI_TX_CTL(pipe));
1121         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1122 }
1123
1124 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1125                        enum pipe pipe, bool state)
1126 {
1127         u32 val;
1128         bool cur_state;
1129
1130         val = I915_READ(FDI_RX_CTL(pipe));
1131         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1132         I915_STATE_WARN(cur_state != state,
1133              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1134                         onoff(state), onoff(cur_state));
1135 }
1136
1137 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1138 {
1139         i915_reg_t pp_reg;
1140         u32 val;
1141         enum pipe panel_pipe = INVALID_PIPE;
1142         bool locked = true;
1143
1144         if (WARN_ON(HAS_DDI(dev_priv)))
1145                 return;
1146
1147         if (HAS_PCH_SPLIT(dev_priv)) {
1148                 u32 port_sel;
1149
1150                 pp_reg = PP_CONTROL(0);
1151                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1152
1153                 switch (port_sel) {
1154                 case PANEL_PORT_SELECT_LVDS:
1155                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1156                         break;
1157                 case PANEL_PORT_SELECT_DPA:
1158                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1159                         break;
1160                 case PANEL_PORT_SELECT_DPC:
1161                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1162                         break;
1163                 case PANEL_PORT_SELECT_DPD:
1164                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1165                         break;
1166                 default:
1167                         MISSING_CASE(port_sel);
1168                         break;
1169                 }
1170         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1171                 /* presumably write lock depends on pipe, not port select */
1172                 pp_reg = PP_CONTROL(pipe);
1173                 panel_pipe = pipe;
1174         } else {
1175                 u32 port_sel;
1176
1177                 pp_reg = PP_CONTROL(0);
1178                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1179
1180                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1181                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1182         }
1183
1184         val = I915_READ(pp_reg);
1185         if (!(val & PANEL_POWER_ON) ||
1186             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1187                 locked = false;
1188
1189         I915_STATE_WARN(panel_pipe == pipe && locked,
1190              "panel assertion failure, pipe %c regs locked\n",
1191              pipe_name(pipe));
1192 }
1193
1194 void assert_pipe(struct drm_i915_private *dev_priv,
1195                  enum pipe pipe, bool state)
1196 {
1197         bool cur_state;
1198         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1199                                                                       pipe);
1200         enum intel_display_power_domain power_domain;
1201
1202         /* we keep both pipes enabled on 830 */
1203         if (IS_I830(dev_priv))
1204                 state = true;
1205
1206         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1207         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1208                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1209                 cur_state = !!(val & PIPECONF_ENABLE);
1210
1211                 intel_display_power_put(dev_priv, power_domain);
1212         } else {
1213                 cur_state = false;
1214         }
1215
1216         I915_STATE_WARN(cur_state != state,
1217              "pipe %c assertion failure (expected %s, current %s)\n",
1218                         pipe_name(pipe), onoff(state), onoff(cur_state));
1219 }
1220
1221 static void assert_plane(struct intel_plane *plane, bool state)
1222 {
1223         enum pipe pipe;
1224         bool cur_state;
1225
1226         cur_state = plane->get_hw_state(plane, &pipe);
1227
1228         I915_STATE_WARN(cur_state != state,
1229                         "%s assertion failure (expected %s, current %s)\n",
1230                         plane->base.name, onoff(state), onoff(cur_state));
1231 }
1232
1233 #define assert_plane_enabled(p) assert_plane(p, true)
1234 #define assert_plane_disabled(p) assert_plane(p, false)
1235
1236 static void assert_planes_disabled(struct intel_crtc *crtc)
1237 {
1238         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1239         struct intel_plane *plane;
1240
1241         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1242                 assert_plane_disabled(plane);
1243 }
1244
1245 static void assert_vblank_disabled(struct drm_crtc *crtc)
1246 {
1247         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1248                 drm_crtc_vblank_put(crtc);
1249 }
1250
1251 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1252                                     enum pipe pipe)
1253 {
1254         u32 val;
1255         bool enabled;
1256
1257         val = I915_READ(PCH_TRANSCONF(pipe));
1258         enabled = !!(val & TRANS_ENABLE);
1259         I915_STATE_WARN(enabled,
1260              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1261              pipe_name(pipe));
1262 }
1263
1264 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1265                                    enum pipe pipe, enum port port,
1266                                    i915_reg_t dp_reg)
1267 {
1268         enum pipe port_pipe;
1269         bool state;
1270
1271         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1272
1273         I915_STATE_WARN(state && port_pipe == pipe,
1274                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1275                         port_name(port), pipe_name(pipe));
1276
1277         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1278                         "IBX PCH DP %c still using transcoder B\n",
1279                         port_name(port));
1280 }
1281
1282 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1283                                      enum pipe pipe, enum port port,
1284                                      i915_reg_t hdmi_reg)
1285 {
1286         enum pipe port_pipe;
1287         bool state;
1288
1289         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1290
1291         I915_STATE_WARN(state && port_pipe == pipe,
1292                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1293                         port_name(port), pipe_name(pipe));
1294
1295         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1296                         "IBX PCH HDMI %c still using transcoder B\n",
1297                         port_name(port));
1298 }
1299
1300 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1301                                       enum pipe pipe)
1302 {
1303         enum pipe port_pipe;
1304
1305         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1306         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1307         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1308
1309         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1310                         port_pipe == pipe,
1311                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1312                         pipe_name(pipe));
1313
1314         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1315                         port_pipe == pipe,
1316                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1317                         pipe_name(pipe));
1318
1319         /* PCH SDVOB multiplex with HDMIB */
1320         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1321         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1322         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1323 }
1324
1325 static void _vlv_enable_pll(struct intel_crtc *crtc,
1326                             const struct intel_crtc_state *pipe_config)
1327 {
1328         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1329         enum pipe pipe = crtc->pipe;
1330
1331         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1332         POSTING_READ(DPLL(pipe));
1333         udelay(150);
1334
1335         if (intel_wait_for_register(dev_priv,
1336                                     DPLL(pipe),
1337                                     DPLL_LOCK_VLV,
1338                                     DPLL_LOCK_VLV,
1339                                     1))
1340                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1341 }
1342
1343 static void vlv_enable_pll(struct intel_crtc *crtc,
1344                            const struct intel_crtc_state *pipe_config)
1345 {
1346         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1347         enum pipe pipe = crtc->pipe;
1348
1349         assert_pipe_disabled(dev_priv, pipe);
1350
1351         /* PLL is protected by panel, make sure we can write it */
1352         assert_panel_unlocked(dev_priv, pipe);
1353
1354         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1355                 _vlv_enable_pll(crtc, pipe_config);
1356
1357         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1358         POSTING_READ(DPLL_MD(pipe));
1359 }
1360
1361
1362 static void _chv_enable_pll(struct intel_crtc *crtc,
1363                             const struct intel_crtc_state *pipe_config)
1364 {
1365         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1366         enum pipe pipe = crtc->pipe;
1367         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1368         u32 tmp;
1369
1370         mutex_lock(&dev_priv->sb_lock);
1371
1372         /* Enable back the 10bit clock to display controller */
1373         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1374         tmp |= DPIO_DCLKP_EN;
1375         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1376
1377         mutex_unlock(&dev_priv->sb_lock);
1378
1379         /*
1380          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1381          */
1382         udelay(1);
1383
1384         /* Enable PLL */
1385         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1386
1387         /* Check PLL is locked */
1388         if (intel_wait_for_register(dev_priv,
1389                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1390                                     1))
1391                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1392 }
1393
1394 static void chv_enable_pll(struct intel_crtc *crtc,
1395                            const struct intel_crtc_state *pipe_config)
1396 {
1397         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1398         enum pipe pipe = crtc->pipe;
1399
1400         assert_pipe_disabled(dev_priv, pipe);
1401
1402         /* PLL is protected by panel, make sure we can write it */
1403         assert_panel_unlocked(dev_priv, pipe);
1404
1405         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1406                 _chv_enable_pll(crtc, pipe_config);
1407
1408         if (pipe != PIPE_A) {
1409                 /*
1410                  * WaPixelRepeatModeFixForC0:chv
1411                  *
1412                  * DPLLCMD is AWOL. Use chicken bits to propagate
1413                  * the value from DPLLBMD to either pipe B or C.
1414                  */
1415                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1416                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1417                 I915_WRITE(CBR4_VLV, 0);
1418                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1419
1420                 /*
1421                  * DPLLB VGA mode also seems to cause problems.
1422                  * We should always have it disabled.
1423                  */
1424                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1425         } else {
1426                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1427                 POSTING_READ(DPLL_MD(pipe));
1428         }
1429 }
1430
1431 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1432 {
1433         struct intel_crtc *crtc;
1434         int count = 0;
1435
1436         for_each_intel_crtc(&dev_priv->drm, crtc) {
1437                 count += crtc->base.state->active &&
1438                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1439         }
1440
1441         return count;
1442 }
1443
1444 static void i9xx_enable_pll(struct intel_crtc *crtc,
1445                             const struct intel_crtc_state *crtc_state)
1446 {
1447         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1448         i915_reg_t reg = DPLL(crtc->pipe);
1449         u32 dpll = crtc_state->dpll_hw_state.dpll;
1450         int i;
1451
1452         assert_pipe_disabled(dev_priv, crtc->pipe);
1453
1454         /* PLL is protected by panel, make sure we can write it */
1455         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1456                 assert_panel_unlocked(dev_priv, crtc->pipe);
1457
1458         /* Enable DVO 2x clock on both PLLs if necessary */
1459         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1460                 /*
1461                  * It appears to be important that we don't enable this
1462                  * for the current pipe before otherwise configuring the
1463                  * PLL. No idea how this should be handled if multiple
1464                  * DVO outputs are enabled simultaneosly.
1465                  */
1466                 dpll |= DPLL_DVO_2X_MODE;
1467                 I915_WRITE(DPLL(!crtc->pipe),
1468                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1469         }
1470
1471         /*
1472          * Apparently we need to have VGA mode enabled prior to changing
1473          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1474          * dividers, even though the register value does change.
1475          */
1476         I915_WRITE(reg, 0);
1477
1478         I915_WRITE(reg, dpll);
1479
1480         /* Wait for the clocks to stabilize. */
1481         POSTING_READ(reg);
1482         udelay(150);
1483
1484         if (INTEL_GEN(dev_priv) >= 4) {
1485                 I915_WRITE(DPLL_MD(crtc->pipe),
1486                            crtc_state->dpll_hw_state.dpll_md);
1487         } else {
1488                 /* The pixel multiplier can only be updated once the
1489                  * DPLL is enabled and the clocks are stable.
1490                  *
1491                  * So write it again.
1492                  */
1493                 I915_WRITE(reg, dpll);
1494         }
1495
1496         /* We do this three times for luck */
1497         for (i = 0; i < 3; i++) {
1498                 I915_WRITE(reg, dpll);
1499                 POSTING_READ(reg);
1500                 udelay(150); /* wait for warmup */
1501         }
1502 }
1503
1504 static void i9xx_disable_pll(const struct intel_crtc_state *crtc_state)
1505 {
1506         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1507         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1508         enum pipe pipe = crtc->pipe;
1509
1510         /* Disable DVO 2x clock on both PLLs if necessary */
1511         if (IS_I830(dev_priv) &&
1512             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO) &&
1513             !intel_num_dvo_pipes(dev_priv)) {
1514                 I915_WRITE(DPLL(PIPE_B),
1515                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1516                 I915_WRITE(DPLL(PIPE_A),
1517                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1518         }
1519
1520         /* Don't disable pipe or pipe PLLs if needed */
1521         if (IS_I830(dev_priv))
1522                 return;
1523
1524         /* Make sure the pipe isn't still relying on us */
1525         assert_pipe_disabled(dev_priv, pipe);
1526
1527         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1528         POSTING_READ(DPLL(pipe));
1529 }
1530
1531 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1532 {
1533         u32 val;
1534
1535         /* Make sure the pipe isn't still relying on us */
1536         assert_pipe_disabled(dev_priv, pipe);
1537
1538         val = DPLL_INTEGRATED_REF_CLK_VLV |
1539                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1540         if (pipe != PIPE_A)
1541                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1542
1543         I915_WRITE(DPLL(pipe), val);
1544         POSTING_READ(DPLL(pipe));
1545 }
1546
1547 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1548 {
1549         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1550         u32 val;
1551
1552         /* Make sure the pipe isn't still relying on us */
1553         assert_pipe_disabled(dev_priv, pipe);
1554
1555         val = DPLL_SSC_REF_CLK_CHV |
1556                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1557         if (pipe != PIPE_A)
1558                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1559
1560         I915_WRITE(DPLL(pipe), val);
1561         POSTING_READ(DPLL(pipe));
1562
1563         mutex_lock(&dev_priv->sb_lock);
1564
1565         /* Disable 10bit clock to display controller */
1566         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1567         val &= ~DPIO_DCLKP_EN;
1568         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1569
1570         mutex_unlock(&dev_priv->sb_lock);
1571 }
1572
1573 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1574                          struct intel_digital_port *dport,
1575                          unsigned int expected_mask)
1576 {
1577         u32 port_mask;
1578         i915_reg_t dpll_reg;
1579
1580         switch (dport->base.port) {
1581         case PORT_B:
1582                 port_mask = DPLL_PORTB_READY_MASK;
1583                 dpll_reg = DPLL(0);
1584                 break;
1585         case PORT_C:
1586                 port_mask = DPLL_PORTC_READY_MASK;
1587                 dpll_reg = DPLL(0);
1588                 expected_mask <<= 4;
1589                 break;
1590         case PORT_D:
1591                 port_mask = DPLL_PORTD_READY_MASK;
1592                 dpll_reg = DPIO_PHY_STATUS;
1593                 break;
1594         default:
1595                 BUG();
1596         }
1597
1598         if (intel_wait_for_register(dev_priv,
1599                                     dpll_reg, port_mask, expected_mask,
1600                                     1000))
1601                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1602                      port_name(dport->base.port),
1603                      I915_READ(dpll_reg) & port_mask, expected_mask);
1604 }
1605
1606 static void ironlake_enable_pch_transcoder(const struct intel_crtc_state *crtc_state)
1607 {
1608         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1609         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1610         enum pipe pipe = crtc->pipe;
1611         i915_reg_t reg;
1612         uint32_t val, pipeconf_val;
1613
1614         /* Make sure PCH DPLL is enabled */
1615         assert_shared_dpll_enabled(dev_priv, crtc_state->shared_dpll);
1616
1617         /* FDI must be feeding us bits for PCH ports */
1618         assert_fdi_tx_enabled(dev_priv, pipe);
1619         assert_fdi_rx_enabled(dev_priv, pipe);
1620
1621         if (HAS_PCH_CPT(dev_priv)) {
1622                 /* Workaround: Set the timing override bit before enabling the
1623                  * pch transcoder. */
1624                 reg = TRANS_CHICKEN2(pipe);
1625                 val = I915_READ(reg);
1626                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1627                 I915_WRITE(reg, val);
1628         }
1629
1630         reg = PCH_TRANSCONF(pipe);
1631         val = I915_READ(reg);
1632         pipeconf_val = I915_READ(PIPECONF(pipe));
1633
1634         if (HAS_PCH_IBX(dev_priv)) {
1635                 /*
1636                  * Make the BPC in transcoder be consistent with
1637                  * that in pipeconf reg. For HDMI we must use 8bpc
1638                  * here for both 8bpc and 12bpc.
1639                  */
1640                 val &= ~PIPECONF_BPC_MASK;
1641                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
1642                         val |= PIPECONF_8BPC;
1643                 else
1644                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1645         }
1646
1647         val &= ~TRANS_INTERLACE_MASK;
1648         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1649                 if (HAS_PCH_IBX(dev_priv) &&
1650                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
1651                         val |= TRANS_LEGACY_INTERLACED_ILK;
1652                 else
1653                         val |= TRANS_INTERLACED;
1654         else
1655                 val |= TRANS_PROGRESSIVE;
1656
1657         I915_WRITE(reg, val | TRANS_ENABLE);
1658         if (intel_wait_for_register(dev_priv,
1659                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1660                                     100))
1661                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1662 }
1663
1664 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1665                                       enum transcoder cpu_transcoder)
1666 {
1667         u32 val, pipeconf_val;
1668
1669         /* FDI must be feeding us bits for PCH ports */
1670         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1671         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1672
1673         /* Workaround: set timing override bit. */
1674         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1675         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1676         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1677
1678         val = TRANS_ENABLE;
1679         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1680
1681         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1682             PIPECONF_INTERLACED_ILK)
1683                 val |= TRANS_INTERLACED;
1684         else
1685                 val |= TRANS_PROGRESSIVE;
1686
1687         I915_WRITE(LPT_TRANSCONF, val);
1688         if (intel_wait_for_register(dev_priv,
1689                                     LPT_TRANSCONF,
1690                                     TRANS_STATE_ENABLE,
1691                                     TRANS_STATE_ENABLE,
1692                                     100))
1693                 DRM_ERROR("Failed to enable PCH transcoder\n");
1694 }
1695
1696 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1697                                             enum pipe pipe)
1698 {
1699         i915_reg_t reg;
1700         uint32_t val;
1701
1702         /* FDI relies on the transcoder */
1703         assert_fdi_tx_disabled(dev_priv, pipe);
1704         assert_fdi_rx_disabled(dev_priv, pipe);
1705
1706         /* Ports must be off as well */
1707         assert_pch_ports_disabled(dev_priv, pipe);
1708
1709         reg = PCH_TRANSCONF(pipe);
1710         val = I915_READ(reg);
1711         val &= ~TRANS_ENABLE;
1712         I915_WRITE(reg, val);
1713         /* wait for PCH transcoder off, transcoder state */
1714         if (intel_wait_for_register(dev_priv,
1715                                     reg, TRANS_STATE_ENABLE, 0,
1716                                     50))
1717                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1718
1719         if (HAS_PCH_CPT(dev_priv)) {
1720                 /* Workaround: Clear the timing override chicken bit again. */
1721                 reg = TRANS_CHICKEN2(pipe);
1722                 val = I915_READ(reg);
1723                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1724                 I915_WRITE(reg, val);
1725         }
1726 }
1727
1728 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1729 {
1730         u32 val;
1731
1732         val = I915_READ(LPT_TRANSCONF);
1733         val &= ~TRANS_ENABLE;
1734         I915_WRITE(LPT_TRANSCONF, val);
1735         /* wait for PCH transcoder off, transcoder state */
1736         if (intel_wait_for_register(dev_priv,
1737                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1738                                     50))
1739                 DRM_ERROR("Failed to disable PCH transcoder\n");
1740
1741         /* Workaround: clear timing override bit. */
1742         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1743         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1744         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1745 }
1746
1747 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1748 {
1749         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1750
1751         if (HAS_PCH_LPT(dev_priv))
1752                 return PIPE_A;
1753         else
1754                 return crtc->pipe;
1755 }
1756
1757 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1758 {
1759         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1760         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1761         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1762         enum pipe pipe = crtc->pipe;
1763         i915_reg_t reg;
1764         u32 val;
1765
1766         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1767
1768         assert_planes_disabled(crtc);
1769
1770         /*
1771          * A pipe without a PLL won't actually be able to drive bits from
1772          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1773          * need the check.
1774          */
1775         if (HAS_GMCH_DISPLAY(dev_priv)) {
1776                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1777                         assert_dsi_pll_enabled(dev_priv);
1778                 else
1779                         assert_pll_enabled(dev_priv, pipe);
1780         } else {
1781                 if (new_crtc_state->has_pch_encoder) {
1782                         /* if driving the PCH, we need FDI enabled */
1783                         assert_fdi_rx_pll_enabled(dev_priv,
1784                                                   intel_crtc_pch_transcoder(crtc));
1785                         assert_fdi_tx_pll_enabled(dev_priv,
1786                                                   (enum pipe) cpu_transcoder);
1787                 }
1788                 /* FIXME: assert CPU port conditions for SNB+ */
1789         }
1790
1791         reg = PIPECONF(cpu_transcoder);
1792         val = I915_READ(reg);
1793         if (val & PIPECONF_ENABLE) {
1794                 /* we keep both pipes enabled on 830 */
1795                 WARN_ON(!IS_I830(dev_priv));
1796                 return;
1797         }
1798
1799         I915_WRITE(reg, val | PIPECONF_ENABLE);
1800         POSTING_READ(reg);
1801
1802         /*
1803          * Until the pipe starts PIPEDSL reads will return a stale value,
1804          * which causes an apparent vblank timestamp jump when PIPEDSL
1805          * resets to its proper value. That also messes up the frame count
1806          * when it's derived from the timestamps. So let's wait for the
1807          * pipe to start properly before we call drm_crtc_vblank_on()
1808          */
1809         if (dev_priv->drm.max_vblank_count == 0)
1810                 intel_wait_for_pipe_scanline_moving(crtc);
1811 }
1812
1813 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1814 {
1815         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1816         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1817         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1818         enum pipe pipe = crtc->pipe;
1819         i915_reg_t reg;
1820         u32 val;
1821
1822         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1823
1824         /*
1825          * Make sure planes won't keep trying to pump pixels to us,
1826          * or we might hang the display.
1827          */
1828         assert_planes_disabled(crtc);
1829
1830         reg = PIPECONF(cpu_transcoder);
1831         val = I915_READ(reg);
1832         if ((val & PIPECONF_ENABLE) == 0)
1833                 return;
1834
1835         /*
1836          * Double wide has implications for planes
1837          * so best keep it disabled when not needed.
1838          */
1839         if (old_crtc_state->double_wide)
1840                 val &= ~PIPECONF_DOUBLE_WIDE;
1841
1842         /* Don't disable pipe or pipe PLLs if needed */
1843         if (!IS_I830(dev_priv))
1844                 val &= ~PIPECONF_ENABLE;
1845
1846         I915_WRITE(reg, val);
1847         if ((val & PIPECONF_ENABLE) == 0)
1848                 intel_wait_for_pipe_off(old_crtc_state);
1849 }
1850
1851 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1852 {
1853         return IS_GEN2(dev_priv) ? 2048 : 4096;
1854 }
1855
1856 static unsigned int
1857 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1858 {
1859         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1860         unsigned int cpp = fb->format->cpp[color_plane];
1861
1862         switch (fb->modifier) {
1863         case DRM_FORMAT_MOD_LINEAR:
1864                 return cpp;
1865         case I915_FORMAT_MOD_X_TILED:
1866                 if (IS_GEN2(dev_priv))
1867                         return 128;
1868                 else
1869                         return 512;
1870         case I915_FORMAT_MOD_Y_TILED_CCS:
1871                 if (color_plane == 1)
1872                         return 128;
1873                 /* fall through */
1874         case I915_FORMAT_MOD_Y_TILED:
1875                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1876                         return 128;
1877                 else
1878                         return 512;
1879         case I915_FORMAT_MOD_Yf_TILED_CCS:
1880                 if (color_plane == 1)
1881                         return 128;
1882                 /* fall through */
1883         case I915_FORMAT_MOD_Yf_TILED:
1884                 switch (cpp) {
1885                 case 1:
1886                         return 64;
1887                 case 2:
1888                 case 4:
1889                         return 128;
1890                 case 8:
1891                 case 16:
1892                         return 256;
1893                 default:
1894                         MISSING_CASE(cpp);
1895                         return cpp;
1896                 }
1897                 break;
1898         default:
1899                 MISSING_CASE(fb->modifier);
1900                 return cpp;
1901         }
1902 }
1903
1904 static unsigned int
1905 intel_tile_height(const struct drm_framebuffer *fb, int color_plane)
1906 {
1907         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1908                 return 1;
1909         else
1910                 return intel_tile_size(to_i915(fb->dev)) /
1911                         intel_tile_width_bytes(fb, color_plane);
1912 }
1913
1914 /* Return the tile dimensions in pixel units */
1915 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1916                             unsigned int *tile_width,
1917                             unsigned int *tile_height)
1918 {
1919         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1920         unsigned int cpp = fb->format->cpp[color_plane];
1921
1922         *tile_width = tile_width_bytes / cpp;
1923         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1924 }
1925
1926 unsigned int
1927 intel_fb_align_height(const struct drm_framebuffer *fb,
1928                       int color_plane, unsigned int height)
1929 {
1930         unsigned int tile_height = intel_tile_height(fb, color_plane);
1931
1932         return ALIGN(height, tile_height);
1933 }
1934
1935 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1936 {
1937         unsigned int size = 0;
1938         int i;
1939
1940         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1941                 size += rot_info->plane[i].width * rot_info->plane[i].height;
1942
1943         return size;
1944 }
1945
1946 static void
1947 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
1948                         const struct drm_framebuffer *fb,
1949                         unsigned int rotation)
1950 {
1951         view->type = I915_GGTT_VIEW_NORMAL;
1952         if (drm_rotation_90_or_270(rotation)) {
1953                 view->type = I915_GGTT_VIEW_ROTATED;
1954                 view->rotated = to_intel_framebuffer(fb)->rot_info;
1955         }
1956 }
1957
1958 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
1959 {
1960         if (IS_I830(dev_priv))
1961                 return 16 * 1024;
1962         else if (IS_I85X(dev_priv))
1963                 return 256;
1964         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
1965                 return 32;
1966         else
1967                 return 4 * 1024;
1968 }
1969
1970 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
1971 {
1972         if (INTEL_GEN(dev_priv) >= 9)
1973                 return 256 * 1024;
1974         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
1975                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
1976                 return 128 * 1024;
1977         else if (INTEL_GEN(dev_priv) >= 4)
1978                 return 4 * 1024;
1979         else
1980                 return 0;
1981 }
1982
1983 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
1984                                          int color_plane)
1985 {
1986         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1987
1988         /* AUX_DIST needs only 4K alignment */
1989         if (color_plane == 1)
1990                 return 4096;
1991
1992         switch (fb->modifier) {
1993         case DRM_FORMAT_MOD_LINEAR:
1994                 return intel_linear_alignment(dev_priv);
1995         case I915_FORMAT_MOD_X_TILED:
1996                 if (INTEL_GEN(dev_priv) >= 9)
1997                         return 256 * 1024;
1998                 return 0;
1999         case I915_FORMAT_MOD_Y_TILED_CCS:
2000         case I915_FORMAT_MOD_Yf_TILED_CCS:
2001         case I915_FORMAT_MOD_Y_TILED:
2002         case I915_FORMAT_MOD_Yf_TILED:
2003                 return 1 * 1024 * 1024;
2004         default:
2005                 MISSING_CASE(fb->modifier);
2006                 return 0;
2007         }
2008 }
2009
2010 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2011 {
2012         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2013         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2014
2015         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2016 }
2017
2018 struct i915_vma *
2019 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2020                            const struct i915_ggtt_view *view,
2021                            bool uses_fence,
2022                            unsigned long *out_flags)
2023 {
2024         struct drm_device *dev = fb->dev;
2025         struct drm_i915_private *dev_priv = to_i915(dev);
2026         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2027         struct i915_vma *vma;
2028         unsigned int pinctl;
2029         u32 alignment;
2030
2031         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2032
2033         alignment = intel_surf_alignment(fb, 0);
2034
2035         /* Note that the w/a also requires 64 PTE of padding following the
2036          * bo. We currently fill all unused PTE with the shadow page and so
2037          * we should always have valid PTE following the scanout preventing
2038          * the VT-d warning.
2039          */
2040         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2041                 alignment = 256 * 1024;
2042
2043         /*
2044          * Global gtt pte registers are special registers which actually forward
2045          * writes to a chunk of system memory. Which means that there is no risk
2046          * that the register values disappear as soon as we call
2047          * intel_runtime_pm_put(), so it is correct to wrap only the
2048          * pin/unpin/fence and not more.
2049          */
2050         intel_runtime_pm_get(dev_priv);
2051
2052         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2053
2054         pinctl = 0;
2055
2056         /* Valleyview is definitely limited to scanning out the first
2057          * 512MiB. Lets presume this behaviour was inherited from the
2058          * g4x display engine and that all earlier gen are similarly
2059          * limited. Testing suggests that it is a little more
2060          * complicated than this. For example, Cherryview appears quite
2061          * happy to scanout from anywhere within its global aperture.
2062          */
2063         if (HAS_GMCH_DISPLAY(dev_priv))
2064                 pinctl |= PIN_MAPPABLE;
2065
2066         vma = i915_gem_object_pin_to_display_plane(obj,
2067                                                    alignment, view, pinctl);
2068         if (IS_ERR(vma))
2069                 goto err;
2070
2071         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2072                 int ret;
2073
2074                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2075                  * fence, whereas 965+ only requires a fence if using
2076                  * framebuffer compression.  For simplicity, we always, when
2077                  * possible, install a fence as the cost is not that onerous.
2078                  *
2079                  * If we fail to fence the tiled scanout, then either the
2080                  * modeset will reject the change (which is highly unlikely as
2081                  * the affected systems, all but one, do not have unmappable
2082                  * space) or we will not be able to enable full powersaving
2083                  * techniques (also likely not to apply due to various limits
2084                  * FBC and the like impose on the size of the buffer, which
2085                  * presumably we violated anyway with this unmappable buffer).
2086                  * Anyway, it is presumably better to stumble onwards with
2087                  * something and try to run the system in a "less than optimal"
2088                  * mode that matches the user configuration.
2089                  */
2090                 ret = i915_vma_pin_fence(vma);
2091                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2092                         i915_gem_object_unpin_from_display_plane(vma);
2093                         vma = ERR_PTR(ret);
2094                         goto err;
2095                 }
2096
2097                 if (ret == 0 && vma->fence)
2098                         *out_flags |= PLANE_HAS_FENCE;
2099         }
2100
2101         i915_vma_get(vma);
2102 err:
2103         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2104
2105         intel_runtime_pm_put(dev_priv);
2106         return vma;
2107 }
2108
2109 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2110 {
2111         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2112
2113         if (flags & PLANE_HAS_FENCE)
2114                 i915_vma_unpin_fence(vma);
2115         i915_gem_object_unpin_from_display_plane(vma);
2116         i915_vma_put(vma);
2117 }
2118
2119 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2120                           unsigned int rotation)
2121 {
2122         if (drm_rotation_90_or_270(rotation))
2123                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2124         else
2125                 return fb->pitches[color_plane];
2126 }
2127
2128 /*
2129  * Convert the x/y offsets into a linear offset.
2130  * Only valid with 0/180 degree rotation, which is fine since linear
2131  * offset is only used with linear buffers on pre-hsw and tiled buffers
2132  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2133  */
2134 u32 intel_fb_xy_to_linear(int x, int y,
2135                           const struct intel_plane_state *state,
2136                           int color_plane)
2137 {
2138         const struct drm_framebuffer *fb = state->base.fb;
2139         unsigned int cpp = fb->format->cpp[color_plane];
2140         unsigned int pitch = state->color_plane[color_plane].stride;
2141
2142         return y * pitch + x * cpp;
2143 }
2144
2145 /*
2146  * Add the x/y offsets derived from fb->offsets[] to the user
2147  * specified plane src x/y offsets. The resulting x/y offsets
2148  * specify the start of scanout from the beginning of the gtt mapping.
2149  */
2150 void intel_add_fb_offsets(int *x, int *y,
2151                           const struct intel_plane_state *state,
2152                           int color_plane)
2153
2154 {
2155         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2156         unsigned int rotation = state->base.rotation;
2157
2158         if (drm_rotation_90_or_270(rotation)) {
2159                 *x += intel_fb->rotated[color_plane].x;
2160                 *y += intel_fb->rotated[color_plane].y;
2161         } else {
2162                 *x += intel_fb->normal[color_plane].x;
2163                 *y += intel_fb->normal[color_plane].y;
2164         }
2165 }
2166
2167 static u32 intel_adjust_tile_offset(int *x, int *y,
2168                                     unsigned int tile_width,
2169                                     unsigned int tile_height,
2170                                     unsigned int tile_size,
2171                                     unsigned int pitch_tiles,
2172                                     u32 old_offset,
2173                                     u32 new_offset)
2174 {
2175         unsigned int pitch_pixels = pitch_tiles * tile_width;
2176         unsigned int tiles;
2177
2178         WARN_ON(old_offset & (tile_size - 1));
2179         WARN_ON(new_offset & (tile_size - 1));
2180         WARN_ON(new_offset > old_offset);
2181
2182         tiles = (old_offset - new_offset) / tile_size;
2183
2184         *y += tiles / pitch_tiles * tile_height;
2185         *x += tiles % pitch_tiles * tile_width;
2186
2187         /* minimize x in case it got needlessly big */
2188         *y += *x / pitch_pixels * tile_height;
2189         *x %= pitch_pixels;
2190
2191         return new_offset;
2192 }
2193
2194 static bool is_surface_linear(u64 modifier, int color_plane)
2195 {
2196         return modifier == DRM_FORMAT_MOD_LINEAR;
2197 }
2198
2199 static u32 intel_adjust_aligned_offset(int *x, int *y,
2200                                        const struct drm_framebuffer *fb,
2201                                        int color_plane,
2202                                        unsigned int rotation,
2203                                        unsigned int pitch,
2204                                        u32 old_offset, u32 new_offset)
2205 {
2206         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2207         unsigned int cpp = fb->format->cpp[color_plane];
2208
2209         WARN_ON(new_offset > old_offset);
2210
2211         if (!is_surface_linear(fb->modifier, color_plane)) {
2212                 unsigned int tile_size, tile_width, tile_height;
2213                 unsigned int pitch_tiles;
2214
2215                 tile_size = intel_tile_size(dev_priv);
2216                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2217
2218                 if (drm_rotation_90_or_270(rotation)) {
2219                         pitch_tiles = pitch / tile_height;
2220                         swap(tile_width, tile_height);
2221                 } else {
2222                         pitch_tiles = pitch / (tile_width * cpp);
2223                 }
2224
2225                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2226                                          tile_size, pitch_tiles,
2227                                          old_offset, new_offset);
2228         } else {
2229                 old_offset += *y * pitch + *x * cpp;
2230
2231                 *y = (old_offset - new_offset) / pitch;
2232                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2233         }
2234
2235         return new_offset;
2236 }
2237
2238 /*
2239  * Adjust the tile offset by moving the difference into
2240  * the x/y offsets.
2241  */
2242 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2243                                              const struct intel_plane_state *state,
2244                                              int color_plane,
2245                                              u32 old_offset, u32 new_offset)
2246 {
2247         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2248                                            state->base.rotation,
2249                                            state->color_plane[color_plane].stride,
2250                                            old_offset, new_offset);
2251 }
2252
2253 /*
2254  * Computes the aligned offset to the base tile and adjusts
2255  * x, y. bytes per pixel is assumed to be a power-of-two.
2256  *
2257  * In the 90/270 rotated case, x and y are assumed
2258  * to be already rotated to match the rotated GTT view, and
2259  * pitch is the tile_height aligned framebuffer height.
2260  *
2261  * This function is used when computing the derived information
2262  * under intel_framebuffer, so using any of that information
2263  * here is not allowed. Anything under drm_framebuffer can be
2264  * used. This is why the user has to pass in the pitch since it
2265  * is specified in the rotated orientation.
2266  */
2267 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2268                                         int *x, int *y,
2269                                         const struct drm_framebuffer *fb,
2270                                         int color_plane,
2271                                         unsigned int pitch,
2272                                         unsigned int rotation,
2273                                         u32 alignment)
2274 {
2275         unsigned int cpp = fb->format->cpp[color_plane];
2276         u32 offset, offset_aligned;
2277
2278         if (alignment)
2279                 alignment--;
2280
2281         if (!is_surface_linear(fb->modifier, color_plane)) {
2282                 unsigned int tile_size, tile_width, tile_height;
2283                 unsigned int tile_rows, tiles, pitch_tiles;
2284
2285                 tile_size = intel_tile_size(dev_priv);
2286                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2287
2288                 if (drm_rotation_90_or_270(rotation)) {
2289                         pitch_tiles = pitch / tile_height;
2290                         swap(tile_width, tile_height);
2291                 } else {
2292                         pitch_tiles = pitch / (tile_width * cpp);
2293                 }
2294
2295                 tile_rows = *y / tile_height;
2296                 *y %= tile_height;
2297
2298                 tiles = *x / tile_width;
2299                 *x %= tile_width;
2300
2301                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2302                 offset_aligned = offset & ~alignment;
2303
2304                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2305                                          tile_size, pitch_tiles,
2306                                          offset, offset_aligned);
2307         } else {
2308                 offset = *y * pitch + *x * cpp;
2309                 offset_aligned = offset & ~alignment;
2310
2311                 *y = (offset & alignment) / pitch;
2312                 *x = ((offset & alignment) - *y * pitch) / cpp;
2313         }
2314
2315         return offset_aligned;
2316 }
2317
2318 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2319                                               const struct intel_plane_state *state,
2320                                               int color_plane)
2321 {
2322         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2323         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2324         const struct drm_framebuffer *fb = state->base.fb;
2325         unsigned int rotation = state->base.rotation;
2326         int pitch = state->color_plane[color_plane].stride;
2327         u32 alignment;
2328
2329         if (intel_plane->id == PLANE_CURSOR)
2330                 alignment = intel_cursor_alignment(dev_priv);
2331         else
2332                 alignment = intel_surf_alignment(fb, color_plane);
2333
2334         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2335                                             pitch, rotation, alignment);
2336 }
2337
2338 /* Convert the fb->offset[] into x/y offsets */
2339 static int intel_fb_offset_to_xy(int *x, int *y,
2340                                  const struct drm_framebuffer *fb,
2341                                  int color_plane)
2342 {
2343         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2344
2345         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2346             fb->offsets[color_plane] % intel_tile_size(dev_priv))
2347                 return -EINVAL;
2348
2349         *x = 0;
2350         *y = 0;
2351
2352         intel_adjust_aligned_offset(x, y,
2353                                     fb, color_plane, DRM_MODE_ROTATE_0,
2354                                     fb->pitches[color_plane],
2355                                     fb->offsets[color_plane], 0);
2356
2357         return 0;
2358 }
2359
2360 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2361 {
2362         switch (fb_modifier) {
2363         case I915_FORMAT_MOD_X_TILED:
2364                 return I915_TILING_X;
2365         case I915_FORMAT_MOD_Y_TILED:
2366         case I915_FORMAT_MOD_Y_TILED_CCS:
2367                 return I915_TILING_Y;
2368         default:
2369                 return I915_TILING_NONE;
2370         }
2371 }
2372
2373 /*
2374  * From the Sky Lake PRM:
2375  * "The Color Control Surface (CCS) contains the compression status of
2376  *  the cache-line pairs. The compression state of the cache-line pair
2377  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2378  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2379  *  cache-line-pairs. CCS is always Y tiled."
2380  *
2381  * Since cache line pairs refers to horizontally adjacent cache lines,
2382  * each cache line in the CCS corresponds to an area of 32x16 cache
2383  * lines on the main surface. Since each pixel is 4 bytes, this gives
2384  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2385  * main surface.
2386  */
2387 static const struct drm_format_info ccs_formats[] = {
2388         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2389         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2390         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2391         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2392 };
2393
2394 static const struct drm_format_info *
2395 lookup_format_info(const struct drm_format_info formats[],
2396                    int num_formats, u32 format)
2397 {
2398         int i;
2399
2400         for (i = 0; i < num_formats; i++) {
2401                 if (formats[i].format == format)
2402                         return &formats[i];
2403         }
2404
2405         return NULL;
2406 }
2407
2408 static const struct drm_format_info *
2409 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2410 {
2411         switch (cmd->modifier[0]) {
2412         case I915_FORMAT_MOD_Y_TILED_CCS:
2413         case I915_FORMAT_MOD_Yf_TILED_CCS:
2414                 return lookup_format_info(ccs_formats,
2415                                           ARRAY_SIZE(ccs_formats),
2416                                           cmd->pixel_format);
2417         default:
2418                 return NULL;
2419         }
2420 }
2421
2422 bool is_ccs_modifier(u64 modifier)
2423 {
2424         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2425                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2426 }
2427
2428 static int
2429 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2430                    struct drm_framebuffer *fb)
2431 {
2432         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2433         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2434         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2435         u32 gtt_offset_rotated = 0;
2436         unsigned int max_size = 0;
2437         int i, num_planes = fb->format->num_planes;
2438         unsigned int tile_size = intel_tile_size(dev_priv);
2439
2440         for (i = 0; i < num_planes; i++) {
2441                 unsigned int width, height;
2442                 unsigned int cpp, size;
2443                 u32 offset;
2444                 int x, y;
2445                 int ret;
2446
2447                 cpp = fb->format->cpp[i];
2448                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2449                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2450
2451                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2452                 if (ret) {
2453                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2454                                       i, fb->offsets[i]);
2455                         return ret;
2456                 }
2457
2458                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2459                         int hsub = fb->format->hsub;
2460                         int vsub = fb->format->vsub;
2461                         int tile_width, tile_height;
2462                         int main_x, main_y;
2463                         int ccs_x, ccs_y;
2464
2465                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2466                         tile_width *= hsub;
2467                         tile_height *= vsub;
2468
2469                         ccs_x = (x * hsub) % tile_width;
2470                         ccs_y = (y * vsub) % tile_height;
2471                         main_x = intel_fb->normal[0].x % tile_width;
2472                         main_y = intel_fb->normal[0].y % tile_height;
2473
2474                         /*
2475                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2476                          * x/y offsets must match between CCS and the main surface.
2477                          */
2478                         if (main_x != ccs_x || main_y != ccs_y) {
2479                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2480                                               main_x, main_y,
2481                                               ccs_x, ccs_y,
2482                                               intel_fb->normal[0].x,
2483                                               intel_fb->normal[0].y,
2484                                               x, y);
2485                                 return -EINVAL;
2486                         }
2487                 }
2488
2489                 /*
2490                  * The fence (if used) is aligned to the start of the object
2491                  * so having the framebuffer wrap around across the edge of the
2492                  * fenced region doesn't really work. We have no API to configure
2493                  * the fence start offset within the object (nor could we probably
2494                  * on gen2/3). So it's just easier if we just require that the
2495                  * fb layout agrees with the fence layout. We already check that the
2496                  * fb stride matches the fence stride elsewhere.
2497                  */
2498                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2499                     (x + width) * cpp > fb->pitches[i]) {
2500                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2501                                       i, fb->offsets[i]);
2502                         return -EINVAL;
2503                 }
2504
2505                 /*
2506                  * First pixel of the framebuffer from
2507                  * the start of the normal gtt mapping.
2508                  */
2509                 intel_fb->normal[i].x = x;
2510                 intel_fb->normal[i].y = y;
2511
2512                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2513                                                       fb->pitches[i],
2514                                                       DRM_MODE_ROTATE_0,
2515                                                       tile_size);
2516                 offset /= tile_size;
2517
2518                 if (!is_surface_linear(fb->modifier, i)) {
2519                         unsigned int tile_width, tile_height;
2520                         unsigned int pitch_tiles;
2521                         struct drm_rect r;
2522
2523                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2524
2525                         rot_info->plane[i].offset = offset;
2526                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2527                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2528                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2529
2530                         intel_fb->rotated[i].pitch =
2531                                 rot_info->plane[i].height * tile_height;
2532
2533                         /* how many tiles does this plane need */
2534                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2535                         /*
2536                          * If the plane isn't horizontally tile aligned,
2537                          * we need one more tile.
2538                          */
2539                         if (x != 0)
2540                                 size++;
2541
2542                         /* rotate the x/y offsets to match the GTT view */
2543                         r.x1 = x;
2544                         r.y1 = y;
2545                         r.x2 = x + width;
2546                         r.y2 = y + height;
2547                         drm_rect_rotate(&r,
2548                                         rot_info->plane[i].width * tile_width,
2549                                         rot_info->plane[i].height * tile_height,
2550                                         DRM_MODE_ROTATE_270);
2551                         x = r.x1;
2552                         y = r.y1;
2553
2554                         /* rotate the tile dimensions to match the GTT view */
2555                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2556                         swap(tile_width, tile_height);
2557
2558                         /*
2559                          * We only keep the x/y offsets, so push all of the
2560                          * gtt offset into the x/y offsets.
2561                          */
2562                         intel_adjust_tile_offset(&x, &y,
2563                                                  tile_width, tile_height,
2564                                                  tile_size, pitch_tiles,
2565                                                  gtt_offset_rotated * tile_size, 0);
2566
2567                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2568
2569                         /*
2570                          * First pixel of the framebuffer from
2571                          * the start of the rotated gtt mapping.
2572                          */
2573                         intel_fb->rotated[i].x = x;
2574                         intel_fb->rotated[i].y = y;
2575                 } else {
2576                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2577                                             x * cpp, tile_size);
2578                 }
2579
2580                 /* how many tiles in total needed in the bo */
2581                 max_size = max(max_size, offset + size);
2582         }
2583
2584         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2585                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2586                               mul_u32_u32(max_size, tile_size), obj->base.size);
2587                 return -EINVAL;
2588         }
2589
2590         return 0;
2591 }
2592
2593 static int i9xx_format_to_fourcc(int format)
2594 {
2595         switch (format) {
2596         case DISPPLANE_8BPP:
2597                 return DRM_FORMAT_C8;
2598         case DISPPLANE_BGRX555:
2599                 return DRM_FORMAT_XRGB1555;
2600         case DISPPLANE_BGRX565:
2601                 return DRM_FORMAT_RGB565;
2602         default:
2603         case DISPPLANE_BGRX888:
2604                 return DRM_FORMAT_XRGB8888;
2605         case DISPPLANE_RGBX888:
2606                 return DRM_FORMAT_XBGR8888;
2607         case DISPPLANE_BGRX101010:
2608                 return DRM_FORMAT_XRGB2101010;
2609         case DISPPLANE_RGBX101010:
2610                 return DRM_FORMAT_XBGR2101010;
2611         }
2612 }
2613
2614 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2615 {
2616         switch (format) {
2617         case PLANE_CTL_FORMAT_RGB_565:
2618                 return DRM_FORMAT_RGB565;
2619         case PLANE_CTL_FORMAT_NV12:
2620                 return DRM_FORMAT_NV12;
2621         default:
2622         case PLANE_CTL_FORMAT_XRGB_8888:
2623                 if (rgb_order) {
2624                         if (alpha)
2625                                 return DRM_FORMAT_ABGR8888;
2626                         else
2627                                 return DRM_FORMAT_XBGR8888;
2628                 } else {
2629                         if (alpha)
2630                                 return DRM_FORMAT_ARGB8888;
2631                         else
2632                                 return DRM_FORMAT_XRGB8888;
2633                 }
2634         case PLANE_CTL_FORMAT_XRGB_2101010:
2635                 if (rgb_order)
2636                         return DRM_FORMAT_XBGR2101010;
2637                 else
2638                         return DRM_FORMAT_XRGB2101010;
2639         }
2640 }
2641
2642 static bool
2643 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2644                               struct intel_initial_plane_config *plane_config)
2645 {
2646         struct drm_device *dev = crtc->base.dev;
2647         struct drm_i915_private *dev_priv = to_i915(dev);
2648         struct drm_i915_gem_object *obj = NULL;
2649         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2650         struct drm_framebuffer *fb = &plane_config->fb->base;
2651         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2652         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2653                                     PAGE_SIZE);
2654
2655         size_aligned -= base_aligned;
2656
2657         if (plane_config->size == 0)
2658                 return false;
2659
2660         /* If the FB is too big, just don't use it since fbdev is not very
2661          * important and we should probably use that space with FBC or other
2662          * features. */
2663         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2664                 return false;
2665
2666         switch (fb->modifier) {
2667         case DRM_FORMAT_MOD_LINEAR:
2668         case I915_FORMAT_MOD_X_TILED:
2669         case I915_FORMAT_MOD_Y_TILED:
2670                 break;
2671         default:
2672                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
2673                                  fb->modifier);
2674                 return false;
2675         }
2676
2677         mutex_lock(&dev->struct_mutex);
2678         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2679                                                              base_aligned,
2680                                                              base_aligned,
2681                                                              size_aligned);
2682         mutex_unlock(&dev->struct_mutex);
2683         if (!obj)
2684                 return false;
2685
2686         switch (plane_config->tiling) {
2687         case I915_TILING_NONE:
2688                 break;
2689         case I915_TILING_X:
2690         case I915_TILING_Y:
2691                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
2692                 break;
2693         default:
2694                 MISSING_CASE(plane_config->tiling);
2695                 return false;
2696         }
2697
2698         mode_cmd.pixel_format = fb->format->format;
2699         mode_cmd.width = fb->width;
2700         mode_cmd.height = fb->height;
2701         mode_cmd.pitches[0] = fb->pitches[0];
2702         mode_cmd.modifier[0] = fb->modifier;
2703         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2704
2705         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2706                 DRM_DEBUG_KMS("intel fb init failed\n");
2707                 goto out_unref_obj;
2708         }
2709
2710
2711         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2712         return true;
2713
2714 out_unref_obj:
2715         i915_gem_object_put(obj);
2716         return false;
2717 }
2718
2719 static void
2720 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2721                         struct intel_plane_state *plane_state,
2722                         bool visible)
2723 {
2724         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2725
2726         plane_state->base.visible = visible;
2727
2728         if (visible)
2729                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2730         else
2731                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2732 }
2733
2734 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
2735 {
2736         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2737         struct drm_plane *plane;
2738
2739         /*
2740          * Active_planes aliases if multiple "primary" or cursor planes
2741          * have been used on the same (or wrong) pipe. plane_mask uses
2742          * unique ids, hence we can use that to reconstruct active_planes.
2743          */
2744         crtc_state->active_planes = 0;
2745
2746         drm_for_each_plane_mask(plane, &dev_priv->drm,
2747                                 crtc_state->base.plane_mask)
2748                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
2749 }
2750
2751 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2752                                          struct intel_plane *plane)
2753 {
2754         struct intel_crtc_state *crtc_state =
2755                 to_intel_crtc_state(crtc->base.state);
2756         struct intel_plane_state *plane_state =
2757                 to_intel_plane_state(plane->base.state);
2758
2759         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
2760                       plane->base.base.id, plane->base.name,
2761                       crtc->base.base.id, crtc->base.name);
2762
2763         intel_set_plane_visible(crtc_state, plane_state, false);
2764         fixup_active_planes(crtc_state);
2765
2766         if (plane->id == PLANE_PRIMARY)
2767                 intel_pre_disable_primary_noatomic(&crtc->base);
2768
2769         trace_intel_disable_plane(&plane->base, crtc);
2770         plane->disable_plane(plane, crtc_state);
2771 }
2772
2773 static void
2774 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2775                              struct intel_initial_plane_config *plane_config)
2776 {
2777         struct drm_device *dev = intel_crtc->base.dev;
2778         struct drm_i915_private *dev_priv = to_i915(dev);
2779         struct drm_crtc *c;
2780         struct drm_i915_gem_object *obj;
2781         struct drm_plane *primary = intel_crtc->base.primary;
2782         struct drm_plane_state *plane_state = primary->state;
2783         struct intel_plane *intel_plane = to_intel_plane(primary);
2784         struct intel_plane_state *intel_state =
2785                 to_intel_plane_state(plane_state);
2786         struct drm_framebuffer *fb;
2787
2788         if (!plane_config->fb)
2789                 return;
2790
2791         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2792                 fb = &plane_config->fb->base;
2793                 goto valid_fb;
2794         }
2795
2796         kfree(plane_config->fb);
2797
2798         /*
2799          * Failed to alloc the obj, check to see if we should share
2800          * an fb with another CRTC instead
2801          */
2802         for_each_crtc(dev, c) {
2803                 struct intel_plane_state *state;
2804
2805                 if (c == &intel_crtc->base)
2806                         continue;
2807
2808                 if (!to_intel_crtc(c)->active)
2809                         continue;
2810
2811                 state = to_intel_plane_state(c->primary->state);
2812                 if (!state->vma)
2813                         continue;
2814
2815                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2816                         fb = state->base.fb;
2817                         drm_framebuffer_get(fb);
2818                         goto valid_fb;
2819                 }
2820         }
2821
2822         /*
2823          * We've failed to reconstruct the BIOS FB.  Current display state
2824          * indicates that the primary plane is visible, but has a NULL FB,
2825          * which will lead to problems later if we don't fix it up.  The
2826          * simplest solution is to just disable the primary plane now and
2827          * pretend the BIOS never had it enabled.
2828          */
2829         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2830
2831         return;
2832
2833 valid_fb:
2834         intel_state->base.rotation = plane_config->rotation;
2835         intel_fill_fb_ggtt_view(&intel_state->view, fb,
2836                                 intel_state->base.rotation);
2837         intel_state->color_plane[0].stride =
2838                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
2839
2840         mutex_lock(&dev->struct_mutex);
2841         intel_state->vma =
2842                 intel_pin_and_fence_fb_obj(fb,
2843                                            &intel_state->view,
2844                                            intel_plane_uses_fence(intel_state),
2845                                            &intel_state->flags);
2846         mutex_unlock(&dev->struct_mutex);
2847         if (IS_ERR(intel_state->vma)) {
2848                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2849                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2850
2851                 intel_state->vma = NULL;
2852                 drm_framebuffer_put(fb);
2853                 return;
2854         }
2855
2856         obj = intel_fb_obj(fb);
2857         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2858
2859         plane_state->src_x = 0;
2860         plane_state->src_y = 0;
2861         plane_state->src_w = fb->width << 16;
2862         plane_state->src_h = fb->height << 16;
2863
2864         plane_state->crtc_x = 0;
2865         plane_state->crtc_y = 0;
2866         plane_state->crtc_w = fb->width;
2867         plane_state->crtc_h = fb->height;
2868
2869         intel_state->base.src = drm_plane_state_src(plane_state);
2870         intel_state->base.dst = drm_plane_state_dest(plane_state);
2871
2872         if (i915_gem_object_is_tiled(obj))
2873                 dev_priv->preserve_bios_swizzle = true;
2874
2875         plane_state->fb = fb;
2876         plane_state->crtc = &intel_crtc->base;
2877
2878         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2879                   &obj->frontbuffer_bits);
2880 }
2881
2882 static int skl_max_plane_width(const struct drm_framebuffer *fb,
2883                                int color_plane,
2884                                unsigned int rotation)
2885 {
2886         int cpp = fb->format->cpp[color_plane];
2887
2888         switch (fb->modifier) {
2889         case DRM_FORMAT_MOD_LINEAR:
2890         case I915_FORMAT_MOD_X_TILED:
2891                 switch (cpp) {
2892                 case 8:
2893                         return 4096;
2894                 case 4:
2895                 case 2:
2896                 case 1:
2897                         return 8192;
2898                 default:
2899                         MISSING_CASE(cpp);
2900                         break;
2901                 }
2902                 break;
2903         case I915_FORMAT_MOD_Y_TILED_CCS:
2904         case I915_FORMAT_MOD_Yf_TILED_CCS:
2905                 /* FIXME AUX plane? */
2906         case I915_FORMAT_MOD_Y_TILED:
2907         case I915_FORMAT_MOD_Yf_TILED:
2908                 switch (cpp) {
2909                 case 8:
2910                         return 2048;
2911                 case 4:
2912                         return 4096;
2913                 case 2:
2914                 case 1:
2915                         return 8192;
2916                 default:
2917                         MISSING_CASE(cpp);
2918                         break;
2919                 }
2920                 break;
2921         default:
2922                 MISSING_CASE(fb->modifier);
2923         }
2924
2925         return 2048;
2926 }
2927
2928 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2929                                            int main_x, int main_y, u32 main_offset)
2930 {
2931         const struct drm_framebuffer *fb = plane_state->base.fb;
2932         int hsub = fb->format->hsub;
2933         int vsub = fb->format->vsub;
2934         int aux_x = plane_state->color_plane[1].x;
2935         int aux_y = plane_state->color_plane[1].y;
2936         u32 aux_offset = plane_state->color_plane[1].offset;
2937         u32 alignment = intel_surf_alignment(fb, 1);
2938
2939         while (aux_offset >= main_offset && aux_y <= main_y) {
2940                 int x, y;
2941
2942                 if (aux_x == main_x && aux_y == main_y)
2943                         break;
2944
2945                 if (aux_offset == 0)
2946                         break;
2947
2948                 x = aux_x / hsub;
2949                 y = aux_y / vsub;
2950                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
2951                                                                aux_offset, aux_offset - alignment);
2952                 aux_x = x * hsub + aux_x % hsub;
2953                 aux_y = y * vsub + aux_y % vsub;
2954         }
2955
2956         if (aux_x != main_x || aux_y != main_y)
2957                 return false;
2958
2959         plane_state->color_plane[1].offset = aux_offset;
2960         plane_state->color_plane[1].x = aux_x;
2961         plane_state->color_plane[1].y = aux_y;
2962
2963         return true;
2964 }
2965
2966 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2967 {
2968         const struct drm_framebuffer *fb = plane_state->base.fb;
2969         unsigned int rotation = plane_state->base.rotation;
2970         int x = plane_state->base.src.x1 >> 16;
2971         int y = plane_state->base.src.y1 >> 16;
2972         int w = drm_rect_width(&plane_state->base.src) >> 16;
2973         int h = drm_rect_height(&plane_state->base.src) >> 16;
2974         int max_width = skl_max_plane_width(fb, 0, rotation);
2975         int max_height = 4096;
2976         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
2977
2978         if (w > max_width || h > max_height) {
2979                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2980                               w, h, max_width, max_height);
2981                 return -EINVAL;
2982         }
2983
2984         intel_add_fb_offsets(&x, &y, plane_state, 0);
2985         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
2986         alignment = intel_surf_alignment(fb, 0);
2987
2988         /*
2989          * AUX surface offset is specified as the distance from the
2990          * main surface offset, and it must be non-negative. Make
2991          * sure that is what we will get.
2992          */
2993         if (offset > aux_offset)
2994                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
2995                                                            offset, aux_offset & ~(alignment - 1));
2996
2997         /*
2998          * When using an X-tiled surface, the plane blows up
2999          * if the x offset + width exceed the stride.
3000          *
3001          * TODO: linear and Y-tiled seem fine, Yf untested,
3002          */
3003         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3004                 int cpp = fb->format->cpp[0];
3005
3006                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3007                         if (offset == 0) {
3008                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3009                                 return -EINVAL;
3010                         }
3011
3012                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3013                                                                    offset, offset - alignment);
3014                 }
3015         }
3016
3017         /*
3018          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3019          * they match with the main surface x/y offsets.
3020          */
3021         if (is_ccs_modifier(fb->modifier)) {
3022                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3023                         if (offset == 0)
3024                                 break;
3025
3026                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3027                                                                    offset, offset - alignment);
3028                 }
3029
3030                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3031                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3032                         return -EINVAL;
3033                 }
3034         }
3035
3036         plane_state->color_plane[0].offset = offset;
3037         plane_state->color_plane[0].x = x;
3038         plane_state->color_plane[0].y = y;
3039
3040         return 0;
3041 }
3042
3043 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3044 {
3045         const struct drm_framebuffer *fb = plane_state->base.fb;
3046         unsigned int rotation = plane_state->base.rotation;
3047         int max_width = skl_max_plane_width(fb, 1, rotation);
3048         int max_height = 4096;
3049         int x = plane_state->base.src.x1 >> 17;
3050         int y = plane_state->base.src.y1 >> 17;
3051         int w = drm_rect_width(&plane_state->base.src) >> 17;
3052         int h = drm_rect_height(&plane_state->base.src) >> 17;
3053         u32 offset;
3054
3055         intel_add_fb_offsets(&x, &y, plane_state, 1);
3056         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3057
3058         /* FIXME not quite sure how/if these apply to the chroma plane */
3059         if (w > max_width || h > max_height) {
3060                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3061                               w, h, max_width, max_height);
3062                 return -EINVAL;
3063         }
3064
3065         plane_state->color_plane[1].offset = offset;
3066         plane_state->color_plane[1].x = x;
3067         plane_state->color_plane[1].y = y;
3068
3069         return 0;
3070 }
3071
3072 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3073 {
3074         const struct drm_framebuffer *fb = plane_state->base.fb;
3075         int src_x = plane_state->base.src.x1 >> 16;
3076         int src_y = plane_state->base.src.y1 >> 16;
3077         int hsub = fb->format->hsub;
3078         int vsub = fb->format->vsub;
3079         int x = src_x / hsub;
3080         int y = src_y / vsub;
3081         u32 offset;
3082
3083         intel_add_fb_offsets(&x, &y, plane_state, 1);
3084         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3085
3086         plane_state->color_plane[1].offset = offset;
3087         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3088         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3089
3090         return 0;
3091 }
3092
3093 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3094 {
3095         const struct drm_framebuffer *fb = plane_state->base.fb;
3096         unsigned int rotation = plane_state->base.rotation;
3097         int ret;
3098
3099         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3100         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3101         plane_state->color_plane[1].stride = intel_fb_pitch(fb, 1, rotation);
3102
3103         ret = intel_plane_check_stride(plane_state);
3104         if (ret)
3105                 return ret;
3106
3107         if (!plane_state->base.visible)
3108                 return 0;
3109
3110         /* Rotate src coordinates to match rotated GTT view */
3111         if (drm_rotation_90_or_270(rotation))
3112                 drm_rect_rotate(&plane_state->base.src,
3113                                 fb->width << 16, fb->height << 16,
3114                                 DRM_MODE_ROTATE_270);
3115
3116         /*
3117          * Handle the AUX surface first since
3118          * the main surface setup depends on it.
3119          */
3120         if (fb->format->format == DRM_FORMAT_NV12) {
3121                 ret = skl_check_nv12_aux_surface(plane_state);
3122                 if (ret)
3123                         return ret;
3124         } else if (is_ccs_modifier(fb->modifier)) {
3125                 ret = skl_check_ccs_aux_surface(plane_state);
3126                 if (ret)
3127                         return ret;
3128         } else {
3129                 plane_state->color_plane[1].offset = ~0xfff;
3130                 plane_state->color_plane[1].x = 0;
3131                 plane_state->color_plane[1].y = 0;
3132         }
3133
3134         ret = skl_check_main_surface(plane_state);
3135         if (ret)
3136                 return ret;
3137
3138         return 0;
3139 }
3140
3141 unsigned int
3142 i9xx_plane_max_stride(struct intel_plane *plane,
3143                       u32 pixel_format, u64 modifier,
3144                       unsigned int rotation)
3145 {
3146         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3147
3148         if (!HAS_GMCH_DISPLAY(dev_priv)) {
3149                 return 32*1024;
3150         } else if (INTEL_GEN(dev_priv) >= 4) {
3151                 if (modifier == I915_FORMAT_MOD_X_TILED)
3152                         return 16*1024;
3153                 else
3154                         return 32*1024;
3155         } else if (INTEL_GEN(dev_priv) >= 3) {
3156                 if (modifier == I915_FORMAT_MOD_X_TILED)
3157                         return 8*1024;
3158                 else
3159                         return 16*1024;
3160         } else {
3161                 if (plane->i9xx_plane == PLANE_C)
3162                         return 4*1024;
3163                 else
3164                         return 8*1024;
3165         }
3166 }
3167
3168 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3169                           const struct intel_plane_state *plane_state)
3170 {
3171         struct drm_i915_private *dev_priv =
3172                 to_i915(plane_state->base.plane->dev);
3173         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3174         const struct drm_framebuffer *fb = plane_state->base.fb;
3175         unsigned int rotation = plane_state->base.rotation;
3176         u32 dspcntr;
3177
3178         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3179
3180         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3181             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3182                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3183
3184         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3185                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3186
3187         if (INTEL_GEN(dev_priv) < 5)
3188                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3189
3190         switch (fb->format->format) {
3191         case DRM_FORMAT_C8:
3192                 dspcntr |= DISPPLANE_8BPP;
3193                 break;
3194         case DRM_FORMAT_XRGB1555:
3195                 dspcntr |= DISPPLANE_BGRX555;
3196                 break;
3197         case DRM_FORMAT_RGB565:
3198                 dspcntr |= DISPPLANE_BGRX565;
3199                 break;
3200         case DRM_FORMAT_XRGB8888:
3201                 dspcntr |= DISPPLANE_BGRX888;
3202                 break;
3203         case DRM_FORMAT_XBGR8888:
3204                 dspcntr |= DISPPLANE_RGBX888;
3205                 break;
3206         case DRM_FORMAT_XRGB2101010:
3207                 dspcntr |= DISPPLANE_BGRX101010;
3208                 break;
3209         case DRM_FORMAT_XBGR2101010:
3210                 dspcntr |= DISPPLANE_RGBX101010;
3211                 break;
3212         default:
3213                 MISSING_CASE(fb->format->format);
3214                 return 0;
3215         }
3216
3217         if (INTEL_GEN(dev_priv) >= 4 &&
3218             fb->modifier == I915_FORMAT_MOD_X_TILED)
3219                 dspcntr |= DISPPLANE_TILED;
3220
3221         if (rotation & DRM_MODE_ROTATE_180)
3222                 dspcntr |= DISPPLANE_ROTATE_180;
3223
3224         if (rotation & DRM_MODE_REFLECT_X)
3225                 dspcntr |= DISPPLANE_MIRROR;
3226
3227         return dspcntr;
3228 }
3229
3230 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3231 {
3232         struct drm_i915_private *dev_priv =
3233                 to_i915(plane_state->base.plane->dev);
3234         const struct drm_framebuffer *fb = plane_state->base.fb;
3235         unsigned int rotation = plane_state->base.rotation;
3236         int src_x = plane_state->base.src.x1 >> 16;
3237         int src_y = plane_state->base.src.y1 >> 16;
3238         u32 offset;
3239         int ret;
3240
3241         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3242         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3243
3244         ret = intel_plane_check_stride(plane_state);
3245         if (ret)
3246                 return ret;
3247
3248         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3249
3250         if (INTEL_GEN(dev_priv) >= 4)
3251                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3252                                                             plane_state, 0);
3253         else
3254                 offset = 0;
3255
3256         /* HSW/BDW do this automagically in hardware */
3257         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3258                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3259                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3260
3261                 if (rotation & DRM_MODE_ROTATE_180) {
3262                         src_x += src_w - 1;
3263                         src_y += src_h - 1;
3264                 } else if (rotation & DRM_MODE_REFLECT_X) {
3265                         src_x += src_w - 1;
3266                 }
3267         }
3268
3269         plane_state->color_plane[0].offset = offset;
3270         plane_state->color_plane[0].x = src_x;
3271         plane_state->color_plane[0].y = src_y;
3272
3273         return 0;
3274 }
3275
3276 static int
3277 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3278                  struct intel_plane_state *plane_state)
3279 {
3280         int ret;
3281
3282         ret = chv_plane_check_rotation(plane_state);
3283         if (ret)
3284                 return ret;
3285
3286         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3287                                                   &crtc_state->base,
3288                                                   DRM_PLANE_HELPER_NO_SCALING,
3289                                                   DRM_PLANE_HELPER_NO_SCALING,
3290                                                   false, true);
3291         if (ret)
3292                 return ret;
3293
3294         if (!plane_state->base.visible)
3295                 return 0;
3296
3297         ret = intel_plane_check_src_coordinates(plane_state);
3298         if (ret)
3299                 return ret;
3300
3301         ret = i9xx_check_plane_surface(plane_state);
3302         if (ret)
3303                 return ret;
3304
3305         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3306
3307         return 0;
3308 }
3309
3310 static void i9xx_update_plane(struct intel_plane *plane,
3311                               const struct intel_crtc_state *crtc_state,
3312                               const struct intel_plane_state *plane_state)
3313 {
3314         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3315         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3316         u32 linear_offset;
3317         u32 dspcntr = plane_state->ctl;
3318         int x = plane_state->color_plane[0].x;
3319         int y = plane_state->color_plane[0].y;
3320         unsigned long irqflags;
3321         u32 dspaddr_offset;
3322
3323         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3324
3325         if (INTEL_GEN(dev_priv) >= 4)
3326                 dspaddr_offset = plane_state->color_plane[0].offset;
3327         else
3328                 dspaddr_offset = linear_offset;
3329
3330         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3331
3332         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3333
3334         if (INTEL_GEN(dev_priv) < 4) {
3335                 /* pipesrc and dspsize control the size that is scaled from,
3336                  * which should always be the user's requested size.
3337                  */
3338                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3339                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3340                               ((crtc_state->pipe_src_h - 1) << 16) |
3341                               (crtc_state->pipe_src_w - 1));
3342         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3343                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3344                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3345                               ((crtc_state->pipe_src_h - 1) << 16) |
3346                               (crtc_state->pipe_src_w - 1));
3347                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3348         }
3349
3350         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3351                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3352         } else if (INTEL_GEN(dev_priv) >= 4) {
3353                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3354                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3355         }
3356
3357         /*
3358          * The control register self-arms if the plane was previously
3359          * disabled. Try to make the plane enable atomic by writing
3360          * the control register just before the surface register.
3361          */
3362         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3363         if (INTEL_GEN(dev_priv) >= 4)
3364                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3365                               intel_plane_ggtt_offset(plane_state) +
3366                               dspaddr_offset);
3367         else
3368                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3369                               intel_plane_ggtt_offset(plane_state) +
3370                               dspaddr_offset);
3371
3372         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3373 }
3374
3375 static void i9xx_disable_plane(struct intel_plane *plane,
3376                                const struct intel_crtc_state *crtc_state)
3377 {
3378         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3379         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3380         unsigned long irqflags;
3381
3382         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3383
3384         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3385         if (INTEL_GEN(dev_priv) >= 4)
3386                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3387         else
3388                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3389
3390         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3391 }
3392
3393 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3394                                     enum pipe *pipe)
3395 {
3396         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3397         enum intel_display_power_domain power_domain;
3398         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3399         bool ret;
3400         u32 val;
3401
3402         /*
3403          * Not 100% correct for planes that can move between pipes,
3404          * but that's only the case for gen2-4 which don't have any
3405          * display power wells.
3406          */
3407         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3408         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3409                 return false;
3410
3411         val = I915_READ(DSPCNTR(i9xx_plane));
3412
3413         ret = val & DISPLAY_PLANE_ENABLE;
3414
3415         if (INTEL_GEN(dev_priv) >= 5)
3416                 *pipe = plane->pipe;
3417         else
3418                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3419                         DISPPLANE_SEL_PIPE_SHIFT;
3420
3421         intel_display_power_put(dev_priv, power_domain);
3422
3423         return ret;
3424 }
3425
3426 static u32
3427 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
3428 {
3429         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3430                 return 64;
3431         else
3432                 return intel_tile_width_bytes(fb, color_plane);
3433 }
3434
3435 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3436 {
3437         struct drm_device *dev = intel_crtc->base.dev;
3438         struct drm_i915_private *dev_priv = to_i915(dev);
3439
3440         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3441         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3442         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3443 }
3444
3445 /*
3446  * This function detaches (aka. unbinds) unused scalers in hardware
3447  */
3448 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3449 {
3450         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3451         const struct intel_crtc_scaler_state *scaler_state =
3452                 &crtc_state->scaler_state;
3453         int i;
3454
3455         /* loop through and disable scalers that aren't in use */
3456         for (i = 0; i < intel_crtc->num_scalers; i++) {
3457                 if (!scaler_state->scalers[i].in_use)
3458                         skl_detach_scaler(intel_crtc, i);
3459         }
3460 }
3461
3462 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3463                      int color_plane)
3464 {
3465         const struct drm_framebuffer *fb = plane_state->base.fb;
3466         unsigned int rotation = plane_state->base.rotation;
3467         u32 stride = plane_state->color_plane[color_plane].stride;
3468
3469         if (color_plane >= fb->format->num_planes)
3470                 return 0;
3471
3472         /*
3473          * The stride is either expressed as a multiple of 64 bytes chunks for
3474          * linear buffers or in number of tiles for tiled buffers.
3475          */
3476         if (drm_rotation_90_or_270(rotation))
3477                 stride /= intel_tile_height(fb, color_plane);
3478         else
3479                 stride /= intel_fb_stride_alignment(fb, color_plane);
3480
3481         return stride;
3482 }
3483
3484 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3485 {
3486         switch (pixel_format) {
3487         case DRM_FORMAT_C8:
3488                 return PLANE_CTL_FORMAT_INDEXED;
3489         case DRM_FORMAT_RGB565:
3490                 return PLANE_CTL_FORMAT_RGB_565;
3491         case DRM_FORMAT_XBGR8888:
3492         case DRM_FORMAT_ABGR8888:
3493                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3494         case DRM_FORMAT_XRGB8888:
3495         case DRM_FORMAT_ARGB8888:
3496                 return PLANE_CTL_FORMAT_XRGB_8888;
3497         case DRM_FORMAT_XRGB2101010:
3498                 return PLANE_CTL_FORMAT_XRGB_2101010;
3499         case DRM_FORMAT_XBGR2101010:
3500                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3501         case DRM_FORMAT_YUYV:
3502                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3503         case DRM_FORMAT_YVYU:
3504                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3505         case DRM_FORMAT_UYVY:
3506                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3507         case DRM_FORMAT_VYUY:
3508                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3509         case DRM_FORMAT_NV12:
3510                 return PLANE_CTL_FORMAT_NV12;
3511         default:
3512                 MISSING_CASE(pixel_format);
3513         }
3514
3515         return 0;
3516 }
3517
3518 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
3519 {
3520         if (!plane_state->base.fb->format->has_alpha)
3521                 return PLANE_CTL_ALPHA_DISABLE;
3522
3523         switch (plane_state->base.pixel_blend_mode) {
3524         case DRM_MODE_BLEND_PIXEL_NONE:
3525                 return PLANE_CTL_ALPHA_DISABLE;
3526         case DRM_MODE_BLEND_PREMULTI:
3527                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3528         case DRM_MODE_BLEND_COVERAGE:
3529                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
3530         default:
3531                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3532                 return PLANE_CTL_ALPHA_DISABLE;
3533         }
3534 }
3535
3536 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
3537 {
3538         if (!plane_state->base.fb->format->has_alpha)
3539                 return PLANE_COLOR_ALPHA_DISABLE;
3540
3541         switch (plane_state->base.pixel_blend_mode) {
3542         case DRM_MODE_BLEND_PIXEL_NONE:
3543                 return PLANE_COLOR_ALPHA_DISABLE;
3544         case DRM_MODE_BLEND_PREMULTI:
3545                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3546         case DRM_MODE_BLEND_COVERAGE:
3547                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
3548         default:
3549                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3550                 return PLANE_COLOR_ALPHA_DISABLE;
3551         }
3552 }
3553
3554 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3555 {
3556         switch (fb_modifier) {
3557         case DRM_FORMAT_MOD_LINEAR:
3558                 break;
3559         case I915_FORMAT_MOD_X_TILED:
3560                 return PLANE_CTL_TILED_X;
3561         case I915_FORMAT_MOD_Y_TILED:
3562                 return PLANE_CTL_TILED_Y;
3563         case I915_FORMAT_MOD_Y_TILED_CCS:
3564                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3565         case I915_FORMAT_MOD_Yf_TILED:
3566                 return PLANE_CTL_TILED_YF;
3567         case I915_FORMAT_MOD_Yf_TILED_CCS:
3568                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3569         default:
3570                 MISSING_CASE(fb_modifier);
3571         }
3572
3573         return 0;
3574 }
3575
3576 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3577 {
3578         switch (rotate) {
3579         case DRM_MODE_ROTATE_0:
3580                 break;
3581         /*
3582          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3583          * while i915 HW rotation is clockwise, thats why this swapping.
3584          */
3585         case DRM_MODE_ROTATE_90:
3586                 return PLANE_CTL_ROTATE_270;
3587         case DRM_MODE_ROTATE_180:
3588                 return PLANE_CTL_ROTATE_180;
3589         case DRM_MODE_ROTATE_270:
3590                 return PLANE_CTL_ROTATE_90;
3591         default:
3592                 MISSING_CASE(rotate);
3593         }
3594
3595         return 0;
3596 }
3597
3598 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3599 {
3600         switch (reflect) {
3601         case 0:
3602                 break;
3603         case DRM_MODE_REFLECT_X:
3604                 return PLANE_CTL_FLIP_HORIZONTAL;
3605         case DRM_MODE_REFLECT_Y:
3606         default:
3607                 MISSING_CASE(reflect);
3608         }
3609
3610         return 0;
3611 }
3612
3613 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3614                   const struct intel_plane_state *plane_state)
3615 {
3616         struct drm_i915_private *dev_priv =
3617                 to_i915(plane_state->base.plane->dev);
3618         const struct drm_framebuffer *fb = plane_state->base.fb;
3619         unsigned int rotation = plane_state->base.rotation;
3620         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3621         u32 plane_ctl;
3622
3623         plane_ctl = PLANE_CTL_ENABLE;
3624
3625         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3626                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
3627                 plane_ctl |=
3628                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3629                         PLANE_CTL_PIPE_CSC_ENABLE |
3630                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3631
3632                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3633                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3634
3635                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3636                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3637         }
3638
3639         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3640         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3641         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3642
3643         if (INTEL_GEN(dev_priv) >= 10)
3644                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3645                                                 DRM_MODE_REFLECT_MASK);
3646
3647         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3648                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3649         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3650                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3651
3652         return plane_ctl;
3653 }
3654
3655 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3656                         const struct intel_plane_state *plane_state)
3657 {
3658         struct drm_i915_private *dev_priv =
3659                 to_i915(plane_state->base.plane->dev);
3660         const struct drm_framebuffer *fb = plane_state->base.fb;
3661         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3662         u32 plane_color_ctl = 0;
3663
3664         if (INTEL_GEN(dev_priv) < 11) {
3665                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3666                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3667         }
3668         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3669         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
3670
3671         if (fb->format->is_yuv && !icl_is_hdr_plane(plane)) {
3672                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3673                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3674                 else
3675                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3676
3677                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3678                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3679         } else if (fb->format->is_yuv) {
3680                 plane_color_ctl |= PLANE_COLOR_INPUT_CSC_ENABLE;
3681         }
3682
3683         return plane_color_ctl;
3684 }
3685
3686 static int
3687 __intel_display_resume(struct drm_device *dev,
3688                        struct drm_atomic_state *state,
3689                        struct drm_modeset_acquire_ctx *ctx)
3690 {
3691         struct drm_crtc_state *crtc_state;
3692         struct drm_crtc *crtc;
3693         int i, ret;
3694
3695         intel_modeset_setup_hw_state(dev, ctx);
3696         i915_redisable_vga(to_i915(dev));
3697
3698         if (!state)
3699                 return 0;
3700
3701         /*
3702          * We've duplicated the state, pointers to the old state are invalid.
3703          *
3704          * Don't attempt to use the old state until we commit the duplicated state.
3705          */
3706         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3707                 /*
3708                  * Force recalculation even if we restore
3709                  * current state. With fast modeset this may not result
3710                  * in a modeset when the state is compatible.
3711                  */
3712                 crtc_state->mode_changed = true;
3713         }
3714
3715         /* ignore any reset values/BIOS leftovers in the WM registers */
3716         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3717                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3718
3719         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3720
3721         WARN_ON(ret == -EDEADLK);
3722         return ret;
3723 }
3724
3725 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3726 {
3727         return intel_has_gpu_reset(dev_priv) &&
3728                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3729 }
3730
3731 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3732 {
3733         struct drm_device *dev = &dev_priv->drm;
3734         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3735         struct drm_atomic_state *state;
3736         int ret;
3737
3738         /* reset doesn't touch the display */
3739         if (!i915_modparams.force_reset_modeset_test &&
3740             !gpu_reset_clobbers_display(dev_priv))
3741                 return;
3742
3743         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3744         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3745         wake_up_all(&dev_priv->gpu_error.wait_queue);
3746
3747         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3748                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3749                 i915_gem_set_wedged(dev_priv);
3750         }
3751
3752         /*
3753          * Need mode_config.mutex so that we don't
3754          * trample ongoing ->detect() and whatnot.
3755          */
3756         mutex_lock(&dev->mode_config.mutex);
3757         drm_modeset_acquire_init(ctx, 0);
3758         while (1) {
3759                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3760                 if (ret != -EDEADLK)
3761                         break;
3762
3763                 drm_modeset_backoff(ctx);
3764         }
3765         /*
3766          * Disabling the crtcs gracefully seems nicer. Also the
3767          * g33 docs say we should at least disable all the planes.
3768          */
3769         state = drm_atomic_helper_duplicate_state(dev, ctx);
3770         if (IS_ERR(state)) {
3771                 ret = PTR_ERR(state);
3772                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3773                 return;
3774         }
3775
3776         ret = drm_atomic_helper_disable_all(dev, ctx);
3777         if (ret) {
3778                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3779                 drm_atomic_state_put(state);
3780                 return;
3781         }
3782
3783         dev_priv->modeset_restore_state = state;
3784         state->acquire_ctx = ctx;
3785 }
3786
3787 void intel_finish_reset(struct drm_i915_private *dev_priv)
3788 {
3789         struct drm_device *dev = &dev_priv->drm;
3790         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3791         struct drm_atomic_state *state;
3792         int ret;
3793
3794         /* reset doesn't touch the display */
3795         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3796                 return;
3797
3798         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3799         if (!state)
3800                 goto unlock;
3801
3802         /* reset doesn't touch the display */
3803         if (!gpu_reset_clobbers_display(dev_priv)) {
3804                 /* for testing only restore the display */
3805                 ret = __intel_display_resume(dev, state, ctx);
3806                 if (ret)
3807                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3808         } else {
3809                 /*
3810                  * The display has been reset as well,
3811                  * so need a full re-initialization.
3812                  */
3813                 intel_runtime_pm_disable_interrupts(dev_priv);
3814                 intel_runtime_pm_enable_interrupts(dev_priv);
3815
3816                 intel_pps_unlock_regs_wa(dev_priv);
3817                 intel_modeset_init_hw(dev);
3818                 intel_init_clock_gating(dev_priv);
3819
3820                 spin_lock_irq(&dev_priv->irq_lock);
3821                 if (dev_priv->display.hpd_irq_setup)
3822                         dev_priv->display.hpd_irq_setup(dev_priv);
3823                 spin_unlock_irq(&dev_priv->irq_lock);
3824
3825                 ret = __intel_display_resume(dev, state, ctx);
3826                 if (ret)
3827                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3828
3829                 intel_hpd_init(dev_priv);
3830         }
3831
3832         drm_atomic_state_put(state);
3833 unlock:
3834         drm_modeset_drop_locks(ctx);
3835         drm_modeset_acquire_fini(ctx);
3836         mutex_unlock(&dev->mode_config.mutex);
3837
3838         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3839 }
3840
3841 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3842                                      const struct intel_crtc_state *new_crtc_state)
3843 {
3844         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3845         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3846
3847         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3848         crtc->base.mode = new_crtc_state->base.mode;
3849
3850         /*
3851          * Update pipe size and adjust fitter if needed: the reason for this is
3852          * that in compute_mode_changes we check the native mode (not the pfit
3853          * mode) to see if we can flip rather than do a full mode set. In the
3854          * fastboot case, we'll flip, but if we don't update the pipesrc and
3855          * pfit state, we'll end up with a big fb scanned out into the wrong
3856          * sized surface.
3857          */
3858
3859         I915_WRITE(PIPESRC(crtc->pipe),
3860                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3861                    (new_crtc_state->pipe_src_h - 1));
3862
3863         /* on skylake this is done by detaching scalers */
3864         if (INTEL_GEN(dev_priv) >= 9) {
3865                 skl_detach_scalers(new_crtc_state);
3866
3867                 if (new_crtc_state->pch_pfit.enabled)
3868                         skylake_pfit_enable(new_crtc_state);
3869         } else if (HAS_PCH_SPLIT(dev_priv)) {
3870                 if (new_crtc_state->pch_pfit.enabled)
3871                         ironlake_pfit_enable(new_crtc_state);
3872                 else if (old_crtc_state->pch_pfit.enabled)
3873                         ironlake_pfit_disable(old_crtc_state);
3874         }
3875 }
3876
3877 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3878 {
3879         struct drm_device *dev = crtc->base.dev;
3880         struct drm_i915_private *dev_priv = to_i915(dev);
3881         int pipe = crtc->pipe;
3882         i915_reg_t reg;
3883         u32 temp;
3884
3885         /* enable normal train */
3886         reg = FDI_TX_CTL(pipe);
3887         temp = I915_READ(reg);
3888         if (IS_IVYBRIDGE(dev_priv)) {
3889                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3890                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3891         } else {
3892                 temp &= ~FDI_LINK_TRAIN_NONE;
3893                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3894         }
3895         I915_WRITE(reg, temp);
3896
3897         reg = FDI_RX_CTL(pipe);
3898         temp = I915_READ(reg);
3899         if (HAS_PCH_CPT(dev_priv)) {
3900                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3901                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3902         } else {
3903                 temp &= ~FDI_LINK_TRAIN_NONE;
3904                 temp |= FDI_LINK_TRAIN_NONE;
3905         }
3906         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3907
3908         /* wait one idle pattern time */
3909         POSTING_READ(reg);
3910         udelay(1000);
3911
3912         /* IVB wants error correction enabled */
3913         if (IS_IVYBRIDGE(dev_priv))
3914                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3915                            FDI_FE_ERRC_ENABLE);
3916 }
3917
3918 /* The FDI link training functions for ILK/Ibexpeak. */
3919 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3920                                     const struct intel_crtc_state *crtc_state)
3921 {
3922         struct drm_device *dev = crtc->base.dev;
3923         struct drm_i915_private *dev_priv = to_i915(dev);
3924         int pipe = crtc->pipe;
3925         i915_reg_t reg;
3926         u32 temp, tries;
3927
3928         /* FDI needs bits from pipe first */
3929         assert_pipe_enabled(dev_priv, pipe);
3930
3931         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3932            for train result */
3933         reg = FDI_RX_IMR(pipe);
3934         temp = I915_READ(reg);
3935         temp &= ~FDI_RX_SYMBOL_LOCK;
3936         temp &= ~FDI_RX_BIT_LOCK;
3937         I915_WRITE(reg, temp);
3938         I915_READ(reg);
3939         udelay(150);
3940
3941         /* enable CPU FDI TX and PCH FDI RX */
3942         reg = FDI_TX_CTL(pipe);
3943         temp = I915_READ(reg);
3944         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3945         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3946         temp &= ~FDI_LINK_TRAIN_NONE;
3947         temp |= FDI_LINK_TRAIN_PATTERN_1;
3948         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3949
3950         reg = FDI_RX_CTL(pipe);
3951         temp = I915_READ(reg);
3952         temp &= ~FDI_LINK_TRAIN_NONE;
3953         temp |= FDI_LINK_TRAIN_PATTERN_1;
3954         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3955
3956         POSTING_READ(reg);
3957         udelay(150);
3958
3959         /* Ironlake workaround, enable clock pointer after FDI enable*/
3960         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3961         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3962                    FDI_RX_PHASE_SYNC_POINTER_EN);
3963
3964         reg = FDI_RX_IIR(pipe);
3965         for (tries = 0; tries < 5; tries++) {
3966                 temp = I915_READ(reg);
3967                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3968
3969                 if ((temp & FDI_RX_BIT_LOCK)) {
3970                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3971                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3972                         break;
3973                 }
3974         }
3975         if (tries == 5)
3976                 DRM_ERROR("FDI train 1 fail!\n");
3977
3978         /* Train 2 */
3979         reg = FDI_TX_CTL(pipe);
3980         temp = I915_READ(reg);
3981         temp &= ~FDI_LINK_TRAIN_NONE;
3982         temp |= FDI_LINK_TRAIN_PATTERN_2;
3983         I915_WRITE(reg, temp);
3984
3985         reg = FDI_RX_CTL(pipe);
3986         temp = I915_READ(reg);
3987         temp &= ~FDI_LINK_TRAIN_NONE;
3988         temp |= FDI_LINK_TRAIN_PATTERN_2;
3989         I915_WRITE(reg, temp);
3990
3991         POSTING_READ(reg);
3992         udelay(150);
3993
3994         reg = FDI_RX_IIR(pipe);
3995         for (tries = 0; tries < 5; tries++) {
3996                 temp = I915_READ(reg);
3997                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3998
3999                 if (temp & FDI_RX_SYMBOL_LOCK) {
4000                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4001                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4002                         break;
4003                 }
4004         }
4005         if (tries == 5)
4006                 DRM_ERROR("FDI train 2 fail!\n");
4007
4008         DRM_DEBUG_KMS("FDI train done\n");
4009
4010 }
4011
4012 static const int snb_b_fdi_train_param[] = {
4013         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4014         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4015         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4016         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4017 };
4018
4019 /* The FDI link training functions for SNB/Cougarpoint. */
4020 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4021                                 const struct intel_crtc_state *crtc_state)
4022 {
4023         struct drm_device *dev = crtc->base.dev;
4024         struct drm_i915_private *dev_priv = to_i915(dev);
4025         int pipe = crtc->pipe;
4026         i915_reg_t reg;
4027         u32 temp, i, retry;
4028
4029         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4030            for train result */
4031         reg = FDI_RX_IMR(pipe);
4032         temp = I915_READ(reg);
4033         temp &= ~FDI_RX_SYMBOL_LOCK;
4034         temp &= ~FDI_RX_BIT_LOCK;
4035         I915_WRITE(reg, temp);
4036
4037         POSTING_READ(reg);
4038         udelay(150);
4039
4040         /* enable CPU FDI TX and PCH FDI RX */
4041         reg = FDI_TX_CTL(pipe);
4042         temp = I915_READ(reg);
4043         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4044         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4045         temp &= ~FDI_LINK_TRAIN_NONE;
4046         temp |= FDI_LINK_TRAIN_PATTERN_1;
4047         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4048         /* SNB-B */
4049         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4050         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4051
4052         I915_WRITE(FDI_RX_MISC(pipe),
4053                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4054
4055         reg = FDI_RX_CTL(pipe);
4056         temp = I915_READ(reg);
4057         if (HAS_PCH_CPT(dev_priv)) {
4058                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4059                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4060         } else {
4061                 temp &= ~FDI_LINK_TRAIN_NONE;
4062                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4063         }
4064         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4065
4066         POSTING_READ(reg);
4067         udelay(150);
4068
4069         for (i = 0; i < 4; i++) {
4070                 reg = FDI_TX_CTL(pipe);
4071                 temp = I915_READ(reg);
4072                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4073                 temp |= snb_b_fdi_train_param[i];
4074                 I915_WRITE(reg, temp);
4075
4076                 POSTING_READ(reg);
4077                 udelay(500);
4078
4079                 for (retry = 0; retry < 5; retry++) {
4080                         reg = FDI_RX_IIR(pipe);
4081                         temp = I915_READ(reg);
4082                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4083                         if (temp & FDI_RX_BIT_LOCK) {
4084                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4085                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4086                                 break;
4087                         }
4088                         udelay(50);
4089                 }
4090                 if (retry < 5)
4091                         break;
4092         }
4093         if (i == 4)
4094                 DRM_ERROR("FDI train 1 fail!\n");
4095
4096         /* Train 2 */
4097         reg = FDI_TX_CTL(pipe);
4098         temp = I915_READ(reg);
4099         temp &= ~FDI_LINK_TRAIN_NONE;
4100         temp |= FDI_LINK_TRAIN_PATTERN_2;
4101         if (IS_GEN6(dev_priv)) {
4102                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4103                 /* SNB-B */
4104                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4105         }
4106         I915_WRITE(reg, temp);
4107
4108         reg = FDI_RX_CTL(pipe);
4109         temp = I915_READ(reg);
4110         if (HAS_PCH_CPT(dev_priv)) {
4111                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4112                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4113         } else {
4114                 temp &= ~FDI_LINK_TRAIN_NONE;
4115                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4116         }
4117         I915_WRITE(reg, temp);
4118
4119         POSTING_READ(reg);
4120         udelay(150);
4121
4122         for (i = 0; i < 4; i++) {
4123                 reg = FDI_TX_CTL(pipe);
4124                 temp = I915_READ(reg);
4125                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4126                 temp |= snb_b_fdi_train_param[i];
4127                 I915_WRITE(reg, temp);
4128
4129                 POSTING_READ(reg);
4130                 udelay(500);
4131
4132                 for (retry = 0; retry < 5; retry++) {
4133                         reg = FDI_RX_IIR(pipe);
4134                         temp = I915_READ(reg);
4135                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4136                         if (temp & FDI_RX_SYMBOL_LOCK) {
4137                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4138                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4139                                 break;
4140                         }
4141                         udelay(50);
4142                 }
4143                 if (retry < 5)
4144                         break;
4145         }
4146         if (i == 4)
4147                 DRM_ERROR("FDI train 2 fail!\n");
4148
4149         DRM_DEBUG_KMS("FDI train done.\n");
4150 }
4151
4152 /* Manual link training for Ivy Bridge A0 parts */
4153 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4154                                       const struct intel_crtc_state *crtc_state)
4155 {
4156         struct drm_device *dev = crtc->base.dev;
4157         struct drm_i915_private *dev_priv = to_i915(dev);
4158         int pipe = crtc->pipe;
4159         i915_reg_t reg;
4160         u32 temp, i, j;
4161
4162         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4163            for train result */
4164         reg = FDI_RX_IMR(pipe);
4165         temp = I915_READ(reg);
4166         temp &= ~FDI_RX_SYMBOL_LOCK;
4167         temp &= ~FDI_RX_BIT_LOCK;
4168         I915_WRITE(reg, temp);
4169
4170         POSTING_READ(reg);
4171         udelay(150);
4172
4173         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4174                       I915_READ(FDI_RX_IIR(pipe)));
4175
4176         /* Try each vswing and preemphasis setting twice before moving on */
4177         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4178                 /* disable first in case we need to retry */
4179                 reg = FDI_TX_CTL(pipe);
4180                 temp = I915_READ(reg);
4181                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4182                 temp &= ~FDI_TX_ENABLE;
4183                 I915_WRITE(reg, temp);
4184
4185                 reg = FDI_RX_CTL(pipe);
4186                 temp = I915_READ(reg);
4187                 temp &= ~FDI_LINK_TRAIN_AUTO;
4188                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4189                 temp &= ~FDI_RX_ENABLE;
4190                 I915_WRITE(reg, temp);
4191
4192                 /* enable CPU FDI TX and PCH FDI RX */
4193                 reg = FDI_TX_CTL(pipe);
4194                 temp = I915_READ(reg);
4195                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4196                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4197                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4198                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4199                 temp |= snb_b_fdi_train_param[j/2];
4200                 temp |= FDI_COMPOSITE_SYNC;
4201                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4202
4203                 I915_WRITE(FDI_RX_MISC(pipe),
4204                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4205
4206                 reg = FDI_RX_CTL(pipe);
4207                 temp = I915_READ(reg);
4208                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4209                 temp |= FDI_COMPOSITE_SYNC;
4210                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4211
4212                 POSTING_READ(reg);
4213                 udelay(1); /* should be 0.5us */
4214
4215                 for (i = 0; i < 4; i++) {
4216                         reg = FDI_RX_IIR(pipe);
4217                         temp = I915_READ(reg);
4218                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4219
4220                         if (temp & FDI_RX_BIT_LOCK ||
4221                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4222                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4223                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4224                                               i);
4225                                 break;
4226                         }
4227                         udelay(1); /* should be 0.5us */
4228                 }
4229                 if (i == 4) {
4230                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4231                         continue;
4232                 }
4233
4234                 /* Train 2 */
4235                 reg = FDI_TX_CTL(pipe);
4236                 temp = I915_READ(reg);
4237                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4238                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4239                 I915_WRITE(reg, temp);
4240
4241                 reg = FDI_RX_CTL(pipe);
4242                 temp = I915_READ(reg);
4243                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4244                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4245                 I915_WRITE(reg, temp);
4246
4247                 POSTING_READ(reg);
4248                 udelay(2); /* should be 1.5us */
4249
4250                 for (i = 0; i < 4; i++) {
4251                         reg = FDI_RX_IIR(pipe);
4252                         temp = I915_READ(reg);
4253                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4254
4255                         if (temp & FDI_RX_SYMBOL_LOCK ||
4256                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4257                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4258                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4259                                               i);
4260                                 goto train_done;
4261                         }
4262                         udelay(2); /* should be 1.5us */
4263                 }
4264                 if (i == 4)
4265                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4266         }
4267
4268 train_done:
4269         DRM_DEBUG_KMS("FDI train done.\n");
4270 }
4271
4272 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4273 {
4274         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4275         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4276         int pipe = intel_crtc->pipe;
4277         i915_reg_t reg;
4278         u32 temp;
4279
4280         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4281         reg = FDI_RX_CTL(pipe);
4282         temp = I915_READ(reg);
4283         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4284         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4285         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4286         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4287
4288         POSTING_READ(reg);
4289         udelay(200);
4290
4291         /* Switch from Rawclk to PCDclk */
4292         temp = I915_READ(reg);
4293         I915_WRITE(reg, temp | FDI_PCDCLK);
4294
4295         POSTING_READ(reg);
4296         udelay(200);
4297
4298         /* Enable CPU FDI TX PLL, always on for Ironlake */
4299         reg = FDI_TX_CTL(pipe);
4300         temp = I915_READ(reg);
4301         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4302                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4303
4304                 POSTING_READ(reg);
4305                 udelay(100);
4306         }
4307 }
4308
4309 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4310 {
4311         struct drm_device *dev = intel_crtc->base.dev;
4312         struct drm_i915_private *dev_priv = to_i915(dev);
4313         int pipe = intel_crtc->pipe;
4314         i915_reg_t reg;
4315         u32 temp;
4316
4317         /* Switch from PCDclk to Rawclk */
4318         reg = FDI_RX_CTL(pipe);
4319         temp = I915_READ(reg);
4320         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4321
4322         /* Disable CPU FDI TX PLL */
4323         reg = FDI_TX_CTL(pipe);
4324         temp = I915_READ(reg);
4325         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4326
4327         POSTING_READ(reg);
4328         udelay(100);
4329
4330         reg = FDI_RX_CTL(pipe);
4331         temp = I915_READ(reg);
4332         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4333
4334         /* Wait for the clocks to turn off. */
4335         POSTING_READ(reg);
4336         udelay(100);
4337 }
4338
4339 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4340 {
4341         struct drm_device *dev = crtc->dev;
4342         struct drm_i915_private *dev_priv = to_i915(dev);
4343         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4344         int pipe = intel_crtc->pipe;
4345         i915_reg_t reg;
4346         u32 temp;
4347
4348         /* disable CPU FDI tx and PCH FDI rx */
4349         reg = FDI_TX_CTL(pipe);
4350         temp = I915_READ(reg);
4351         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4352         POSTING_READ(reg);
4353
4354         reg = FDI_RX_CTL(pipe);
4355         temp = I915_READ(reg);
4356         temp &= ~(0x7 << 16);
4357         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4358         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4359
4360         POSTING_READ(reg);
4361         udelay(100);
4362
4363         /* Ironlake workaround, disable clock pointer after downing FDI */
4364         if (HAS_PCH_IBX(dev_priv))
4365                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4366
4367         /* still set train pattern 1 */
4368         reg = FDI_TX_CTL(pipe);
4369         temp = I915_READ(reg);
4370         temp &= ~FDI_LINK_TRAIN_NONE;
4371         temp |= FDI_LINK_TRAIN_PATTERN_1;
4372         I915_WRITE(reg, temp);
4373
4374         reg = FDI_RX_CTL(pipe);
4375         temp = I915_READ(reg);
4376         if (HAS_PCH_CPT(dev_priv)) {
4377                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4378                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4379         } else {
4380                 temp &= ~FDI_LINK_TRAIN_NONE;
4381                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4382         }
4383         /* BPC in FDI rx is consistent with that in PIPECONF */
4384         temp &= ~(0x07 << 16);
4385         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4386         I915_WRITE(reg, temp);
4387
4388         POSTING_READ(reg);
4389         udelay(100);
4390 }
4391
4392 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4393 {
4394         struct drm_crtc *crtc;
4395         bool cleanup_done;
4396
4397         drm_for_each_crtc(crtc, &dev_priv->drm) {
4398                 struct drm_crtc_commit *commit;
4399                 spin_lock(&crtc->commit_lock);
4400                 commit = list_first_entry_or_null(&crtc->commit_list,
4401                                                   struct drm_crtc_commit, commit_entry);
4402                 cleanup_done = commit ?
4403                         try_wait_for_completion(&commit->cleanup_done) : true;
4404                 spin_unlock(&crtc->commit_lock);
4405
4406                 if (cleanup_done)
4407                         continue;
4408
4409                 drm_crtc_wait_one_vblank(crtc);
4410
4411                 return true;
4412         }
4413
4414         return false;
4415 }
4416
4417 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4418 {
4419         u32 temp;
4420
4421         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4422
4423         mutex_lock(&dev_priv->sb_lock);
4424
4425         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4426         temp |= SBI_SSCCTL_DISABLE;
4427         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4428
4429         mutex_unlock(&dev_priv->sb_lock);
4430 }
4431
4432 /* Program iCLKIP clock to the desired frequency */
4433 static void lpt_program_iclkip(const struct intel_crtc_state *crtc_state)
4434 {
4435         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4436         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4437         int clock = crtc_state->base.adjusted_mode.crtc_clock;
4438         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4439         u32 temp;
4440
4441         lpt_disable_iclkip(dev_priv);
4442
4443         /* The iCLK virtual clock root frequency is in MHz,
4444          * but the adjusted_mode->crtc_clock in in KHz. To get the
4445          * divisors, it is necessary to divide one by another, so we
4446          * convert the virtual clock precision to KHz here for higher
4447          * precision.
4448          */
4449         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4450                 u32 iclk_virtual_root_freq = 172800 * 1000;
4451                 u32 iclk_pi_range = 64;
4452                 u32 desired_divisor;
4453
4454                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4455                                                     clock << auxdiv);
4456                 divsel = (desired_divisor / iclk_pi_range) - 2;
4457                 phaseinc = desired_divisor % iclk_pi_range;
4458
4459                 /*
4460                  * Near 20MHz is a corner case which is
4461                  * out of range for the 7-bit divisor
4462                  */
4463                 if (divsel <= 0x7f)
4464                         break;
4465         }
4466
4467         /* This should not happen with any sane values */
4468         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4469                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4470         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4471                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4472
4473         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4474                         clock,
4475                         auxdiv,
4476                         divsel,
4477                         phasedir,
4478                         phaseinc);
4479
4480         mutex_lock(&dev_priv->sb_lock);
4481
4482         /* Program SSCDIVINTPHASE6 */
4483         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4484         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4485         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4486         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4487         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4488         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4489         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4490         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4491
4492         /* Program SSCAUXDIV */
4493         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4494         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4495         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4496         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4497
4498         /* Enable modulator and associated divider */
4499         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4500         temp &= ~SBI_SSCCTL_DISABLE;
4501         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4502
4503         mutex_unlock(&dev_priv->sb_lock);
4504
4505         /* Wait for initialization time */
4506         udelay(24);
4507
4508         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4509 }
4510
4511 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4512 {
4513         u32 divsel, phaseinc, auxdiv;
4514         u32 iclk_virtual_root_freq = 172800 * 1000;
4515         u32 iclk_pi_range = 64;
4516         u32 desired_divisor;
4517         u32 temp;
4518
4519         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4520                 return 0;
4521
4522         mutex_lock(&dev_priv->sb_lock);
4523
4524         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4525         if (temp & SBI_SSCCTL_DISABLE) {
4526                 mutex_unlock(&dev_priv->sb_lock);
4527                 return 0;
4528         }
4529
4530         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4531         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4532                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4533         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4534                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4535
4536         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4537         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4538                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4539
4540         mutex_unlock(&dev_priv->sb_lock);
4541
4542         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4543
4544         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4545                                  desired_divisor << auxdiv);
4546 }
4547
4548 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
4549                                                 enum pipe pch_transcoder)
4550 {
4551         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4552         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4553         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4554
4555         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4556                    I915_READ(HTOTAL(cpu_transcoder)));
4557         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4558                    I915_READ(HBLANK(cpu_transcoder)));
4559         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4560                    I915_READ(HSYNC(cpu_transcoder)));
4561
4562         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4563                    I915_READ(VTOTAL(cpu_transcoder)));
4564         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4565                    I915_READ(VBLANK(cpu_transcoder)));
4566         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4567                    I915_READ(VSYNC(cpu_transcoder)));
4568         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4569                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4570 }
4571
4572 static void cpt_set_fdi_bc_bifurcation(struct drm_i915_private *dev_priv, bool enable)
4573 {
4574         uint32_t temp;
4575
4576         temp = I915_READ(SOUTH_CHICKEN1);
4577         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4578                 return;
4579
4580         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4581         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4582
4583         temp &= ~FDI_BC_BIFURCATION_SELECT;
4584         if (enable)
4585                 temp |= FDI_BC_BIFURCATION_SELECT;
4586
4587         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4588         I915_WRITE(SOUTH_CHICKEN1, temp);
4589         POSTING_READ(SOUTH_CHICKEN1);
4590 }
4591
4592 static void ivybridge_update_fdi_bc_bifurcation(const struct intel_crtc_state *crtc_state)
4593 {
4594         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4595         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4596
4597         switch (crtc->pipe) {
4598         case PIPE_A:
4599                 break;
4600         case PIPE_B:
4601                 if (crtc_state->fdi_lanes > 2)
4602                         cpt_set_fdi_bc_bifurcation(dev_priv, false);
4603                 else
4604                         cpt_set_fdi_bc_bifurcation(dev_priv, true);
4605
4606                 break;
4607         case PIPE_C:
4608                 cpt_set_fdi_bc_bifurcation(dev_priv, true);
4609
4610                 break;
4611         default:
4612                 BUG();
4613         }
4614 }
4615
4616 /*
4617  * Finds the encoder associated with the given CRTC. This can only be
4618  * used when we know that the CRTC isn't feeding multiple encoders!
4619  */
4620 static struct intel_encoder *
4621 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4622                            const struct intel_crtc_state *crtc_state)
4623 {
4624         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4625         const struct drm_connector_state *connector_state;
4626         const struct drm_connector *connector;
4627         struct intel_encoder *encoder = NULL;
4628         int num_encoders = 0;
4629         int i;
4630
4631         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4632                 if (connector_state->crtc != &crtc->base)
4633                         continue;
4634
4635                 encoder = to_intel_encoder(connector_state->best_encoder);
4636                 num_encoders++;
4637         }
4638
4639         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4640              num_encoders, pipe_name(crtc->pipe));
4641
4642         return encoder;
4643 }
4644
4645 /*
4646  * Enable PCH resources required for PCH ports:
4647  *   - PCH PLLs
4648  *   - FDI training & RX/TX
4649  *   - update transcoder timings
4650  *   - DP transcoding bits
4651  *   - transcoder
4652  */
4653 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4654                                 const struct intel_crtc_state *crtc_state)
4655 {
4656         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4657         struct drm_device *dev = crtc->base.dev;
4658         struct drm_i915_private *dev_priv = to_i915(dev);
4659         int pipe = crtc->pipe;
4660         u32 temp;
4661
4662         assert_pch_transcoder_disabled(dev_priv, pipe);
4663
4664         if (IS_IVYBRIDGE(dev_priv))
4665                 ivybridge_update_fdi_bc_bifurcation(crtc_state);
4666
4667         /* Write the TU size bits before fdi link training, so that error
4668          * detection works. */
4669         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4670                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4671
4672         /* For PCH output, training FDI link */
4673         dev_priv->display.fdi_link_train(crtc, crtc_state);
4674
4675         /* We need to program the right clock selection before writing the pixel
4676          * mutliplier into the DPLL. */
4677         if (HAS_PCH_CPT(dev_priv)) {
4678                 u32 sel;
4679
4680                 temp = I915_READ(PCH_DPLL_SEL);
4681                 temp |= TRANS_DPLL_ENABLE(pipe);
4682                 sel = TRANS_DPLLB_SEL(pipe);
4683                 if (crtc_state->shared_dpll ==
4684                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4685                         temp |= sel;
4686                 else
4687                         temp &= ~sel;
4688                 I915_WRITE(PCH_DPLL_SEL, temp);
4689         }
4690
4691         /* XXX: pch pll's can be enabled any time before we enable the PCH
4692          * transcoder, and we actually should do this to not upset any PCH
4693          * transcoder that already use the clock when we share it.
4694          *
4695          * Note that enable_shared_dpll tries to do the right thing, but
4696          * get_shared_dpll unconditionally resets the pll - we need that to have
4697          * the right LVDS enable sequence. */
4698         intel_enable_shared_dpll(crtc_state);
4699
4700         /* set transcoder timing, panel must allow it */
4701         assert_panel_unlocked(dev_priv, pipe);
4702         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
4703
4704         intel_fdi_normal_train(crtc);
4705
4706         /* For PCH DP, enable TRANS_DP_CTL */
4707         if (HAS_PCH_CPT(dev_priv) &&
4708             intel_crtc_has_dp_encoder(crtc_state)) {
4709                 const struct drm_display_mode *adjusted_mode =
4710                         &crtc_state->base.adjusted_mode;
4711                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4712                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4713                 enum port port;
4714
4715                 temp = I915_READ(reg);
4716                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4717                           TRANS_DP_SYNC_MASK |
4718                           TRANS_DP_BPC_MASK);
4719                 temp |= TRANS_DP_OUTPUT_ENABLE;
4720                 temp |= bpc << 9; /* same format but at 11:9 */
4721
4722                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4723                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4724                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4725                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4726
4727                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4728                 WARN_ON(port < PORT_B || port > PORT_D);
4729                 temp |= TRANS_DP_PORT_SEL(port);
4730
4731                 I915_WRITE(reg, temp);
4732         }
4733
4734         ironlake_enable_pch_transcoder(crtc_state);
4735 }
4736
4737 static void lpt_pch_enable(const struct intel_atomic_state *state,
4738                            const struct intel_crtc_state *crtc_state)
4739 {
4740         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4741         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4742         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4743
4744         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4745
4746         lpt_program_iclkip(crtc_state);
4747
4748         /* Set transcoder timing. */
4749         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
4750
4751         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4752 }
4753
4754 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4755 {
4756         struct drm_i915_private *dev_priv = to_i915(dev);
4757         i915_reg_t dslreg = PIPEDSL(pipe);
4758         u32 temp;
4759
4760         temp = I915_READ(dslreg);
4761         udelay(500);
4762         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4763                 if (wait_for(I915_READ(dslreg) != temp, 5))
4764                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4765         }
4766 }
4767
4768 /*
4769  * The hardware phase 0.0 refers to the center of the pixel.
4770  * We want to start from the top/left edge which is phase
4771  * -0.5. That matches how the hardware calculates the scaling
4772  * factors (from top-left of the first pixel to bottom-right
4773  * of the last pixel, as opposed to the pixel centers).
4774  *
4775  * For 4:2:0 subsampled chroma planes we obviously have to
4776  * adjust that so that the chroma sample position lands in
4777  * the right spot.
4778  *
4779  * Note that for packed YCbCr 4:2:2 formats there is no way to
4780  * control chroma siting. The hardware simply replicates the
4781  * chroma samples for both of the luma samples, and thus we don't
4782  * actually get the expected MPEG2 chroma siting convention :(
4783  * The same behaviour is observed on pre-SKL platforms as well.
4784  *
4785  * Theory behind the formula (note that we ignore sub-pixel
4786  * source coordinates):
4787  * s = source sample position
4788  * d = destination sample position
4789  *
4790  * Downscaling 4:1:
4791  * -0.5
4792  * | 0.0
4793  * | |     1.5 (initial phase)
4794  * | |     |
4795  * v v     v
4796  * | s | s | s | s |
4797  * |       d       |
4798  *
4799  * Upscaling 1:4:
4800  * -0.5
4801  * | -0.375 (initial phase)
4802  * | |     0.0
4803  * | |     |
4804  * v v     v
4805  * |       s       |
4806  * | d | d | d | d |
4807  */
4808 u16 skl_scaler_calc_phase(int sub, int scale, bool chroma_cosited)
4809 {
4810         int phase = -0x8000;
4811         u16 trip = 0;
4812
4813         if (chroma_cosited)
4814                 phase += (sub - 1) * 0x8000 / sub;
4815
4816         phase += scale / (2 * sub);
4817
4818         /*
4819          * Hardware initial phase limited to [-0.5:1.5].
4820          * Since the max hardware scale factor is 3.0, we
4821          * should never actually excdeed 1.0 here.
4822          */
4823         WARN_ON(phase < -0x8000 || phase > 0x18000);
4824
4825         if (phase < 0)
4826                 phase = 0x10000 + phase;
4827         else
4828                 trip = PS_PHASE_TRIP;
4829
4830         return ((phase >> 2) & PS_PHASE_MASK) | trip;
4831 }
4832
4833 static int
4834 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4835                   unsigned int scaler_user, int *scaler_id,
4836                   int src_w, int src_h, int dst_w, int dst_h,
4837                   const struct drm_format_info *format, bool need_scaler)
4838 {
4839         struct intel_crtc_scaler_state *scaler_state =
4840                 &crtc_state->scaler_state;
4841         struct intel_crtc *intel_crtc =
4842                 to_intel_crtc(crtc_state->base.crtc);
4843         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4844         const struct drm_display_mode *adjusted_mode =
4845                 &crtc_state->base.adjusted_mode;
4846
4847         /*
4848          * Src coordinates are already rotated by 270 degrees for
4849          * the 90/270 degree plane rotation cases (to match the
4850          * GTT mapping), hence no need to account for rotation here.
4851          */
4852         if (src_w != dst_w || src_h != dst_h)
4853                 need_scaler = true;
4854
4855         /*
4856          * Scaling/fitting not supported in IF-ID mode in GEN9+
4857          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4858          * Once NV12 is enabled, handle it here while allocating scaler
4859          * for NV12.
4860          */
4861         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4862             need_scaler && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4863                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4864                 return -EINVAL;
4865         }
4866
4867         /*
4868          * if plane is being disabled or scaler is no more required or force detach
4869          *  - free scaler binded to this plane/crtc
4870          *  - in order to do this, update crtc->scaler_usage
4871          *
4872          * Here scaler state in crtc_state is set free so that
4873          * scaler can be assigned to other user. Actual register
4874          * update to free the scaler is done in plane/panel-fit programming.
4875          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4876          */
4877         if (force_detach || !need_scaler) {
4878                 if (*scaler_id >= 0) {
4879                         scaler_state->scaler_users &= ~(1 << scaler_user);
4880                         scaler_state->scalers[*scaler_id].in_use = 0;
4881
4882                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4883                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4884                                 intel_crtc->pipe, scaler_user, *scaler_id,
4885                                 scaler_state->scaler_users);
4886                         *scaler_id = -1;
4887                 }
4888                 return 0;
4889         }
4890
4891         if (format && format->format == DRM_FORMAT_NV12 &&
4892             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4893                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4894                 return -EINVAL;
4895         }
4896
4897         /* range checks */
4898         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4899             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4900             (IS_GEN11(dev_priv) &&
4901              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4902               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4903             (!IS_GEN11(dev_priv) &&
4904              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4905               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4906                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4907                         "size is out of scaler range\n",
4908                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4909                 return -EINVAL;
4910         }
4911
4912         /* mark this plane as a scaler user in crtc_state */
4913         scaler_state->scaler_users |= (1 << scaler_user);
4914         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4915                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4916                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4917                 scaler_state->scaler_users);
4918
4919         return 0;
4920 }
4921
4922 /**
4923  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4924  *
4925  * @state: crtc's scaler state
4926  *
4927  * Return
4928  *     0 - scaler_usage updated successfully
4929  *    error - requested scaling cannot be supported or other error condition
4930  */
4931 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4932 {
4933         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4934         bool need_scaler = false;
4935
4936         if (state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
4937                 need_scaler = true;
4938
4939         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4940                                  &state->scaler_state.scaler_id,
4941                                  state->pipe_src_w, state->pipe_src_h,
4942                                  adjusted_mode->crtc_hdisplay,
4943                                  adjusted_mode->crtc_vdisplay, NULL, need_scaler);
4944 }
4945
4946 /**
4947  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4948  * @crtc_state: crtc's scaler state
4949  * @plane_state: atomic plane state to update
4950  *
4951  * Return
4952  *     0 - scaler_usage updated successfully
4953  *    error - requested scaling cannot be supported or other error condition
4954  */
4955 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4956                                    struct intel_plane_state *plane_state)
4957 {
4958         struct intel_plane *intel_plane =
4959                 to_intel_plane(plane_state->base.plane);
4960         struct drm_framebuffer *fb = plane_state->base.fb;
4961         int ret;
4962         bool force_detach = !fb || !plane_state->base.visible;
4963         bool need_scaler = false;
4964
4965         /* Pre-gen11 and SDR planes always need a scaler for planar formats. */
4966         if (!icl_is_hdr_plane(intel_plane) &&
4967             fb && fb->format->format == DRM_FORMAT_NV12)
4968                 need_scaler = true;
4969
4970         ret = skl_update_scaler(crtc_state, force_detach,
4971                                 drm_plane_index(&intel_plane->base),
4972                                 &plane_state->scaler_id,
4973                                 drm_rect_width(&plane_state->base.src) >> 16,
4974                                 drm_rect_height(&plane_state->base.src) >> 16,
4975                                 drm_rect_width(&plane_state->base.dst),
4976                                 drm_rect_height(&plane_state->base.dst),
4977                                 fb ? fb->format : NULL, need_scaler);
4978
4979         if (ret || plane_state->scaler_id < 0)
4980                 return ret;
4981
4982         /* check colorkey */
4983         if (plane_state->ckey.flags) {
4984                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4985                               intel_plane->base.base.id,
4986                               intel_plane->base.name);
4987                 return -EINVAL;
4988         }
4989
4990         /* Check src format */
4991         switch (fb->format->format) {
4992         case DRM_FORMAT_RGB565:
4993         case DRM_FORMAT_XBGR8888:
4994         case DRM_FORMAT_XRGB8888:
4995         case DRM_FORMAT_ABGR8888:
4996         case DRM_FORMAT_ARGB8888:
4997         case DRM_FORMAT_XRGB2101010:
4998         case DRM_FORMAT_XBGR2101010:
4999         case DRM_FORMAT_YUYV:
5000         case DRM_FORMAT_YVYU:
5001         case DRM_FORMAT_UYVY:
5002         case DRM_FORMAT_VYUY:
5003         case DRM_FORMAT_NV12:
5004                 break;
5005         default:
5006                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5007                               intel_plane->base.base.id, intel_plane->base.name,
5008                               fb->base.id, fb->format->format);
5009                 return -EINVAL;
5010         }
5011
5012         return 0;
5013 }
5014
5015 static void skylake_scaler_disable(struct intel_crtc *crtc)
5016 {
5017         int i;
5018
5019         for (i = 0; i < crtc->num_scalers; i++)
5020                 skl_detach_scaler(crtc, i);
5021 }
5022
5023 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5024 {
5025         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5026         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5027         enum pipe pipe = crtc->pipe;
5028         const struct intel_crtc_scaler_state *scaler_state =
5029                 &crtc_state->scaler_state;
5030
5031         if (crtc_state->pch_pfit.enabled) {
5032                 u16 uv_rgb_hphase, uv_rgb_vphase;
5033                 int pfit_w, pfit_h, hscale, vscale;
5034                 int id;
5035
5036                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5037                         return;
5038
5039                 pfit_w = (crtc_state->pch_pfit.size >> 16) & 0xFFFF;
5040                 pfit_h = crtc_state->pch_pfit.size & 0xFFFF;
5041
5042                 hscale = (crtc_state->pipe_src_w << 16) / pfit_w;
5043                 vscale = (crtc_state->pipe_src_h << 16) / pfit_h;
5044
5045                 uv_rgb_hphase = skl_scaler_calc_phase(1, hscale, false);
5046                 uv_rgb_vphase = skl_scaler_calc_phase(1, vscale, false);
5047
5048                 id = scaler_state->scaler_id;
5049                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5050                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5051                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5052                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5053                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5054                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5055                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5056                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5057         }
5058 }
5059
5060 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5061 {
5062         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5063         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5064         int pipe = crtc->pipe;
5065
5066         if (crtc_state->pch_pfit.enabled) {
5067                 /* Force use of hard-coded filter coefficients
5068                  * as some pre-programmed values are broken,
5069                  * e.g. x201.
5070                  */
5071                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5072                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5073                                                  PF_PIPE_SEL_IVB(pipe));
5074                 else
5075                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5076                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5077                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5078         }
5079 }
5080
5081 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5082 {
5083         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5084         struct drm_device *dev = crtc->base.dev;
5085         struct drm_i915_private *dev_priv = to_i915(dev);
5086
5087         if (!crtc_state->ips_enabled)
5088                 return;
5089
5090         /*
5091          * We can only enable IPS after we enable a plane and wait for a vblank
5092          * This function is called from post_plane_update, which is run after
5093          * a vblank wait.
5094          */
5095         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5096
5097         if (IS_BROADWELL(dev_priv)) {
5098                 mutex_lock(&dev_priv->pcu_lock);
5099                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5100                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5101                 mutex_unlock(&dev_priv->pcu_lock);
5102                 /* Quoting Art Runyan: "its not safe to expect any particular
5103                  * value in IPS_CTL bit 31 after enabling IPS through the
5104                  * mailbox." Moreover, the mailbox may return a bogus state,
5105                  * so we need to just enable it and continue on.
5106                  */
5107         } else {
5108                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5109                 /* The bit only becomes 1 in the next vblank, so this wait here
5110                  * is essentially intel_wait_for_vblank. If we don't have this
5111                  * and don't wait for vblanks until the end of crtc_enable, then
5112                  * the HW state readout code will complain that the expected
5113                  * IPS_CTL value is not the one we read. */
5114                 if (intel_wait_for_register(dev_priv,
5115                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5116                                             50))
5117                         DRM_ERROR("Timed out waiting for IPS enable\n");
5118         }
5119 }
5120
5121 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5122 {
5123         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5124         struct drm_device *dev = crtc->base.dev;
5125         struct drm_i915_private *dev_priv = to_i915(dev);
5126
5127         if (!crtc_state->ips_enabled)
5128                 return;
5129
5130         if (IS_BROADWELL(dev_priv)) {
5131                 mutex_lock(&dev_priv->pcu_lock);
5132                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5133                 mutex_unlock(&dev_priv->pcu_lock);
5134                 /*
5135                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5136                  * 42ms timeout value leads to occasional timeouts so use 100ms
5137                  * instead.
5138                  */
5139                 if (intel_wait_for_register(dev_priv,
5140                                             IPS_CTL, IPS_ENABLE, 0,
5141                                             100))
5142                         DRM_ERROR("Timed out waiting for IPS disable\n");
5143         } else {
5144                 I915_WRITE(IPS_CTL, 0);
5145                 POSTING_READ(IPS_CTL);
5146         }
5147
5148         /* We need to wait for a vblank before we can disable the plane. */
5149         intel_wait_for_vblank(dev_priv, crtc->pipe);
5150 }
5151
5152 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5153 {
5154         if (intel_crtc->overlay) {
5155                 struct drm_device *dev = intel_crtc->base.dev;
5156
5157                 mutex_lock(&dev->struct_mutex);
5158                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5159                 mutex_unlock(&dev->struct_mutex);
5160         }
5161
5162         /* Let userspace switch the overlay on again. In most cases userspace
5163          * has to recompute where to put it anyway.
5164          */
5165 }
5166
5167 /**
5168  * intel_post_enable_primary - Perform operations after enabling primary plane
5169  * @crtc: the CRTC whose primary plane was just enabled
5170  * @new_crtc_state: the enabling state
5171  *
5172  * Performs potentially sleeping operations that must be done after the primary
5173  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5174  * called due to an explicit primary plane update, or due to an implicit
5175  * re-enable that is caused when a sprite plane is updated to no longer
5176  * completely hide the primary plane.
5177  */
5178 static void
5179 intel_post_enable_primary(struct drm_crtc *crtc,
5180                           const struct intel_crtc_state *new_crtc_state)
5181 {
5182         struct drm_device *dev = crtc->dev;
5183         struct drm_i915_private *dev_priv = to_i915(dev);
5184         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5185         int pipe = intel_crtc->pipe;
5186
5187         /*
5188          * Gen2 reports pipe underruns whenever all planes are disabled.
5189          * So don't enable underrun reporting before at least some planes
5190          * are enabled.
5191          * FIXME: Need to fix the logic to work when we turn off all planes
5192          * but leave the pipe running.
5193          */
5194         if (IS_GEN2(dev_priv))
5195                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5196
5197         /* Underruns don't always raise interrupts, so check manually. */
5198         intel_check_cpu_fifo_underruns(dev_priv);
5199         intel_check_pch_fifo_underruns(dev_priv);
5200 }
5201
5202 /* FIXME get rid of this and use pre_plane_update */
5203 static void
5204 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5205 {
5206         struct drm_device *dev = crtc->dev;
5207         struct drm_i915_private *dev_priv = to_i915(dev);
5208         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5209         int pipe = intel_crtc->pipe;
5210
5211         /*
5212          * Gen2 reports pipe underruns whenever all planes are disabled.
5213          * So disable underrun reporting before all the planes get disabled.
5214          */
5215         if (IS_GEN2(dev_priv))
5216                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5217
5218         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5219
5220         /*
5221          * Vblank time updates from the shadow to live plane control register
5222          * are blocked if the memory self-refresh mode is active at that
5223          * moment. So to make sure the plane gets truly disabled, disable
5224          * first the self-refresh mode. The self-refresh enable bit in turn
5225          * will be checked/applied by the HW only at the next frame start
5226          * event which is after the vblank start event, so we need to have a
5227          * wait-for-vblank between disabling the plane and the pipe.
5228          */
5229         if (HAS_GMCH_DISPLAY(dev_priv) &&
5230             intel_set_memory_cxsr(dev_priv, false))
5231                 intel_wait_for_vblank(dev_priv, pipe);
5232 }
5233
5234 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5235                                        const struct intel_crtc_state *new_crtc_state)
5236 {
5237         if (!old_crtc_state->ips_enabled)
5238                 return false;
5239
5240         if (needs_modeset(&new_crtc_state->base))
5241                 return true;
5242
5243         return !new_crtc_state->ips_enabled;
5244 }
5245
5246 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5247                                        const struct intel_crtc_state *new_crtc_state)
5248 {
5249         if (!new_crtc_state->ips_enabled)
5250                 return false;
5251
5252         if (needs_modeset(&new_crtc_state->base))
5253                 return true;
5254
5255         /*
5256          * We can't read out IPS on broadwell, assume the worst and
5257          * forcibly enable IPS on the first fastset.
5258          */
5259         if (new_crtc_state->update_pipe &&
5260             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5261                 return true;
5262
5263         return !old_crtc_state->ips_enabled;
5264 }
5265
5266 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5267                           const struct intel_crtc_state *crtc_state)
5268 {
5269         if (!crtc_state->nv12_planes)
5270                 return false;
5271
5272         /* WA Display #0827: Gen9:all */
5273         if (IS_GEN9(dev_priv) && !IS_GEMINILAKE(dev_priv))
5274                 return true;
5275
5276         return false;
5277 }
5278
5279 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5280 {
5281         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5282         struct drm_device *dev = crtc->base.dev;
5283         struct drm_i915_private *dev_priv = to_i915(dev);
5284         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5285         struct intel_crtc_state *pipe_config =
5286                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5287                                                 crtc);
5288         struct drm_plane *primary = crtc->base.primary;
5289         struct drm_plane_state *old_primary_state =
5290                 drm_atomic_get_old_plane_state(old_state, primary);
5291
5292         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5293
5294         if (pipe_config->update_wm_post && pipe_config->base.active)
5295                 intel_update_watermarks(crtc);
5296
5297         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5298                 hsw_enable_ips(pipe_config);
5299
5300         if (old_primary_state) {
5301                 struct drm_plane_state *new_primary_state =
5302                         drm_atomic_get_new_plane_state(old_state, primary);
5303
5304                 intel_fbc_post_update(crtc);
5305
5306                 if (new_primary_state->visible &&
5307                     (needs_modeset(&pipe_config->base) ||
5308                      !old_primary_state->visible))
5309                         intel_post_enable_primary(&crtc->base, pipe_config);
5310         }
5311
5312         /* Display WA 827 */
5313         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5314             !needs_nv12_wa(dev_priv, pipe_config)) {
5315                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5316         }
5317 }
5318
5319 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5320                                    struct intel_crtc_state *pipe_config)
5321 {
5322         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5323         struct drm_device *dev = crtc->base.dev;
5324         struct drm_i915_private *dev_priv = to_i915(dev);
5325         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5326         struct drm_plane *primary = crtc->base.primary;
5327         struct drm_plane_state *old_primary_state =
5328                 drm_atomic_get_old_plane_state(old_state, primary);
5329         bool modeset = needs_modeset(&pipe_config->base);
5330         struct intel_atomic_state *old_intel_state =
5331                 to_intel_atomic_state(old_state);
5332
5333         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5334                 hsw_disable_ips(old_crtc_state);
5335
5336         if (old_primary_state) {
5337                 struct intel_plane_state *new_primary_state =
5338                         intel_atomic_get_new_plane_state(old_intel_state,
5339                                                          to_intel_plane(primary));
5340
5341                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5342                 /*
5343                  * Gen2 reports pipe underruns whenever all planes are disabled.
5344                  * So disable underrun reporting before all the planes get disabled.
5345                  */
5346                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5347                     (modeset || !new_primary_state->base.visible))
5348                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5349         }
5350
5351         /* Display WA 827 */
5352         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5353             needs_nv12_wa(dev_priv, pipe_config)) {
5354                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5355         }
5356
5357         /*
5358          * Vblank time updates from the shadow to live plane control register
5359          * are blocked if the memory self-refresh mode is active at that
5360          * moment. So to make sure the plane gets truly disabled, disable
5361          * first the self-refresh mode. The self-refresh enable bit in turn
5362          * will be checked/applied by the HW only at the next frame start
5363          * event which is after the vblank start event, so we need to have a
5364          * wait-for-vblank between disabling the plane and the pipe.
5365          */
5366         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5367             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5368                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5369
5370         /*
5371          * IVB workaround: must disable low power watermarks for at least
5372          * one frame before enabling scaling.  LP watermarks can be re-enabled
5373          * when scaling is disabled.
5374          *
5375          * WaCxSRDisabledForSpriteScaling:ivb
5376          */
5377         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5378             old_crtc_state->base.active)
5379                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5380
5381         /*
5382          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5383          * watermark programming here.
5384          */
5385         if (needs_modeset(&pipe_config->base))
5386                 return;
5387
5388         /*
5389          * For platforms that support atomic watermarks, program the
5390          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5391          * will be the intermediate values that are safe for both pre- and
5392          * post- vblank; when vblank happens, the 'active' values will be set
5393          * to the final 'target' values and we'll do this again to get the
5394          * optimal watermarks.  For gen9+ platforms, the values we program here
5395          * will be the final target values which will get automatically latched
5396          * at vblank time; no further programming will be necessary.
5397          *
5398          * If a platform hasn't been transitioned to atomic watermarks yet,
5399          * we'll continue to update watermarks the old way, if flags tell
5400          * us to.
5401          */
5402         if (dev_priv->display.initial_watermarks != NULL)
5403                 dev_priv->display.initial_watermarks(old_intel_state,
5404                                                      pipe_config);
5405         else if (pipe_config->update_wm_pre)
5406                 intel_update_watermarks(crtc);
5407 }
5408
5409 static void intel_crtc_disable_planes(struct intel_atomic_state *state,
5410                                       struct intel_crtc *crtc)
5411 {
5412         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5413         const struct intel_crtc_state *new_crtc_state =
5414                 intel_atomic_get_new_crtc_state(state, crtc);
5415         unsigned int update_mask = new_crtc_state->update_planes;
5416         const struct intel_plane_state *old_plane_state;
5417         struct intel_plane *plane;
5418         unsigned fb_bits = 0;
5419         int i;
5420
5421         intel_crtc_dpms_overlay_disable(crtc);
5422
5423         for_each_old_intel_plane_in_state(state, plane, old_plane_state, i) {
5424                 if (crtc->pipe != plane->pipe ||
5425                     !(update_mask & BIT(plane->id)))
5426                         continue;
5427
5428                 plane->disable_plane(plane, new_crtc_state);
5429
5430                 if (old_plane_state->base.visible)
5431                         fb_bits |= plane->frontbuffer_bit;
5432         }
5433
5434         intel_frontbuffer_flip(dev_priv, fb_bits);
5435 }
5436
5437 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5438                                           struct intel_crtc_state *crtc_state,
5439                                           struct drm_atomic_state *old_state)
5440 {
5441         struct drm_connector_state *conn_state;
5442         struct drm_connector *conn;
5443         int i;
5444
5445         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5446                 struct intel_encoder *encoder =
5447                         to_intel_encoder(conn_state->best_encoder);
5448
5449                 if (conn_state->crtc != crtc)
5450                         continue;
5451
5452                 if (encoder->pre_pll_enable)
5453                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5454         }
5455 }
5456
5457 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5458                                       struct intel_crtc_state *crtc_state,
5459                                       struct drm_atomic_state *old_state)
5460 {
5461         struct drm_connector_state *conn_state;
5462         struct drm_connector *conn;
5463         int i;
5464
5465         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5466                 struct intel_encoder *encoder =
5467                         to_intel_encoder(conn_state->best_encoder);
5468
5469                 if (conn_state->crtc != crtc)
5470                         continue;
5471
5472                 if (encoder->pre_enable)
5473                         encoder->pre_enable(encoder, crtc_state, conn_state);
5474         }
5475 }
5476
5477 static void intel_encoders_enable(struct drm_crtc *crtc,
5478                                   struct intel_crtc_state *crtc_state,
5479                                   struct drm_atomic_state *old_state)
5480 {
5481         struct drm_connector_state *conn_state;
5482         struct drm_connector *conn;
5483         int i;
5484
5485         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5486                 struct intel_encoder *encoder =
5487                         to_intel_encoder(conn_state->best_encoder);
5488
5489                 if (conn_state->crtc != crtc)
5490                         continue;
5491
5492                 if (encoder->enable)
5493                         encoder->enable(encoder, crtc_state, conn_state);
5494                 intel_opregion_notify_encoder(encoder, true);
5495         }
5496 }
5497
5498 static void intel_encoders_disable(struct drm_crtc *crtc,
5499                                    struct intel_crtc_state *old_crtc_state,
5500                                    struct drm_atomic_state *old_state)
5501 {
5502         struct drm_connector_state *old_conn_state;
5503         struct drm_connector *conn;
5504         int i;
5505
5506         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5507                 struct intel_encoder *encoder =
5508                         to_intel_encoder(old_conn_state->best_encoder);
5509
5510                 if (old_conn_state->crtc != crtc)
5511                         continue;
5512
5513                 intel_opregion_notify_encoder(encoder, false);
5514                 if (encoder->disable)
5515                         encoder->disable(encoder, old_crtc_state, old_conn_state);
5516         }
5517 }
5518
5519 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5520                                         struct intel_crtc_state *old_crtc_state,
5521                                         struct drm_atomic_state *old_state)
5522 {
5523         struct drm_connector_state *old_conn_state;
5524         struct drm_connector *conn;
5525         int i;
5526
5527         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5528                 struct intel_encoder *encoder =
5529                         to_intel_encoder(old_conn_state->best_encoder);
5530
5531                 if (old_conn_state->crtc != crtc)
5532                         continue;
5533
5534                 if (encoder->post_disable)
5535                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5536         }
5537 }
5538
5539 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5540                                             struct intel_crtc_state *old_crtc_state,
5541                                             struct drm_atomic_state *old_state)
5542 {
5543         struct drm_connector_state *old_conn_state;
5544         struct drm_connector *conn;
5545         int i;
5546
5547         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5548                 struct intel_encoder *encoder =
5549                         to_intel_encoder(old_conn_state->best_encoder);
5550
5551                 if (old_conn_state->crtc != crtc)
5552                         continue;
5553
5554                 if (encoder->post_pll_disable)
5555                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5556         }
5557 }
5558
5559 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5560                                  struct drm_atomic_state *old_state)
5561 {
5562         struct drm_crtc *crtc = pipe_config->base.crtc;
5563         struct drm_device *dev = crtc->dev;
5564         struct drm_i915_private *dev_priv = to_i915(dev);
5565         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5566         int pipe = intel_crtc->pipe;
5567         struct intel_atomic_state *old_intel_state =
5568                 to_intel_atomic_state(old_state);
5569
5570         if (WARN_ON(intel_crtc->active))
5571                 return;
5572
5573         /*
5574          * Sometimes spurious CPU pipe underruns happen during FDI
5575          * training, at least with VGA+HDMI cloning. Suppress them.
5576          *
5577          * On ILK we get an occasional spurious CPU pipe underruns
5578          * between eDP port A enable and vdd enable. Also PCH port
5579          * enable seems to result in the occasional CPU pipe underrun.
5580          *
5581          * Spurious PCH underruns also occur during PCH enabling.
5582          */
5583         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5584         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5585
5586         if (pipe_config->has_pch_encoder)
5587                 intel_prepare_shared_dpll(pipe_config);
5588
5589         if (intel_crtc_has_dp_encoder(pipe_config))
5590                 intel_dp_set_m_n(pipe_config, M1_N1);
5591
5592         intel_set_pipe_timings(pipe_config);
5593         intel_set_pipe_src_size(pipe_config);
5594
5595         if (pipe_config->has_pch_encoder) {
5596                 intel_cpu_transcoder_set_m_n(pipe_config,
5597                                              &pipe_config->fdi_m_n, NULL);
5598         }
5599
5600         ironlake_set_pipeconf(pipe_config);
5601
5602         intel_crtc->active = true;
5603
5604         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5605
5606         if (pipe_config->has_pch_encoder) {
5607                 /* Note: FDI PLL enabling _must_ be done before we enable the
5608                  * cpu pipes, hence this is separate from all the other fdi/pch
5609                  * enabling. */
5610                 ironlake_fdi_pll_enable(pipe_config);
5611         } else {
5612                 assert_fdi_tx_disabled(dev_priv, pipe);
5613                 assert_fdi_rx_disabled(dev_priv, pipe);
5614         }
5615
5616         ironlake_pfit_enable(pipe_config);
5617
5618         /*
5619          * On ILK+ LUT must be loaded before the pipe is running but with
5620          * clocks enabled
5621          */
5622         intel_color_load_luts(&pipe_config->base);
5623
5624         if (dev_priv->display.initial_watermarks != NULL)
5625                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5626         intel_enable_pipe(pipe_config);
5627
5628         if (pipe_config->has_pch_encoder)
5629                 ironlake_pch_enable(old_intel_state, pipe_config);
5630
5631         assert_vblank_disabled(crtc);
5632         drm_crtc_vblank_on(crtc);
5633
5634         intel_encoders_enable(crtc, pipe_config, old_state);
5635
5636         if (HAS_PCH_CPT(dev_priv))
5637                 cpt_verify_modeset(dev, intel_crtc->pipe);
5638
5639         /*
5640          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5641          * And a second vblank wait is needed at least on ILK with
5642          * some interlaced HDMI modes. Let's do the double wait always
5643          * in case there are more corner cases we don't know about.
5644          */
5645         if (pipe_config->has_pch_encoder) {
5646                 intel_wait_for_vblank(dev_priv, pipe);
5647                 intel_wait_for_vblank(dev_priv, pipe);
5648         }
5649         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5650         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5651 }
5652
5653 /* IPS only exists on ULT machines and is tied to pipe A. */
5654 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5655 {
5656         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5657 }
5658
5659 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5660                                             enum pipe pipe, bool apply)
5661 {
5662         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5663         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5664
5665         if (apply)
5666                 val |= mask;
5667         else
5668                 val &= ~mask;
5669
5670         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5671 }
5672
5673 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5674 {
5675         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5676         enum pipe pipe = crtc->pipe;
5677         uint32_t val;
5678
5679         val = MBUS_DBOX_A_CREDIT(2);
5680         val |= MBUS_DBOX_BW_CREDIT(1);
5681         val |= MBUS_DBOX_B_CREDIT(8);
5682
5683         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5684 }
5685
5686 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5687                                 struct drm_atomic_state *old_state)
5688 {
5689         struct drm_crtc *crtc = pipe_config->base.crtc;
5690         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5691         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5692         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5693         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
5694         struct intel_atomic_state *old_intel_state =
5695                 to_intel_atomic_state(old_state);
5696         bool psl_clkgate_wa;
5697         u32 pipe_chicken;
5698
5699         if (WARN_ON(intel_crtc->active))
5700                 return;
5701
5702         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5703
5704         if (pipe_config->shared_dpll)
5705                 intel_enable_shared_dpll(pipe_config);
5706
5707         if (INTEL_GEN(dev_priv) >= 11)
5708                 icl_map_plls_to_ports(crtc, pipe_config, old_state);
5709
5710         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5711
5712         if (intel_crtc_has_dp_encoder(pipe_config))
5713                 intel_dp_set_m_n(pipe_config, M1_N1);
5714
5715         if (!transcoder_is_dsi(cpu_transcoder))
5716                 intel_set_pipe_timings(pipe_config);
5717
5718         intel_set_pipe_src_size(pipe_config);
5719
5720         if (cpu_transcoder != TRANSCODER_EDP &&
5721             !transcoder_is_dsi(cpu_transcoder)) {
5722                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5723                            pipe_config->pixel_multiplier - 1);
5724         }
5725
5726         if (pipe_config->has_pch_encoder) {
5727                 intel_cpu_transcoder_set_m_n(pipe_config,
5728                                              &pipe_config->fdi_m_n, NULL);
5729         }
5730
5731         if (!transcoder_is_dsi(cpu_transcoder))
5732                 haswell_set_pipeconf(pipe_config);
5733
5734         haswell_set_pipemisc(pipe_config);
5735
5736         intel_color_set_csc(&pipe_config->base);
5737
5738         intel_crtc->active = true;
5739
5740         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5741         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5742                          pipe_config->pch_pfit.enabled;
5743         if (psl_clkgate_wa)
5744                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5745
5746         if (INTEL_GEN(dev_priv) >= 9)
5747                 skylake_pfit_enable(pipe_config);
5748         else
5749                 ironlake_pfit_enable(pipe_config);
5750
5751         /*
5752          * On ILK+ LUT must be loaded before the pipe is running but with
5753          * clocks enabled
5754          */
5755         intel_color_load_luts(&pipe_config->base);
5756
5757         /*
5758          * Display WA #1153: enable hardware to bypass the alpha math
5759          * and rounding for per-pixel values 00 and 0xff
5760          */
5761         if (INTEL_GEN(dev_priv) >= 11) {
5762                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5763                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5764                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5765                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5766         }
5767
5768         intel_ddi_set_pipe_settings(pipe_config);
5769         if (!transcoder_is_dsi(cpu_transcoder))
5770                 intel_ddi_enable_transcoder_func(pipe_config);
5771
5772         if (dev_priv->display.initial_watermarks != NULL)
5773                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5774
5775         if (INTEL_GEN(dev_priv) >= 11)
5776                 icl_pipe_mbus_enable(intel_crtc);
5777
5778         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5779         if (!transcoder_is_dsi(cpu_transcoder))
5780                 intel_enable_pipe(pipe_config);
5781
5782         if (pipe_config->has_pch_encoder)
5783                 lpt_pch_enable(old_intel_state, pipe_config);
5784
5785         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
5786                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5787
5788         assert_vblank_disabled(crtc);
5789         drm_crtc_vblank_on(crtc);
5790
5791         intel_encoders_enable(crtc, pipe_config, old_state);
5792
5793         if (psl_clkgate_wa) {
5794                 intel_wait_for_vblank(dev_priv, pipe);
5795                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5796         }
5797
5798         /* If we change the relative order between pipe/planes enabling, we need
5799          * to change the workaround. */
5800         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5801         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5802                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5803                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5804         }
5805 }
5806
5807 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
5808 {
5809         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5810         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5811         enum pipe pipe = crtc->pipe;
5812
5813         /* To avoid upsetting the power well on haswell only disable the pfit if
5814          * it's in use. The hw state code will make sure we get this right. */
5815         if (old_crtc_state->pch_pfit.enabled) {
5816                 I915_WRITE(PF_CTL(pipe), 0);
5817                 I915_WRITE(PF_WIN_POS(pipe), 0);
5818                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5819         }
5820 }
5821
5822 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5823                                   struct drm_atomic_state *old_state)
5824 {
5825         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5826         struct drm_device *dev = crtc->dev;
5827         struct drm_i915_private *dev_priv = to_i915(dev);
5828         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5829         int pipe = intel_crtc->pipe;
5830
5831         /*
5832          * Sometimes spurious CPU pipe underruns happen when the
5833          * pipe is already disabled, but FDI RX/TX is still enabled.
5834          * Happens at least with VGA+HDMI cloning. Suppress them.
5835          */
5836         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5837         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5838
5839         intel_encoders_disable(crtc, old_crtc_state, old_state);
5840
5841         drm_crtc_vblank_off(crtc);
5842         assert_vblank_disabled(crtc);
5843
5844         intel_disable_pipe(old_crtc_state);
5845
5846         ironlake_pfit_disable(old_crtc_state);
5847
5848         if (old_crtc_state->has_pch_encoder)
5849                 ironlake_fdi_disable(crtc);
5850
5851         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5852
5853         if (old_crtc_state->has_pch_encoder) {
5854                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5855
5856                 if (HAS_PCH_CPT(dev_priv)) {
5857                         i915_reg_t reg;
5858                         u32 temp;
5859
5860                         /* disable TRANS_DP_CTL */
5861                         reg = TRANS_DP_CTL(pipe);
5862                         temp = I915_READ(reg);
5863                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5864                                   TRANS_DP_PORT_SEL_MASK);
5865                         temp |= TRANS_DP_PORT_SEL_NONE;
5866                         I915_WRITE(reg, temp);
5867
5868                         /* disable DPLL_SEL */
5869                         temp = I915_READ(PCH_DPLL_SEL);
5870                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5871                         I915_WRITE(PCH_DPLL_SEL, temp);
5872                 }
5873
5874                 ironlake_fdi_pll_disable(intel_crtc);
5875         }
5876
5877         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5878         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5879 }
5880
5881 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5882                                  struct drm_atomic_state *old_state)
5883 {
5884         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5885         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5886         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5887         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5888
5889         intel_encoders_disable(crtc, old_crtc_state, old_state);
5890
5891         drm_crtc_vblank_off(crtc);
5892         assert_vblank_disabled(crtc);
5893
5894         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5895         if (!transcoder_is_dsi(cpu_transcoder))
5896                 intel_disable_pipe(old_crtc_state);
5897
5898         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5899                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5900
5901         if (!transcoder_is_dsi(cpu_transcoder))
5902                 intel_ddi_disable_transcoder_func(old_crtc_state);
5903
5904         if (INTEL_GEN(dev_priv) >= 9)
5905                 skylake_scaler_disable(intel_crtc);
5906         else
5907                 ironlake_pfit_disable(old_crtc_state);
5908
5909         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5910
5911         if (INTEL_GEN(dev_priv) >= 11)
5912                 icl_unmap_plls_to_ports(crtc, old_crtc_state, old_state);
5913
5914         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5915 }
5916
5917 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
5918 {
5919         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5920         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5921
5922         if (!crtc_state->gmch_pfit.control)
5923                 return;
5924
5925         /*
5926          * The panel fitter should only be adjusted whilst the pipe is disabled,
5927          * according to register description and PRM.
5928          */
5929         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5930         assert_pipe_disabled(dev_priv, crtc->pipe);
5931
5932         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
5933         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
5934
5935         /* Border color in case we don't scale up to the full screen. Black by
5936          * default, change to something else for debugging. */
5937         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5938 }
5939
5940 bool intel_port_is_combophy(struct drm_i915_private *dev_priv, enum port port)
5941 {
5942         if (port == PORT_NONE)
5943                 return false;
5944
5945         if (IS_ICELAKE(dev_priv))
5946                 return port <= PORT_B;
5947
5948         return false;
5949 }
5950
5951 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
5952 {
5953         if (IS_ICELAKE(dev_priv))
5954                 return port >= PORT_C && port <= PORT_F;
5955
5956         return false;
5957 }
5958
5959 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
5960 {
5961         if (!intel_port_is_tc(dev_priv, port))
5962                 return PORT_TC_NONE;
5963
5964         return port - PORT_C;
5965 }
5966
5967 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5968 {
5969         switch (port) {
5970         case PORT_A:
5971                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5972         case PORT_B:
5973                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5974         case PORT_C:
5975                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5976         case PORT_D:
5977                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5978         case PORT_E:
5979                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5980         case PORT_F:
5981                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5982         default:
5983                 MISSING_CASE(port);
5984                 return POWER_DOMAIN_PORT_OTHER;
5985         }
5986 }
5987
5988 enum intel_display_power_domain
5989 intel_aux_power_domain(struct intel_digital_port *dig_port)
5990 {
5991         switch (dig_port->aux_ch) {
5992         case AUX_CH_A:
5993                 return POWER_DOMAIN_AUX_A;
5994         case AUX_CH_B:
5995                 return POWER_DOMAIN_AUX_B;
5996         case AUX_CH_C:
5997                 return POWER_DOMAIN_AUX_C;
5998         case AUX_CH_D:
5999                 return POWER_DOMAIN_AUX_D;
6000         case AUX_CH_E:
6001                 return POWER_DOMAIN_AUX_E;
6002         case AUX_CH_F:
6003                 return POWER_DOMAIN_AUX_F;
6004         default:
6005                 MISSING_CASE(dig_port->aux_ch);
6006                 return POWER_DOMAIN_AUX_A;
6007         }
6008 }
6009
6010 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
6011                                   struct intel_crtc_state *crtc_state)
6012 {
6013         struct drm_device *dev = crtc->dev;
6014         struct drm_i915_private *dev_priv = to_i915(dev);
6015         struct drm_encoder *encoder;
6016         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6017         enum pipe pipe = intel_crtc->pipe;
6018         u64 mask;
6019         enum transcoder transcoder = crtc_state->cpu_transcoder;
6020
6021         if (!crtc_state->base.active)
6022                 return 0;
6023
6024         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6025         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6026         if (crtc_state->pch_pfit.enabled ||
6027             crtc_state->pch_pfit.force_thru)
6028                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6029
6030         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
6031                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6032
6033                 mask |= BIT_ULL(intel_encoder->power_domain);
6034         }
6035
6036         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6037                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6038
6039         if (crtc_state->shared_dpll)
6040                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
6041
6042         return mask;
6043 }
6044
6045 static u64
6046 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6047                                struct intel_crtc_state *crtc_state)
6048 {
6049         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6050         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6051         enum intel_display_power_domain domain;
6052         u64 domains, new_domains, old_domains;
6053
6054         old_domains = intel_crtc->enabled_power_domains;
6055         intel_crtc->enabled_power_domains = new_domains =
6056                 get_crtc_power_domains(crtc, crtc_state);
6057
6058         domains = new_domains & ~old_domains;
6059
6060         for_each_power_domain(domain, domains)
6061                 intel_display_power_get(dev_priv, domain);
6062
6063         return old_domains & ~new_domains;
6064 }
6065
6066 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6067                                       u64 domains)
6068 {
6069         enum intel_display_power_domain domain;
6070
6071         for_each_power_domain(domain, domains)
6072                 intel_display_power_put(dev_priv, domain);
6073 }
6074
6075 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6076                                    struct drm_atomic_state *old_state)
6077 {
6078         struct intel_atomic_state *old_intel_state =
6079                 to_intel_atomic_state(old_state);
6080         struct drm_crtc *crtc = pipe_config->base.crtc;
6081         struct drm_device *dev = crtc->dev;
6082         struct drm_i915_private *dev_priv = to_i915(dev);
6083         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6084         int pipe = intel_crtc->pipe;
6085
6086         if (WARN_ON(intel_crtc->active))
6087                 return;
6088
6089         if (intel_crtc_has_dp_encoder(pipe_config))
6090                 intel_dp_set_m_n(pipe_config, M1_N1);
6091
6092         intel_set_pipe_timings(pipe_config);
6093         intel_set_pipe_src_size(pipe_config);
6094
6095         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6096                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6097                 I915_WRITE(CHV_CANVAS(pipe), 0);
6098         }
6099
6100         i9xx_set_pipeconf(pipe_config);
6101
6102         intel_color_set_csc(&pipe_config->base);
6103
6104         intel_crtc->active = true;
6105
6106         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6107
6108         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6109
6110         if (IS_CHERRYVIEW(dev_priv)) {
6111                 chv_prepare_pll(intel_crtc, pipe_config);
6112                 chv_enable_pll(intel_crtc, pipe_config);
6113         } else {
6114                 vlv_prepare_pll(intel_crtc, pipe_config);
6115                 vlv_enable_pll(intel_crtc, pipe_config);
6116         }
6117
6118         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6119
6120         i9xx_pfit_enable(pipe_config);
6121
6122         intel_color_load_luts(&pipe_config->base);
6123
6124         dev_priv->display.initial_watermarks(old_intel_state,
6125                                              pipe_config);
6126         intel_enable_pipe(pipe_config);
6127
6128         assert_vblank_disabled(crtc);
6129         drm_crtc_vblank_on(crtc);
6130
6131         intel_encoders_enable(crtc, pipe_config, old_state);
6132 }
6133
6134 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6135 {
6136         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6137         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6138
6139         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6140         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6141 }
6142
6143 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6144                              struct drm_atomic_state *old_state)
6145 {
6146         struct intel_atomic_state *old_intel_state =
6147                 to_intel_atomic_state(old_state);
6148         struct drm_crtc *crtc = pipe_config->base.crtc;
6149         struct drm_device *dev = crtc->dev;
6150         struct drm_i915_private *dev_priv = to_i915(dev);
6151         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6152         enum pipe pipe = intel_crtc->pipe;
6153
6154         if (WARN_ON(intel_crtc->active))
6155                 return;
6156
6157         i9xx_set_pll_dividers(pipe_config);
6158
6159         if (intel_crtc_has_dp_encoder(pipe_config))
6160                 intel_dp_set_m_n(pipe_config, M1_N1);
6161
6162         intel_set_pipe_timings(pipe_config);
6163         intel_set_pipe_src_size(pipe_config);
6164
6165         i9xx_set_pipeconf(pipe_config);
6166
6167         intel_crtc->active = true;
6168
6169         if (!IS_GEN2(dev_priv))
6170                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6171
6172         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6173
6174         i9xx_enable_pll(intel_crtc, pipe_config);
6175
6176         i9xx_pfit_enable(pipe_config);
6177
6178         intel_color_load_luts(&pipe_config->base);
6179
6180         if (dev_priv->display.initial_watermarks != NULL)
6181                 dev_priv->display.initial_watermarks(old_intel_state,
6182                                                      pipe_config);
6183         else
6184                 intel_update_watermarks(intel_crtc);
6185         intel_enable_pipe(pipe_config);
6186
6187         assert_vblank_disabled(crtc);
6188         drm_crtc_vblank_on(crtc);
6189
6190         intel_encoders_enable(crtc, pipe_config, old_state);
6191 }
6192
6193 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6194 {
6195         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6196         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6197
6198         if (!old_crtc_state->gmch_pfit.control)
6199                 return;
6200
6201         assert_pipe_disabled(dev_priv, crtc->pipe);
6202
6203         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6204                       I915_READ(PFIT_CONTROL));
6205         I915_WRITE(PFIT_CONTROL, 0);
6206 }
6207
6208 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6209                               struct drm_atomic_state *old_state)
6210 {
6211         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6212         struct drm_device *dev = crtc->dev;
6213         struct drm_i915_private *dev_priv = to_i915(dev);
6214         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6215         int pipe = intel_crtc->pipe;
6216
6217         /*
6218          * On gen2 planes are double buffered but the pipe isn't, so we must
6219          * wait for planes to fully turn off before disabling the pipe.
6220          */
6221         if (IS_GEN2(dev_priv))
6222                 intel_wait_for_vblank(dev_priv, pipe);
6223
6224         intel_encoders_disable(crtc, old_crtc_state, old_state);
6225
6226         drm_crtc_vblank_off(crtc);
6227         assert_vblank_disabled(crtc);
6228
6229         intel_disable_pipe(old_crtc_state);
6230
6231         i9xx_pfit_disable(old_crtc_state);
6232
6233         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6234
6235         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6236                 if (IS_CHERRYVIEW(dev_priv))
6237                         chv_disable_pll(dev_priv, pipe);
6238                 else if (IS_VALLEYVIEW(dev_priv))
6239                         vlv_disable_pll(dev_priv, pipe);
6240                 else
6241                         i9xx_disable_pll(old_crtc_state);
6242         }
6243
6244         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6245
6246         if (!IS_GEN2(dev_priv))
6247                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6248
6249         if (!dev_priv->display.initial_watermarks)
6250                 intel_update_watermarks(intel_crtc);
6251
6252         /* clock the pipe down to 640x480@60 to potentially save power */
6253         if (IS_I830(dev_priv))
6254                 i830_enable_pipe(dev_priv, pipe);
6255 }
6256
6257 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6258                                         struct drm_modeset_acquire_ctx *ctx)
6259 {
6260         struct intel_encoder *encoder;
6261         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6262         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6263         enum intel_display_power_domain domain;
6264         struct intel_plane *plane;
6265         u64 domains;
6266         struct drm_atomic_state *state;
6267         struct intel_crtc_state *crtc_state;
6268         int ret;
6269
6270         if (!intel_crtc->active)
6271                 return;
6272
6273         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6274                 const struct intel_plane_state *plane_state =
6275                         to_intel_plane_state(plane->base.state);
6276
6277                 if (plane_state->base.visible)
6278                         intel_plane_disable_noatomic(intel_crtc, plane);
6279         }
6280
6281         state = drm_atomic_state_alloc(crtc->dev);
6282         if (!state) {
6283                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6284                               crtc->base.id, crtc->name);
6285                 return;
6286         }
6287
6288         state->acquire_ctx = ctx;
6289
6290         /* Everything's already locked, -EDEADLK can't happen. */
6291         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6292         ret = drm_atomic_add_affected_connectors(state, crtc);
6293
6294         WARN_ON(IS_ERR(crtc_state) || ret);
6295
6296         dev_priv->display.crtc_disable(crtc_state, state);
6297
6298         drm_atomic_state_put(state);
6299
6300         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6301                       crtc->base.id, crtc->name);
6302
6303         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6304         crtc->state->active = false;
6305         intel_crtc->active = false;
6306         crtc->enabled = false;
6307         crtc->state->connector_mask = 0;
6308         crtc->state->encoder_mask = 0;
6309
6310         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6311                 encoder->base.crtc = NULL;
6312
6313         intel_fbc_disable(intel_crtc);
6314         intel_update_watermarks(intel_crtc);
6315         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6316
6317         domains = intel_crtc->enabled_power_domains;
6318         for_each_power_domain(domain, domains)
6319                 intel_display_power_put(dev_priv, domain);
6320         intel_crtc->enabled_power_domains = 0;
6321
6322         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6323         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6324         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6325 }
6326
6327 /*
6328  * turn all crtc's off, but do not adjust state
6329  * This has to be paired with a call to intel_modeset_setup_hw_state.
6330  */
6331 int intel_display_suspend(struct drm_device *dev)
6332 {
6333         struct drm_i915_private *dev_priv = to_i915(dev);
6334         struct drm_atomic_state *state;
6335         int ret;
6336
6337         state = drm_atomic_helper_suspend(dev);
6338         ret = PTR_ERR_OR_ZERO(state);
6339         if (ret)
6340                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6341         else
6342                 dev_priv->modeset_restore_state = state;
6343         return ret;
6344 }
6345
6346 void intel_encoder_destroy(struct drm_encoder *encoder)
6347 {
6348         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6349
6350         drm_encoder_cleanup(encoder);
6351         kfree(intel_encoder);
6352 }
6353
6354 /* Cross check the actual hw state with our own modeset state tracking (and it's
6355  * internal consistency). */
6356 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6357                                          struct drm_connector_state *conn_state)
6358 {
6359         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6360
6361         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6362                       connector->base.base.id,
6363                       connector->base.name);
6364
6365         if (connector->get_hw_state(connector)) {
6366                 struct intel_encoder *encoder = connector->encoder;
6367
6368                 I915_STATE_WARN(!crtc_state,
6369                          "connector enabled without attached crtc\n");
6370
6371                 if (!crtc_state)
6372                         return;
6373
6374                 I915_STATE_WARN(!crtc_state->active,
6375                       "connector is active, but attached crtc isn't\n");
6376
6377                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6378                         return;
6379
6380                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6381                         "atomic encoder doesn't match attached encoder\n");
6382
6383                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6384                         "attached encoder crtc differs from connector crtc\n");
6385         } else {
6386                 I915_STATE_WARN(crtc_state && crtc_state->active,
6387                         "attached crtc is active, but connector isn't\n");
6388                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6389                         "best encoder set without crtc!\n");
6390         }
6391 }
6392
6393 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6394 {
6395         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6396                 return crtc_state->fdi_lanes;
6397
6398         return 0;
6399 }
6400
6401 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6402                                      struct intel_crtc_state *pipe_config)
6403 {
6404         struct drm_i915_private *dev_priv = to_i915(dev);
6405         struct drm_atomic_state *state = pipe_config->base.state;
6406         struct intel_crtc *other_crtc;
6407         struct intel_crtc_state *other_crtc_state;
6408
6409         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6410                       pipe_name(pipe), pipe_config->fdi_lanes);
6411         if (pipe_config->fdi_lanes > 4) {
6412                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6413                               pipe_name(pipe), pipe_config->fdi_lanes);
6414                 return -EINVAL;
6415         }
6416
6417         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6418                 if (pipe_config->fdi_lanes > 2) {
6419                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6420                                       pipe_config->fdi_lanes);
6421                         return -EINVAL;
6422                 } else {
6423                         return 0;
6424                 }
6425         }
6426
6427         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6428                 return 0;
6429
6430         /* Ivybridge 3 pipe is really complicated */
6431         switch (pipe) {
6432         case PIPE_A:
6433                 return 0;
6434         case PIPE_B:
6435                 if (pipe_config->fdi_lanes <= 2)
6436                         return 0;
6437
6438                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6439                 other_crtc_state =
6440                         intel_atomic_get_crtc_state(state, other_crtc);
6441                 if (IS_ERR(other_crtc_state))
6442                         return PTR_ERR(other_crtc_state);
6443
6444                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6445                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6446                                       pipe_name(pipe), pipe_config->fdi_lanes);
6447                         return -EINVAL;
6448                 }
6449                 return 0;
6450         case PIPE_C:
6451                 if (pipe_config->fdi_lanes > 2) {
6452                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6453                                       pipe_name(pipe), pipe_config->fdi_lanes);
6454                         return -EINVAL;
6455                 }
6456
6457                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6458                 other_crtc_state =
6459                         intel_atomic_get_crtc_state(state, other_crtc);
6460                 if (IS_ERR(other_crtc_state))
6461                         return PTR_ERR(other_crtc_state);
6462
6463                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6464                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6465                         return -EINVAL;
6466                 }
6467                 return 0;
6468         default:
6469                 BUG();
6470         }
6471 }
6472
6473 #define RETRY 1
6474 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6475                                        struct intel_crtc_state *pipe_config)
6476 {
6477         struct drm_device *dev = intel_crtc->base.dev;
6478         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6479         int lane, link_bw, fdi_dotclock, ret;
6480         bool needs_recompute = false;
6481
6482 retry:
6483         /* FDI is a binary signal running at ~2.7GHz, encoding
6484          * each output octet as 10 bits. The actual frequency
6485          * is stored as a divider into a 100MHz clock, and the
6486          * mode pixel clock is stored in units of 1KHz.
6487          * Hence the bw of each lane in terms of the mode signal
6488          * is:
6489          */
6490         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6491
6492         fdi_dotclock = adjusted_mode->crtc_clock;
6493
6494         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6495                                            pipe_config->pipe_bpp);
6496
6497         pipe_config->fdi_lanes = lane;
6498
6499         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6500                                link_bw, &pipe_config->fdi_m_n, false);
6501
6502         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6503         if (ret == -EDEADLK)
6504                 return ret;
6505
6506         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6507                 pipe_config->pipe_bpp -= 2*3;
6508                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6509                               pipe_config->pipe_bpp);
6510                 needs_recompute = true;
6511                 pipe_config->bw_constrained = true;
6512
6513                 goto retry;
6514         }
6515
6516         if (needs_recompute)
6517                 return RETRY;
6518
6519         return ret;
6520 }
6521
6522 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6523 {
6524         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6525         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6526
6527         /* IPS only exists on ULT machines and is tied to pipe A. */
6528         if (!hsw_crtc_supports_ips(crtc))
6529                 return false;
6530
6531         if (!i915_modparams.enable_ips)
6532                 return false;
6533
6534         if (crtc_state->pipe_bpp > 24)
6535                 return false;
6536
6537         /*
6538          * We compare against max which means we must take
6539          * the increased cdclk requirement into account when
6540          * calculating the new cdclk.
6541          *
6542          * Should measure whether using a lower cdclk w/o IPS
6543          */
6544         if (IS_BROADWELL(dev_priv) &&
6545             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6546                 return false;
6547
6548         return true;
6549 }
6550
6551 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6552 {
6553         struct drm_i915_private *dev_priv =
6554                 to_i915(crtc_state->base.crtc->dev);
6555         struct intel_atomic_state *intel_state =
6556                 to_intel_atomic_state(crtc_state->base.state);
6557
6558         if (!hsw_crtc_state_ips_capable(crtc_state))
6559                 return false;
6560
6561         if (crtc_state->ips_force_disable)
6562                 return false;
6563
6564         /* IPS should be fine as long as at least one plane is enabled. */
6565         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6566                 return false;
6567
6568         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6569         if (IS_BROADWELL(dev_priv) &&
6570             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6571                 return false;
6572
6573         return true;
6574 }
6575
6576 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6577 {
6578         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6579
6580         /* GDG double wide on either pipe, otherwise pipe A only */
6581         return INTEL_GEN(dev_priv) < 4 &&
6582                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6583 }
6584
6585 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6586 {
6587         uint32_t pixel_rate;
6588
6589         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6590
6591         /*
6592          * We only use IF-ID interlacing. If we ever use
6593          * PF-ID we'll need to adjust the pixel_rate here.
6594          */
6595
6596         if (pipe_config->pch_pfit.enabled) {
6597                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6598                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6599
6600                 pipe_w = pipe_config->pipe_src_w;
6601                 pipe_h = pipe_config->pipe_src_h;
6602
6603                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6604                 pfit_h = pfit_size & 0xFFFF;
6605                 if (pipe_w < pfit_w)
6606                         pipe_w = pfit_w;
6607                 if (pipe_h < pfit_h)
6608                         pipe_h = pfit_h;
6609
6610                 if (WARN_ON(!pfit_w || !pfit_h))
6611                         return pixel_rate;
6612
6613                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6614                                      pfit_w * pfit_h);
6615         }
6616
6617         return pixel_rate;
6618 }
6619
6620 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6621 {
6622         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6623
6624         if (HAS_GMCH_DISPLAY(dev_priv))
6625                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6626                 crtc_state->pixel_rate =
6627                         crtc_state->base.adjusted_mode.crtc_clock;
6628         else
6629                 crtc_state->pixel_rate =
6630                         ilk_pipe_pixel_rate(crtc_state);
6631 }
6632
6633 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6634                                      struct intel_crtc_state *pipe_config)
6635 {
6636         struct drm_device *dev = crtc->base.dev;
6637         struct drm_i915_private *dev_priv = to_i915(dev);
6638         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6639         int clock_limit = dev_priv->max_dotclk_freq;
6640
6641         if (INTEL_GEN(dev_priv) < 4) {
6642                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6643
6644                 /*
6645                  * Enable double wide mode when the dot clock
6646                  * is > 90% of the (display) core speed.
6647                  */
6648                 if (intel_crtc_supports_double_wide(crtc) &&
6649                     adjusted_mode->crtc_clock > clock_limit) {
6650                         clock_limit = dev_priv->max_dotclk_freq;
6651                         pipe_config->double_wide = true;
6652                 }
6653         }
6654
6655         if (adjusted_mode->crtc_clock > clock_limit) {
6656                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6657                               adjusted_mode->crtc_clock, clock_limit,
6658                               yesno(pipe_config->double_wide));
6659                 return -EINVAL;
6660         }
6661
6662         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
6663              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
6664              pipe_config->base.ctm) {
6665                 /*
6666                  * There is only one pipe CSC unit per pipe, and we need that
6667                  * for output conversion from RGB->YCBCR. So if CTM is already
6668                  * applied we can't support YCBCR420 output.
6669                  */
6670                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6671                 return -EINVAL;
6672         }
6673
6674         /*
6675          * Pipe horizontal size must be even in:
6676          * - DVO ganged mode
6677          * - LVDS dual channel mode
6678          * - Double wide pipe
6679          */
6680         if (pipe_config->pipe_src_w & 1) {
6681                 if (pipe_config->double_wide) {
6682                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6683                         return -EINVAL;
6684                 }
6685
6686                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6687                     intel_is_dual_link_lvds(dev)) {
6688                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6689                         return -EINVAL;
6690                 }
6691         }
6692
6693         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6694          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6695          */
6696         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6697                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6698                 return -EINVAL;
6699
6700         intel_crtc_compute_pixel_rate(pipe_config);
6701
6702         if (pipe_config->has_pch_encoder)
6703                 return ironlake_fdi_compute_config(crtc, pipe_config);
6704
6705         return 0;
6706 }
6707
6708 static void
6709 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6710 {
6711         while (*num > DATA_LINK_M_N_MASK ||
6712                *den > DATA_LINK_M_N_MASK) {
6713                 *num >>= 1;
6714                 *den >>= 1;
6715         }
6716 }
6717
6718 static void compute_m_n(unsigned int m, unsigned int n,
6719                         uint32_t *ret_m, uint32_t *ret_n,
6720                         bool constant_n)
6721 {
6722         /*
6723          * Several DP dongles in particular seem to be fussy about
6724          * too large link M/N values. Give N value as 0x8000 that
6725          * should be acceptable by specific devices. 0x8000 is the
6726          * specified fixed N value for asynchronous clock mode,
6727          * which the devices expect also in synchronous clock mode.
6728          */
6729         if (constant_n)
6730                 *ret_n = 0x8000;
6731         else
6732                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6733
6734         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6735         intel_reduce_m_n_ratio(ret_m, ret_n);
6736 }
6737
6738 void
6739 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6740                        int pixel_clock, int link_clock,
6741                        struct intel_link_m_n *m_n,
6742                        bool constant_n)
6743 {
6744         m_n->tu = 64;
6745
6746         compute_m_n(bits_per_pixel * pixel_clock,
6747                     link_clock * nlanes * 8,
6748                     &m_n->gmch_m, &m_n->gmch_n,
6749                     constant_n);
6750
6751         compute_m_n(pixel_clock, link_clock,
6752                     &m_n->link_m, &m_n->link_n,
6753                     constant_n);
6754 }
6755
6756 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6757 {
6758         if (i915_modparams.panel_use_ssc >= 0)
6759                 return i915_modparams.panel_use_ssc != 0;
6760         return dev_priv->vbt.lvds_use_ssc
6761                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6762 }
6763
6764 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6765 {
6766         return (1 << dpll->n) << 16 | dpll->m2;
6767 }
6768
6769 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6770 {
6771         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6772 }
6773
6774 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6775                                      struct intel_crtc_state *crtc_state,
6776                                      struct dpll *reduced_clock)
6777 {
6778         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6779         u32 fp, fp2 = 0;
6780
6781         if (IS_PINEVIEW(dev_priv)) {
6782                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6783                 if (reduced_clock)
6784                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6785         } else {
6786                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6787                 if (reduced_clock)
6788                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6789         }
6790
6791         crtc_state->dpll_hw_state.fp0 = fp;
6792
6793         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6794             reduced_clock) {
6795                 crtc_state->dpll_hw_state.fp1 = fp2;
6796         } else {
6797                 crtc_state->dpll_hw_state.fp1 = fp;
6798         }
6799 }
6800
6801 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6802                 pipe)
6803 {
6804         u32 reg_val;
6805
6806         /*
6807          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6808          * and set it to a reasonable value instead.
6809          */
6810         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6811         reg_val &= 0xffffff00;
6812         reg_val |= 0x00000030;
6813         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6814
6815         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6816         reg_val &= 0x00ffffff;
6817         reg_val |= 0x8c000000;
6818         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6819
6820         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6821         reg_val &= 0xffffff00;
6822         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6823
6824         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6825         reg_val &= 0x00ffffff;
6826         reg_val |= 0xb0000000;
6827         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6828 }
6829
6830 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
6831                                          const struct intel_link_m_n *m_n)
6832 {
6833         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6834         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6835         enum pipe pipe = crtc->pipe;
6836
6837         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6838         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6839         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6840         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6841 }
6842
6843 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
6844                                  enum transcoder transcoder)
6845 {
6846         if (IS_HASWELL(dev_priv))
6847                 return transcoder == TRANSCODER_EDP;
6848
6849         /*
6850          * Strictly speaking some registers are available before
6851          * gen7, but we only support DRRS on gen7+
6852          */
6853         return IS_GEN7(dev_priv) || IS_CHERRYVIEW(dev_priv);
6854 }
6855
6856 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
6857                                          const struct intel_link_m_n *m_n,
6858                                          const struct intel_link_m_n *m2_n2)
6859 {
6860         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6861         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6862         enum pipe pipe = crtc->pipe;
6863         enum transcoder transcoder = crtc_state->cpu_transcoder;
6864
6865         if (INTEL_GEN(dev_priv) >= 5) {
6866                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6867                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6868                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6869                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6870                 /*
6871                  *  M2_N2 registers are set only if DRRS is supported
6872                  * (to make sure the registers are not unnecessarily accessed).
6873                  */
6874                 if (m2_n2 && crtc_state->has_drrs &&
6875                     transcoder_has_m2_n2(dev_priv, transcoder)) {
6876                         I915_WRITE(PIPE_DATA_M2(transcoder),
6877                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6878                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6879                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6880                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6881                 }
6882         } else {
6883                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6884                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6885                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6886                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6887         }
6888 }
6889
6890 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
6891 {
6892         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6893
6894         if (m_n == M1_N1) {
6895                 dp_m_n = &crtc_state->dp_m_n;
6896                 dp_m2_n2 = &crtc_state->dp_m2_n2;
6897         } else if (m_n == M2_N2) {
6898
6899                 /*
6900                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6901                  * needs to be programmed into M1_N1.
6902                  */
6903                 dp_m_n = &crtc_state->dp_m2_n2;
6904         } else {
6905                 DRM_ERROR("Unsupported divider value\n");
6906                 return;
6907         }
6908
6909         if (crtc_state->has_pch_encoder)
6910                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
6911         else
6912                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
6913 }
6914
6915 static void vlv_compute_dpll(struct intel_crtc *crtc,
6916                              struct intel_crtc_state *pipe_config)
6917 {
6918         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6919                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6920         if (crtc->pipe != PIPE_A)
6921                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6922
6923         /* DPLL not used with DSI, but still need the rest set up */
6924         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6925                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6926                         DPLL_EXT_BUFFER_ENABLE_VLV;
6927
6928         pipe_config->dpll_hw_state.dpll_md =
6929                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6930 }
6931
6932 static void chv_compute_dpll(struct intel_crtc *crtc,
6933                              struct intel_crtc_state *pipe_config)
6934 {
6935         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6936                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6937         if (crtc->pipe != PIPE_A)
6938                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6939
6940         /* DPLL not used with DSI, but still need the rest set up */
6941         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6942                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6943
6944         pipe_config->dpll_hw_state.dpll_md =
6945                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6946 }
6947
6948 static void vlv_prepare_pll(struct intel_crtc *crtc,
6949                             const struct intel_crtc_state *pipe_config)
6950 {
6951         struct drm_device *dev = crtc->base.dev;
6952         struct drm_i915_private *dev_priv = to_i915(dev);
6953         enum pipe pipe = crtc->pipe;
6954         u32 mdiv;
6955         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6956         u32 coreclk, reg_val;
6957
6958         /* Enable Refclk */
6959         I915_WRITE(DPLL(pipe),
6960                    pipe_config->dpll_hw_state.dpll &
6961                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6962
6963         /* No need to actually set up the DPLL with DSI */
6964         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6965                 return;
6966
6967         mutex_lock(&dev_priv->sb_lock);
6968
6969         bestn = pipe_config->dpll.n;
6970         bestm1 = pipe_config->dpll.m1;
6971         bestm2 = pipe_config->dpll.m2;
6972         bestp1 = pipe_config->dpll.p1;
6973         bestp2 = pipe_config->dpll.p2;
6974
6975         /* See eDP HDMI DPIO driver vbios notes doc */
6976
6977         /* PLL B needs special handling */
6978         if (pipe == PIPE_B)
6979                 vlv_pllb_recal_opamp(dev_priv, pipe);
6980
6981         /* Set up Tx target for periodic Rcomp update */
6982         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6983
6984         /* Disable target IRef on PLL */
6985         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6986         reg_val &= 0x00ffffff;
6987         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6988
6989         /* Disable fast lock */
6990         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6991
6992         /* Set idtafcrecal before PLL is enabled */
6993         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6994         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6995         mdiv |= ((bestn << DPIO_N_SHIFT));
6996         mdiv |= (1 << DPIO_K_SHIFT);
6997
6998         /*
6999          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7000          * but we don't support that).
7001          * Note: don't use the DAC post divider as it seems unstable.
7002          */
7003         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7004         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7005
7006         mdiv |= DPIO_ENABLE_CALIBRATION;
7007         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7008
7009         /* Set HBR and RBR LPF coefficients */
7010         if (pipe_config->port_clock == 162000 ||
7011             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
7012             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
7013                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7014                                  0x009f0003);
7015         else
7016                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7017                                  0x00d0000f);
7018
7019         if (intel_crtc_has_dp_encoder(pipe_config)) {
7020                 /* Use SSC source */
7021                 if (pipe == PIPE_A)
7022                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7023                                          0x0df40000);
7024                 else
7025                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7026                                          0x0df70000);
7027         } else { /* HDMI or VGA */
7028                 /* Use bend source */
7029                 if (pipe == PIPE_A)
7030                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7031                                          0x0df70000);
7032                 else
7033                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7034                                          0x0df40000);
7035         }
7036
7037         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7038         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7039         if (intel_crtc_has_dp_encoder(pipe_config))
7040                 coreclk |= 0x01000000;
7041         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7042
7043         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7044         mutex_unlock(&dev_priv->sb_lock);
7045 }
7046
7047 static void chv_prepare_pll(struct intel_crtc *crtc,
7048                             const struct intel_crtc_state *pipe_config)
7049 {
7050         struct drm_device *dev = crtc->base.dev;
7051         struct drm_i915_private *dev_priv = to_i915(dev);
7052         enum pipe pipe = crtc->pipe;
7053         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7054         u32 loopfilter, tribuf_calcntr;
7055         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7056         u32 dpio_val;
7057         int vco;
7058
7059         /* Enable Refclk and SSC */
7060         I915_WRITE(DPLL(pipe),
7061                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7062
7063         /* No need to actually set up the DPLL with DSI */
7064         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7065                 return;
7066
7067         bestn = pipe_config->dpll.n;
7068         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7069         bestm1 = pipe_config->dpll.m1;
7070         bestm2 = pipe_config->dpll.m2 >> 22;
7071         bestp1 = pipe_config->dpll.p1;
7072         bestp2 = pipe_config->dpll.p2;
7073         vco = pipe_config->dpll.vco;
7074         dpio_val = 0;
7075         loopfilter = 0;
7076
7077         mutex_lock(&dev_priv->sb_lock);
7078
7079         /* p1 and p2 divider */
7080         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7081                         5 << DPIO_CHV_S1_DIV_SHIFT |
7082                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7083                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7084                         1 << DPIO_CHV_K_DIV_SHIFT);
7085
7086         /* Feedback post-divider - m2 */
7087         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7088
7089         /* Feedback refclk divider - n and m1 */
7090         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7091                         DPIO_CHV_M1_DIV_BY_2 |
7092                         1 << DPIO_CHV_N_DIV_SHIFT);
7093
7094         /* M2 fraction division */
7095         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7096
7097         /* M2 fraction division enable */
7098         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7099         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7100         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7101         if (bestm2_frac)
7102                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7103         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7104
7105         /* Program digital lock detect threshold */
7106         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7107         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7108                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7109         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7110         if (!bestm2_frac)
7111                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7112         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7113
7114         /* Loop filter */
7115         if (vco == 5400000) {
7116                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7117                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7118                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7119                 tribuf_calcntr = 0x9;
7120         } else if (vco <= 6200000) {
7121                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7122                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7123                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7124                 tribuf_calcntr = 0x9;
7125         } else if (vco <= 6480000) {
7126                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7127                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7128                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7129                 tribuf_calcntr = 0x8;
7130         } else {
7131                 /* Not supported. Apply the same limits as in the max case */
7132                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7133                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7134                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7135                 tribuf_calcntr = 0;
7136         }
7137         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7138
7139         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7140         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7141         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7142         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7143
7144         /* AFC Recal */
7145         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7146                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7147                         DPIO_AFC_RECAL);
7148
7149         mutex_unlock(&dev_priv->sb_lock);
7150 }
7151
7152 /**
7153  * vlv_force_pll_on - forcibly enable just the PLL
7154  * @dev_priv: i915 private structure
7155  * @pipe: pipe PLL to enable
7156  * @dpll: PLL configuration
7157  *
7158  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7159  * in cases where we need the PLL enabled even when @pipe is not going to
7160  * be enabled.
7161  */
7162 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7163                      const struct dpll *dpll)
7164 {
7165         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7166         struct intel_crtc_state *pipe_config;
7167
7168         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7169         if (!pipe_config)
7170                 return -ENOMEM;
7171
7172         pipe_config->base.crtc = &crtc->base;
7173         pipe_config->pixel_multiplier = 1;
7174         pipe_config->dpll = *dpll;
7175
7176         if (IS_CHERRYVIEW(dev_priv)) {
7177                 chv_compute_dpll(crtc, pipe_config);
7178                 chv_prepare_pll(crtc, pipe_config);
7179                 chv_enable_pll(crtc, pipe_config);
7180         } else {
7181                 vlv_compute_dpll(crtc, pipe_config);
7182                 vlv_prepare_pll(crtc, pipe_config);
7183                 vlv_enable_pll(crtc, pipe_config);
7184         }
7185
7186         kfree(pipe_config);
7187
7188         return 0;
7189 }
7190
7191 /**
7192  * vlv_force_pll_off - forcibly disable just the PLL
7193  * @dev_priv: i915 private structure
7194  * @pipe: pipe PLL to disable
7195  *
7196  * Disable the PLL for @pipe. To be used in cases where we need
7197  * the PLL enabled even when @pipe is not going to be enabled.
7198  */
7199 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7200 {
7201         if (IS_CHERRYVIEW(dev_priv))
7202                 chv_disable_pll(dev_priv, pipe);
7203         else
7204                 vlv_disable_pll(dev_priv, pipe);
7205 }
7206
7207 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7208                               struct intel_crtc_state *crtc_state,
7209                               struct dpll *reduced_clock)
7210 {
7211         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7212         u32 dpll;
7213         struct dpll *clock = &crtc_state->dpll;
7214
7215         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7216
7217         dpll = DPLL_VGA_MODE_DIS;
7218
7219         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7220                 dpll |= DPLLB_MODE_LVDS;
7221         else
7222                 dpll |= DPLLB_MODE_DAC_SERIAL;
7223
7224         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7225             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7226                 dpll |= (crtc_state->pixel_multiplier - 1)
7227                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7228         }
7229
7230         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7231             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7232                 dpll |= DPLL_SDVO_HIGH_SPEED;
7233
7234         if (intel_crtc_has_dp_encoder(crtc_state))
7235                 dpll |= DPLL_SDVO_HIGH_SPEED;
7236
7237         /* compute bitmask from p1 value */
7238         if (IS_PINEVIEW(dev_priv))
7239                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7240         else {
7241                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7242                 if (IS_G4X(dev_priv) && reduced_clock)
7243                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7244         }
7245         switch (clock->p2) {
7246         case 5:
7247                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7248                 break;
7249         case 7:
7250                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7251                 break;
7252         case 10:
7253                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7254                 break;
7255         case 14:
7256                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7257                 break;
7258         }
7259         if (INTEL_GEN(dev_priv) >= 4)
7260                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7261
7262         if (crtc_state->sdvo_tv_clock)
7263                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7264         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7265                  intel_panel_use_ssc(dev_priv))
7266                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7267         else
7268                 dpll |= PLL_REF_INPUT_DREFCLK;
7269
7270         dpll |= DPLL_VCO_ENABLE;
7271         crtc_state->dpll_hw_state.dpll = dpll;
7272
7273         if (INTEL_GEN(dev_priv) >= 4) {
7274                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7275                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7276                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7277         }
7278 }
7279
7280 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7281                               struct intel_crtc_state *crtc_state,
7282                               struct dpll *reduced_clock)
7283 {
7284         struct drm_device *dev = crtc->base.dev;
7285         struct drm_i915_private *dev_priv = to_i915(dev);
7286         u32 dpll;
7287         struct dpll *clock = &crtc_state->dpll;
7288
7289         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7290
7291         dpll = DPLL_VGA_MODE_DIS;
7292
7293         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7294                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7295         } else {
7296                 if (clock->p1 == 2)
7297                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7298                 else
7299                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7300                 if (clock->p2 == 4)
7301                         dpll |= PLL_P2_DIVIDE_BY_4;
7302         }
7303
7304         if (!IS_I830(dev_priv) &&
7305             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7306                 dpll |= DPLL_DVO_2X_MODE;
7307
7308         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7309             intel_panel_use_ssc(dev_priv))
7310                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7311         else
7312                 dpll |= PLL_REF_INPUT_DREFCLK;
7313
7314         dpll |= DPLL_VCO_ENABLE;
7315         crtc_state->dpll_hw_state.dpll = dpll;
7316 }
7317
7318 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7319 {
7320         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7321         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7322         enum pipe pipe = crtc->pipe;
7323         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7324         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7325         uint32_t crtc_vtotal, crtc_vblank_end;
7326         int vsyncshift = 0;
7327
7328         /* We need to be careful not to changed the adjusted mode, for otherwise
7329          * the hw state checker will get angry at the mismatch. */
7330         crtc_vtotal = adjusted_mode->crtc_vtotal;
7331         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7332
7333         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7334                 /* the chip adds 2 halflines automatically */
7335                 crtc_vtotal -= 1;
7336                 crtc_vblank_end -= 1;
7337
7338                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7339                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7340                 else
7341                         vsyncshift = adjusted_mode->crtc_hsync_start -
7342                                 adjusted_mode->crtc_htotal / 2;
7343                 if (vsyncshift < 0)
7344                         vsyncshift += adjusted_mode->crtc_htotal;
7345         }
7346
7347         if (INTEL_GEN(dev_priv) > 3)
7348                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7349
7350         I915_WRITE(HTOTAL(cpu_transcoder),
7351                    (adjusted_mode->crtc_hdisplay - 1) |
7352                    ((adjusted_mode->crtc_htotal - 1) << 16));
7353         I915_WRITE(HBLANK(cpu_transcoder),
7354                    (adjusted_mode->crtc_hblank_start - 1) |
7355                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7356         I915_WRITE(HSYNC(cpu_transcoder),
7357                    (adjusted_mode->crtc_hsync_start - 1) |
7358                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7359
7360         I915_WRITE(VTOTAL(cpu_transcoder),
7361                    (adjusted_mode->crtc_vdisplay - 1) |
7362                    ((crtc_vtotal - 1) << 16));
7363         I915_WRITE(VBLANK(cpu_transcoder),
7364                    (adjusted_mode->crtc_vblank_start - 1) |
7365                    ((crtc_vblank_end - 1) << 16));
7366         I915_WRITE(VSYNC(cpu_transcoder),
7367                    (adjusted_mode->crtc_vsync_start - 1) |
7368                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7369
7370         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7371          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7372          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7373          * bits. */
7374         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7375             (pipe == PIPE_B || pipe == PIPE_C))
7376                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7377
7378 }
7379
7380 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
7381 {
7382         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7383         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7384         enum pipe pipe = crtc->pipe;
7385
7386         /* pipesrc controls the size that is scaled from, which should
7387          * always be the user's requested size.
7388          */
7389         I915_WRITE(PIPESRC(pipe),
7390                    ((crtc_state->pipe_src_w - 1) << 16) |
7391                    (crtc_state->pipe_src_h - 1));
7392 }
7393
7394 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7395                                    struct intel_crtc_state *pipe_config)
7396 {
7397         struct drm_device *dev = crtc->base.dev;
7398         struct drm_i915_private *dev_priv = to_i915(dev);
7399         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7400         uint32_t tmp;
7401
7402         tmp = I915_READ(HTOTAL(cpu_transcoder));
7403         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7404         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7405         tmp = I915_READ(HBLANK(cpu_transcoder));
7406         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7407         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7408         tmp = I915_READ(HSYNC(cpu_transcoder));
7409         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7410         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7411
7412         tmp = I915_READ(VTOTAL(cpu_transcoder));
7413         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7414         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7415         tmp = I915_READ(VBLANK(cpu_transcoder));
7416         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7417         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7418         tmp = I915_READ(VSYNC(cpu_transcoder));
7419         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7420         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7421
7422         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7423                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7424                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7425                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7426         }
7427 }
7428
7429 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7430                                     struct intel_crtc_state *pipe_config)
7431 {
7432         struct drm_device *dev = crtc->base.dev;
7433         struct drm_i915_private *dev_priv = to_i915(dev);
7434         u32 tmp;
7435
7436         tmp = I915_READ(PIPESRC(crtc->pipe));
7437         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7438         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7439
7440         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7441         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7442 }
7443
7444 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7445                                  struct intel_crtc_state *pipe_config)
7446 {
7447         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7448         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7449         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7450         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7451
7452         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7453         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7454         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7455         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7456
7457         mode->flags = pipe_config->base.adjusted_mode.flags;
7458         mode->type = DRM_MODE_TYPE_DRIVER;
7459
7460         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7461
7462         mode->hsync = drm_mode_hsync(mode);
7463         mode->vrefresh = drm_mode_vrefresh(mode);
7464         drm_mode_set_name(mode);
7465 }
7466
7467 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
7468 {
7469         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7470         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7471         uint32_t pipeconf;
7472
7473         pipeconf = 0;
7474
7475         /* we keep both pipes enabled on 830 */
7476         if (IS_I830(dev_priv))
7477                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
7478
7479         if (crtc_state->double_wide)
7480                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7481
7482         /* only g4x and later have fancy bpc/dither controls */
7483         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7484             IS_CHERRYVIEW(dev_priv)) {
7485                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7486                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
7487                         pipeconf |= PIPECONF_DITHER_EN |
7488                                     PIPECONF_DITHER_TYPE_SP;
7489
7490                 switch (crtc_state->pipe_bpp) {
7491                 case 18:
7492                         pipeconf |= PIPECONF_6BPC;
7493                         break;
7494                 case 24:
7495                         pipeconf |= PIPECONF_8BPC;
7496                         break;
7497                 case 30:
7498                         pipeconf |= PIPECONF_10BPC;
7499                         break;
7500                 default:
7501                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7502                         BUG();
7503                 }
7504         }
7505
7506         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7507                 if (INTEL_GEN(dev_priv) < 4 ||
7508                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7509                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7510                 else
7511                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7512         } else
7513                 pipeconf |= PIPECONF_PROGRESSIVE;
7514
7515         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7516              crtc_state->limited_color_range)
7517                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7518
7519         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
7520         POSTING_READ(PIPECONF(crtc->pipe));
7521 }
7522
7523 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7524                                    struct intel_crtc_state *crtc_state)
7525 {
7526         struct drm_device *dev = crtc->base.dev;
7527         struct drm_i915_private *dev_priv = to_i915(dev);
7528         const struct intel_limit *limit;
7529         int refclk = 48000;
7530
7531         memset(&crtc_state->dpll_hw_state, 0,
7532                sizeof(crtc_state->dpll_hw_state));
7533
7534         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7535                 if (intel_panel_use_ssc(dev_priv)) {
7536                         refclk = dev_priv->vbt.lvds_ssc_freq;
7537                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7538                 }
7539
7540                 limit = &intel_limits_i8xx_lvds;
7541         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7542                 limit = &intel_limits_i8xx_dvo;
7543         } else {
7544                 limit = &intel_limits_i8xx_dac;
7545         }
7546
7547         if (!crtc_state->clock_set &&
7548             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7549                                  refclk, NULL, &crtc_state->dpll)) {
7550                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7551                 return -EINVAL;
7552         }
7553
7554         i8xx_compute_dpll(crtc, crtc_state, NULL);
7555
7556         return 0;
7557 }
7558
7559 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7560                                   struct intel_crtc_state *crtc_state)
7561 {
7562         struct drm_device *dev = crtc->base.dev;
7563         struct drm_i915_private *dev_priv = to_i915(dev);
7564         const struct intel_limit *limit;
7565         int refclk = 96000;
7566
7567         memset(&crtc_state->dpll_hw_state, 0,
7568                sizeof(crtc_state->dpll_hw_state));
7569
7570         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7571                 if (intel_panel_use_ssc(dev_priv)) {
7572                         refclk = dev_priv->vbt.lvds_ssc_freq;
7573                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7574                 }
7575
7576                 if (intel_is_dual_link_lvds(dev))
7577                         limit = &intel_limits_g4x_dual_channel_lvds;
7578                 else
7579                         limit = &intel_limits_g4x_single_channel_lvds;
7580         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7581                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7582                 limit = &intel_limits_g4x_hdmi;
7583         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7584                 limit = &intel_limits_g4x_sdvo;
7585         } else {
7586                 /* The option is for other outputs */
7587                 limit = &intel_limits_i9xx_sdvo;
7588         }
7589
7590         if (!crtc_state->clock_set &&
7591             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7592                                 refclk, NULL, &crtc_state->dpll)) {
7593                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7594                 return -EINVAL;
7595         }
7596
7597         i9xx_compute_dpll(crtc, crtc_state, NULL);
7598
7599         return 0;
7600 }
7601
7602 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7603                                   struct intel_crtc_state *crtc_state)
7604 {
7605         struct drm_device *dev = crtc->base.dev;
7606         struct drm_i915_private *dev_priv = to_i915(dev);
7607         const struct intel_limit *limit;
7608         int refclk = 96000;
7609
7610         memset(&crtc_state->dpll_hw_state, 0,
7611                sizeof(crtc_state->dpll_hw_state));
7612
7613         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7614                 if (intel_panel_use_ssc(dev_priv)) {
7615                         refclk = dev_priv->vbt.lvds_ssc_freq;
7616                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7617                 }
7618
7619                 limit = &intel_limits_pineview_lvds;
7620         } else {
7621                 limit = &intel_limits_pineview_sdvo;
7622         }
7623
7624         if (!crtc_state->clock_set &&
7625             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7626                                 refclk, NULL, &crtc_state->dpll)) {
7627                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7628                 return -EINVAL;
7629         }
7630
7631         i9xx_compute_dpll(crtc, crtc_state, NULL);
7632
7633         return 0;
7634 }
7635
7636 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7637                                    struct intel_crtc_state *crtc_state)
7638 {
7639         struct drm_device *dev = crtc->base.dev;
7640         struct drm_i915_private *dev_priv = to_i915(dev);
7641         const struct intel_limit *limit;
7642         int refclk = 96000;
7643
7644         memset(&crtc_state->dpll_hw_state, 0,
7645                sizeof(crtc_state->dpll_hw_state));
7646
7647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7648                 if (intel_panel_use_ssc(dev_priv)) {
7649                         refclk = dev_priv->vbt.lvds_ssc_freq;
7650                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7651                 }
7652
7653                 limit = &intel_limits_i9xx_lvds;
7654         } else {
7655                 limit = &intel_limits_i9xx_sdvo;
7656         }
7657
7658         if (!crtc_state->clock_set &&
7659             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7660                                  refclk, NULL, &crtc_state->dpll)) {
7661                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7662                 return -EINVAL;
7663         }
7664
7665         i9xx_compute_dpll(crtc, crtc_state, NULL);
7666
7667         return 0;
7668 }
7669
7670 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7671                                   struct intel_crtc_state *crtc_state)
7672 {
7673         int refclk = 100000;
7674         const struct intel_limit *limit = &intel_limits_chv;
7675
7676         memset(&crtc_state->dpll_hw_state, 0,
7677                sizeof(crtc_state->dpll_hw_state));
7678
7679         if (!crtc_state->clock_set &&
7680             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7681                                 refclk, NULL, &crtc_state->dpll)) {
7682                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7683                 return -EINVAL;
7684         }
7685
7686         chv_compute_dpll(crtc, crtc_state);
7687
7688         return 0;
7689 }
7690
7691 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7692                                   struct intel_crtc_state *crtc_state)
7693 {
7694         int refclk = 100000;
7695         const struct intel_limit *limit = &intel_limits_vlv;
7696
7697         memset(&crtc_state->dpll_hw_state, 0,
7698                sizeof(crtc_state->dpll_hw_state));
7699
7700         if (!crtc_state->clock_set &&
7701             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7702                                 refclk, NULL, &crtc_state->dpll)) {
7703                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7704                 return -EINVAL;
7705         }
7706
7707         vlv_compute_dpll(crtc, crtc_state);
7708
7709         return 0;
7710 }
7711
7712 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7713                                  struct intel_crtc_state *pipe_config)
7714 {
7715         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7716         uint32_t tmp;
7717
7718         if (INTEL_GEN(dev_priv) <= 3 &&
7719             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7720                 return;
7721
7722         tmp = I915_READ(PFIT_CONTROL);
7723         if (!(tmp & PFIT_ENABLE))
7724                 return;
7725
7726         /* Check whether the pfit is attached to our pipe. */
7727         if (INTEL_GEN(dev_priv) < 4) {
7728                 if (crtc->pipe != PIPE_B)
7729                         return;
7730         } else {
7731                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7732                         return;
7733         }
7734
7735         pipe_config->gmch_pfit.control = tmp;
7736         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7737 }
7738
7739 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7740                                struct intel_crtc_state *pipe_config)
7741 {
7742         struct drm_device *dev = crtc->base.dev;
7743         struct drm_i915_private *dev_priv = to_i915(dev);
7744         int pipe = pipe_config->cpu_transcoder;
7745         struct dpll clock;
7746         u32 mdiv;
7747         int refclk = 100000;
7748
7749         /* In case of DSI, DPLL will not be used */
7750         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7751                 return;
7752
7753         mutex_lock(&dev_priv->sb_lock);
7754         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7755         mutex_unlock(&dev_priv->sb_lock);
7756
7757         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7758         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7759         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7760         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7761         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7762
7763         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7764 }
7765
7766 static void
7767 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7768                               struct intel_initial_plane_config *plane_config)
7769 {
7770         struct drm_device *dev = crtc->base.dev;
7771         struct drm_i915_private *dev_priv = to_i915(dev);
7772         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7773         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7774         enum pipe pipe;
7775         u32 val, base, offset;
7776         int fourcc, pixel_format;
7777         unsigned int aligned_height;
7778         struct drm_framebuffer *fb;
7779         struct intel_framebuffer *intel_fb;
7780
7781         if (!plane->get_hw_state(plane, &pipe))
7782                 return;
7783
7784         WARN_ON(pipe != crtc->pipe);
7785
7786         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7787         if (!intel_fb) {
7788                 DRM_DEBUG_KMS("failed to alloc fb\n");
7789                 return;
7790         }
7791
7792         fb = &intel_fb->base;
7793
7794         fb->dev = dev;
7795
7796         val = I915_READ(DSPCNTR(i9xx_plane));
7797
7798         if (INTEL_GEN(dev_priv) >= 4) {
7799                 if (val & DISPPLANE_TILED) {
7800                         plane_config->tiling = I915_TILING_X;
7801                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7802                 }
7803
7804                 if (val & DISPPLANE_ROTATE_180)
7805                         plane_config->rotation = DRM_MODE_ROTATE_180;
7806         }
7807
7808         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B &&
7809             val & DISPPLANE_MIRROR)
7810                 plane_config->rotation |= DRM_MODE_REFLECT_X;
7811
7812         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7813         fourcc = i9xx_format_to_fourcc(pixel_format);
7814         fb->format = drm_format_info(fourcc);
7815
7816         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7817                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7818                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7819         } else if (INTEL_GEN(dev_priv) >= 4) {
7820                 if (plane_config->tiling)
7821                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7822                 else
7823                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7824                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7825         } else {
7826                 base = I915_READ(DSPADDR(i9xx_plane));
7827         }
7828         plane_config->base = base;
7829
7830         val = I915_READ(PIPESRC(pipe));
7831         fb->width = ((val >> 16) & 0xfff) + 1;
7832         fb->height = ((val >> 0) & 0xfff) + 1;
7833
7834         val = I915_READ(DSPSTRIDE(i9xx_plane));
7835         fb->pitches[0] = val & 0xffffffc0;
7836
7837         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7838
7839         plane_config->size = fb->pitches[0] * aligned_height;
7840
7841         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7842                       crtc->base.name, plane->base.name, fb->width, fb->height,
7843                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7844                       plane_config->size);
7845
7846         plane_config->fb = intel_fb;
7847 }
7848
7849 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7850                                struct intel_crtc_state *pipe_config)
7851 {
7852         struct drm_device *dev = crtc->base.dev;
7853         struct drm_i915_private *dev_priv = to_i915(dev);
7854         int pipe = pipe_config->cpu_transcoder;
7855         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7856         struct dpll clock;
7857         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7858         int refclk = 100000;
7859
7860         /* In case of DSI, DPLL will not be used */
7861         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7862                 return;
7863
7864         mutex_lock(&dev_priv->sb_lock);
7865         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7866         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7867         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7868         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7869         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7870         mutex_unlock(&dev_priv->sb_lock);
7871
7872         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7873         clock.m2 = (pll_dw0 & 0xff) << 22;
7874         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7875                 clock.m2 |= pll_dw2 & 0x3fffff;
7876         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7877         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7878         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7879
7880         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7881 }
7882
7883 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
7884                                         struct intel_crtc_state *pipe_config)
7885 {
7886         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7887         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
7888
7889         pipe_config->lspcon_downsampling = false;
7890
7891         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
7892                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
7893
7894                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
7895                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
7896                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
7897
7898                         if (ycbcr420_enabled) {
7899                                 /* We support 4:2:0 in full blend mode only */
7900                                 if (!blend)
7901                                         output = INTEL_OUTPUT_FORMAT_INVALID;
7902                                 else if (!(IS_GEMINILAKE(dev_priv) ||
7903                                            INTEL_GEN(dev_priv) >= 10))
7904                                         output = INTEL_OUTPUT_FORMAT_INVALID;
7905                                 else
7906                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
7907                         } else {
7908                                 /*
7909                                  * Currently there is no interface defined to
7910                                  * check user preference between RGB/YCBCR444
7911                                  * or YCBCR420. So the only possible case for
7912                                  * YCBCR444 usage is driving YCBCR420 output
7913                                  * with LSPCON, when pipe is configured for
7914                                  * YCBCR444 output and LSPCON takes care of
7915                                  * downsampling it.
7916                                  */
7917                                 pipe_config->lspcon_downsampling = true;
7918                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
7919                         }
7920                 }
7921         }
7922
7923         pipe_config->output_format = output;
7924 }
7925
7926 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7927                                  struct intel_crtc_state *pipe_config)
7928 {
7929         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7930         enum intel_display_power_domain power_domain;
7931         uint32_t tmp;
7932         bool ret;
7933
7934         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7935         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7936                 return false;
7937
7938         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
7939         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7940         pipe_config->shared_dpll = NULL;
7941
7942         ret = false;
7943
7944         tmp = I915_READ(PIPECONF(crtc->pipe));
7945         if (!(tmp & PIPECONF_ENABLE))
7946                 goto out;
7947
7948         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7949             IS_CHERRYVIEW(dev_priv)) {
7950                 switch (tmp & PIPECONF_BPC_MASK) {
7951                 case PIPECONF_6BPC:
7952                         pipe_config->pipe_bpp = 18;
7953                         break;
7954                 case PIPECONF_8BPC:
7955                         pipe_config->pipe_bpp = 24;
7956                         break;
7957                 case PIPECONF_10BPC:
7958                         pipe_config->pipe_bpp = 30;
7959                         break;
7960                 default:
7961                         break;
7962                 }
7963         }
7964
7965         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7966             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7967                 pipe_config->limited_color_range = true;
7968
7969         if (INTEL_GEN(dev_priv) < 4)
7970                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7971
7972         intel_get_pipe_timings(crtc, pipe_config);
7973         intel_get_pipe_src_size(crtc, pipe_config);
7974
7975         i9xx_get_pfit_config(crtc, pipe_config);
7976
7977         if (INTEL_GEN(dev_priv) >= 4) {
7978                 /* No way to read it out on pipes B and C */
7979                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7980                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7981                 else
7982                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7983                 pipe_config->pixel_multiplier =
7984                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7985                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7986                 pipe_config->dpll_hw_state.dpll_md = tmp;
7987         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7988                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7989                 tmp = I915_READ(DPLL(crtc->pipe));
7990                 pipe_config->pixel_multiplier =
7991                         ((tmp & SDVO_MULTIPLIER_MASK)
7992                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7993         } else {
7994                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7995                  * port and will be fixed up in the encoder->get_config
7996                  * function. */
7997                 pipe_config->pixel_multiplier = 1;
7998         }
7999         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8000         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8001                 /*
8002                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8003                  * on 830. Filter it out here so that we don't
8004                  * report errors due to that.
8005                  */
8006                 if (IS_I830(dev_priv))
8007                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8008
8009                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8010                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8011         } else {
8012                 /* Mask out read-only status bits. */
8013                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8014                                                      DPLL_PORTC_READY_MASK |
8015                                                      DPLL_PORTB_READY_MASK);
8016         }
8017
8018         if (IS_CHERRYVIEW(dev_priv))
8019                 chv_crtc_clock_get(crtc, pipe_config);
8020         else if (IS_VALLEYVIEW(dev_priv))
8021                 vlv_crtc_clock_get(crtc, pipe_config);
8022         else
8023                 i9xx_crtc_clock_get(crtc, pipe_config);
8024
8025         /*
8026          * Normally the dotclock is filled in by the encoder .get_config()
8027          * but in case the pipe is enabled w/o any ports we need a sane
8028          * default.
8029          */
8030         pipe_config->base.adjusted_mode.crtc_clock =
8031                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8032
8033         ret = true;
8034
8035 out:
8036         intel_display_power_put(dev_priv, power_domain);
8037
8038         return ret;
8039 }
8040
8041 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8042 {
8043         struct intel_encoder *encoder;
8044         int i;
8045         u32 val, final;
8046         bool has_lvds = false;
8047         bool has_cpu_edp = false;
8048         bool has_panel = false;
8049         bool has_ck505 = false;
8050         bool can_ssc = false;
8051         bool using_ssc_source = false;
8052
8053         /* We need to take the global config into account */
8054         for_each_intel_encoder(&dev_priv->drm, encoder) {
8055                 switch (encoder->type) {
8056                 case INTEL_OUTPUT_LVDS:
8057                         has_panel = true;
8058                         has_lvds = true;
8059                         break;
8060                 case INTEL_OUTPUT_EDP:
8061                         has_panel = true;
8062                         if (encoder->port == PORT_A)
8063                                 has_cpu_edp = true;
8064                         break;
8065                 default:
8066                         break;
8067                 }
8068         }
8069
8070         if (HAS_PCH_IBX(dev_priv)) {
8071                 has_ck505 = dev_priv->vbt.display_clock_mode;
8072                 can_ssc = has_ck505;
8073         } else {
8074                 has_ck505 = false;
8075                 can_ssc = true;
8076         }
8077
8078         /* Check if any DPLLs are using the SSC source */
8079         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8080                 u32 temp = I915_READ(PCH_DPLL(i));
8081
8082                 if (!(temp & DPLL_VCO_ENABLE))
8083                         continue;
8084
8085                 if ((temp & PLL_REF_INPUT_MASK) ==
8086                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8087                         using_ssc_source = true;
8088                         break;
8089                 }
8090         }
8091
8092         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8093                       has_panel, has_lvds, has_ck505, using_ssc_source);
8094
8095         /* Ironlake: try to setup display ref clock before DPLL
8096          * enabling. This is only under driver's control after
8097          * PCH B stepping, previous chipset stepping should be
8098          * ignoring this setting.
8099          */
8100         val = I915_READ(PCH_DREF_CONTROL);
8101
8102         /* As we must carefully and slowly disable/enable each source in turn,
8103          * compute the final state we want first and check if we need to
8104          * make any changes at all.
8105          */
8106         final = val;
8107         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8108         if (has_ck505)
8109                 final |= DREF_NONSPREAD_CK505_ENABLE;
8110         else
8111                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8112
8113         final &= ~DREF_SSC_SOURCE_MASK;
8114         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8115         final &= ~DREF_SSC1_ENABLE;
8116
8117         if (has_panel) {
8118                 final |= DREF_SSC_SOURCE_ENABLE;
8119
8120                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8121                         final |= DREF_SSC1_ENABLE;
8122
8123                 if (has_cpu_edp) {
8124                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8125                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8126                         else
8127                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8128                 } else
8129                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8130         } else if (using_ssc_source) {
8131                 final |= DREF_SSC_SOURCE_ENABLE;
8132                 final |= DREF_SSC1_ENABLE;
8133         }
8134
8135         if (final == val)
8136                 return;
8137
8138         /* Always enable nonspread source */
8139         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8140
8141         if (has_ck505)
8142                 val |= DREF_NONSPREAD_CK505_ENABLE;
8143         else
8144                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8145
8146         if (has_panel) {
8147                 val &= ~DREF_SSC_SOURCE_MASK;
8148                 val |= DREF_SSC_SOURCE_ENABLE;
8149
8150                 /* SSC must be turned on before enabling the CPU output  */
8151                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8152                         DRM_DEBUG_KMS("Using SSC on panel\n");
8153                         val |= DREF_SSC1_ENABLE;
8154                 } else
8155                         val &= ~DREF_SSC1_ENABLE;
8156
8157                 /* Get SSC going before enabling the outputs */
8158                 I915_WRITE(PCH_DREF_CONTROL, val);
8159                 POSTING_READ(PCH_DREF_CONTROL);
8160                 udelay(200);
8161
8162                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8163
8164                 /* Enable CPU source on CPU attached eDP */
8165                 if (has_cpu_edp) {
8166                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8167                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8168                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8169                         } else
8170                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8171                 } else
8172                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8173
8174                 I915_WRITE(PCH_DREF_CONTROL, val);
8175                 POSTING_READ(PCH_DREF_CONTROL);
8176                 udelay(200);
8177         } else {
8178                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8179
8180                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8181
8182                 /* Turn off CPU output */
8183                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8184
8185                 I915_WRITE(PCH_DREF_CONTROL, val);
8186                 POSTING_READ(PCH_DREF_CONTROL);
8187                 udelay(200);
8188
8189                 if (!using_ssc_source) {
8190                         DRM_DEBUG_KMS("Disabling SSC source\n");
8191
8192                         /* Turn off the SSC source */
8193                         val &= ~DREF_SSC_SOURCE_MASK;
8194                         val |= DREF_SSC_SOURCE_DISABLE;
8195
8196                         /* Turn off SSC1 */
8197                         val &= ~DREF_SSC1_ENABLE;
8198
8199                         I915_WRITE(PCH_DREF_CONTROL, val);
8200                         POSTING_READ(PCH_DREF_CONTROL);
8201                         udelay(200);
8202                 }
8203         }
8204
8205         BUG_ON(val != final);
8206 }
8207
8208 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8209 {
8210         uint32_t tmp;
8211
8212         tmp = I915_READ(SOUTH_CHICKEN2);
8213         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8214         I915_WRITE(SOUTH_CHICKEN2, tmp);
8215
8216         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8217                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8218                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8219
8220         tmp = I915_READ(SOUTH_CHICKEN2);
8221         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8222         I915_WRITE(SOUTH_CHICKEN2, tmp);
8223
8224         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8225                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8226                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8227 }
8228
8229 /* WaMPhyProgramming:hsw */
8230 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8231 {
8232         uint32_t tmp;
8233
8234         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8235         tmp &= ~(0xFF << 24);
8236         tmp |= (0x12 << 24);
8237         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8238
8239         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8240         tmp |= (1 << 11);
8241         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8242
8243         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8244         tmp |= (1 << 11);
8245         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8246
8247         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8248         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8249         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8250
8251         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8252         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8253         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8254
8255         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8256         tmp &= ~(7 << 13);
8257         tmp |= (5 << 13);
8258         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8259
8260         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8261         tmp &= ~(7 << 13);
8262         tmp |= (5 << 13);
8263         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8264
8265         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8266         tmp &= ~0xFF;
8267         tmp |= 0x1C;
8268         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8269
8270         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8271         tmp &= ~0xFF;
8272         tmp |= 0x1C;
8273         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8274
8275         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8276         tmp &= ~(0xFF << 16);
8277         tmp |= (0x1C << 16);
8278         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8279
8280         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8281         tmp &= ~(0xFF << 16);
8282         tmp |= (0x1C << 16);
8283         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8284
8285         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8286         tmp |= (1 << 27);
8287         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8288
8289         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8290         tmp |= (1 << 27);
8291         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8292
8293         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8294         tmp &= ~(0xF << 28);
8295         tmp |= (4 << 28);
8296         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8297
8298         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8299         tmp &= ~(0xF << 28);
8300         tmp |= (4 << 28);
8301         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8302 }
8303
8304 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8305  * Programming" based on the parameters passed:
8306  * - Sequence to enable CLKOUT_DP
8307  * - Sequence to enable CLKOUT_DP without spread
8308  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8309  */
8310 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8311                                  bool with_spread, bool with_fdi)
8312 {
8313         uint32_t reg, tmp;
8314
8315         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8316                 with_spread = true;
8317         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8318             with_fdi, "LP PCH doesn't have FDI\n"))
8319                 with_fdi = false;
8320
8321         mutex_lock(&dev_priv->sb_lock);
8322
8323         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8324         tmp &= ~SBI_SSCCTL_DISABLE;
8325         tmp |= SBI_SSCCTL_PATHALT;
8326         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8327
8328         udelay(24);
8329
8330         if (with_spread) {
8331                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8332                 tmp &= ~SBI_SSCCTL_PATHALT;
8333                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8334
8335                 if (with_fdi) {
8336                         lpt_reset_fdi_mphy(dev_priv);
8337                         lpt_program_fdi_mphy(dev_priv);
8338                 }
8339         }
8340
8341         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8342         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8343         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8344         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8345
8346         mutex_unlock(&dev_priv->sb_lock);
8347 }
8348
8349 /* Sequence to disable CLKOUT_DP */
8350 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8351 {
8352         uint32_t reg, tmp;
8353
8354         mutex_lock(&dev_priv->sb_lock);
8355
8356         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8357         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8358         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8359         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8360
8361         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8362         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8363                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8364                         tmp |= SBI_SSCCTL_PATHALT;
8365                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8366                         udelay(32);
8367                 }
8368                 tmp |= SBI_SSCCTL_DISABLE;
8369                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8370         }
8371
8372         mutex_unlock(&dev_priv->sb_lock);
8373 }
8374
8375 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8376
8377 static const uint16_t sscdivintphase[] = {
8378         [BEND_IDX( 50)] = 0x3B23,
8379         [BEND_IDX( 45)] = 0x3B23,
8380         [BEND_IDX( 40)] = 0x3C23,
8381         [BEND_IDX( 35)] = 0x3C23,
8382         [BEND_IDX( 30)] = 0x3D23,
8383         [BEND_IDX( 25)] = 0x3D23,
8384         [BEND_IDX( 20)] = 0x3E23,
8385         [BEND_IDX( 15)] = 0x3E23,
8386         [BEND_IDX( 10)] = 0x3F23,
8387         [BEND_IDX(  5)] = 0x3F23,
8388         [BEND_IDX(  0)] = 0x0025,
8389         [BEND_IDX( -5)] = 0x0025,
8390         [BEND_IDX(-10)] = 0x0125,
8391         [BEND_IDX(-15)] = 0x0125,
8392         [BEND_IDX(-20)] = 0x0225,
8393         [BEND_IDX(-25)] = 0x0225,
8394         [BEND_IDX(-30)] = 0x0325,
8395         [BEND_IDX(-35)] = 0x0325,
8396         [BEND_IDX(-40)] = 0x0425,
8397         [BEND_IDX(-45)] = 0x0425,
8398         [BEND_IDX(-50)] = 0x0525,
8399 };
8400
8401 /*
8402  * Bend CLKOUT_DP
8403  * steps -50 to 50 inclusive, in steps of 5
8404  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8405  * change in clock period = -(steps / 10) * 5.787 ps
8406  */
8407 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8408 {
8409         uint32_t tmp;
8410         int idx = BEND_IDX(steps);
8411
8412         if (WARN_ON(steps % 5 != 0))
8413                 return;
8414
8415         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8416                 return;
8417
8418         mutex_lock(&dev_priv->sb_lock);
8419
8420         if (steps % 10 != 0)
8421                 tmp = 0xAAAAAAAB;
8422         else
8423                 tmp = 0x00000000;
8424         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8425
8426         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8427         tmp &= 0xffff0000;
8428         tmp |= sscdivintphase[idx];
8429         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8430
8431         mutex_unlock(&dev_priv->sb_lock);
8432 }
8433
8434 #undef BEND_IDX
8435
8436 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8437 {
8438         struct intel_encoder *encoder;
8439         bool has_vga = false;
8440
8441         for_each_intel_encoder(&dev_priv->drm, encoder) {
8442                 switch (encoder->type) {
8443                 case INTEL_OUTPUT_ANALOG:
8444                         has_vga = true;
8445                         break;
8446                 default:
8447                         break;
8448                 }
8449         }
8450
8451         if (has_vga) {
8452                 lpt_bend_clkout_dp(dev_priv, 0);
8453                 lpt_enable_clkout_dp(dev_priv, true, true);
8454         } else {
8455                 lpt_disable_clkout_dp(dev_priv);
8456         }
8457 }
8458
8459 /*
8460  * Initialize reference clocks when the driver loads
8461  */
8462 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8463 {
8464         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8465                 ironlake_init_pch_refclk(dev_priv);
8466         else if (HAS_PCH_LPT(dev_priv))
8467                 lpt_init_pch_refclk(dev_priv);
8468 }
8469
8470 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
8471 {
8472         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8473         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8474         enum pipe pipe = crtc->pipe;
8475         uint32_t val;
8476
8477         val = 0;
8478
8479         switch (crtc_state->pipe_bpp) {
8480         case 18:
8481                 val |= PIPECONF_6BPC;
8482                 break;
8483         case 24:
8484                 val |= PIPECONF_8BPC;
8485                 break;
8486         case 30:
8487                 val |= PIPECONF_10BPC;
8488                 break;
8489         case 36:
8490                 val |= PIPECONF_12BPC;
8491                 break;
8492         default:
8493                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8494                 BUG();
8495         }
8496
8497         if (crtc_state->dither)
8498                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8499
8500         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8501                 val |= PIPECONF_INTERLACED_ILK;
8502         else
8503                 val |= PIPECONF_PROGRESSIVE;
8504
8505         if (crtc_state->limited_color_range)
8506                 val |= PIPECONF_COLOR_RANGE_SELECT;
8507
8508         I915_WRITE(PIPECONF(pipe), val);
8509         POSTING_READ(PIPECONF(pipe));
8510 }
8511
8512 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
8513 {
8514         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8515         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8516         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
8517         u32 val = 0;
8518
8519         if (IS_HASWELL(dev_priv) && crtc_state->dither)
8520                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8521
8522         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8523                 val |= PIPECONF_INTERLACED_ILK;
8524         else
8525                 val |= PIPECONF_PROGRESSIVE;
8526
8527         I915_WRITE(PIPECONF(cpu_transcoder), val);
8528         POSTING_READ(PIPECONF(cpu_transcoder));
8529 }
8530
8531 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state)
8532 {
8533         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
8534         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8535
8536         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8537                 u32 val = 0;
8538
8539                 switch (crtc_state->pipe_bpp) {
8540                 case 18:
8541                         val |= PIPEMISC_DITHER_6_BPC;
8542                         break;
8543                 case 24:
8544                         val |= PIPEMISC_DITHER_8_BPC;
8545                         break;
8546                 case 30:
8547                         val |= PIPEMISC_DITHER_10_BPC;
8548                         break;
8549                 case 36:
8550                         val |= PIPEMISC_DITHER_12_BPC;
8551                         break;
8552                 default:
8553                         /* Case prevented by pipe_config_set_bpp. */
8554                         BUG();
8555                 }
8556
8557                 if (crtc_state->dither)
8558                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8559
8560                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
8561                     crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
8562                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
8563
8564                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
8565                         val |= PIPEMISC_YUV420_ENABLE |
8566                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8567
8568                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8569         }
8570 }
8571
8572 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8573 {
8574         /*
8575          * Account for spread spectrum to avoid
8576          * oversubscribing the link. Max center spread
8577          * is 2.5%; use 5% for safety's sake.
8578          */
8579         u32 bps = target_clock * bpp * 21 / 20;
8580         return DIV_ROUND_UP(bps, link_bw * 8);
8581 }
8582
8583 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8584 {
8585         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8586 }
8587
8588 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8589                                   struct intel_crtc_state *crtc_state,
8590                                   struct dpll *reduced_clock)
8591 {
8592         struct drm_crtc *crtc = &intel_crtc->base;
8593         struct drm_device *dev = crtc->dev;
8594         struct drm_i915_private *dev_priv = to_i915(dev);
8595         u32 dpll, fp, fp2;
8596         int factor;
8597
8598         /* Enable autotuning of the PLL clock (if permissible) */
8599         factor = 21;
8600         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8601                 if ((intel_panel_use_ssc(dev_priv) &&
8602                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8603                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8604                         factor = 25;
8605         } else if (crtc_state->sdvo_tv_clock)
8606                 factor = 20;
8607
8608         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8609
8610         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8611                 fp |= FP_CB_TUNE;
8612
8613         if (reduced_clock) {
8614                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8615
8616                 if (reduced_clock->m < factor * reduced_clock->n)
8617                         fp2 |= FP_CB_TUNE;
8618         } else {
8619                 fp2 = fp;
8620         }
8621
8622         dpll = 0;
8623
8624         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8625                 dpll |= DPLLB_MODE_LVDS;
8626         else
8627                 dpll |= DPLLB_MODE_DAC_SERIAL;
8628
8629         dpll |= (crtc_state->pixel_multiplier - 1)
8630                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8631
8632         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8633             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8634                 dpll |= DPLL_SDVO_HIGH_SPEED;
8635
8636         if (intel_crtc_has_dp_encoder(crtc_state))
8637                 dpll |= DPLL_SDVO_HIGH_SPEED;
8638
8639         /*
8640          * The high speed IO clock is only really required for
8641          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8642          * possible to share the DPLL between CRT and HDMI. Enabling
8643          * the clock needlessly does no real harm, except use up a
8644          * bit of power potentially.
8645          *
8646          * We'll limit this to IVB with 3 pipes, since it has only two
8647          * DPLLs and so DPLL sharing is the only way to get three pipes
8648          * driving PCH ports at the same time. On SNB we could do this,
8649          * and potentially avoid enabling the second DPLL, but it's not
8650          * clear if it''s a win or loss power wise. No point in doing
8651          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8652          */
8653         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8654             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8655                 dpll |= DPLL_SDVO_HIGH_SPEED;
8656
8657         /* compute bitmask from p1 value */
8658         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8659         /* also FPA1 */
8660         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8661
8662         switch (crtc_state->dpll.p2) {
8663         case 5:
8664                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8665                 break;
8666         case 7:
8667                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8668                 break;
8669         case 10:
8670                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8671                 break;
8672         case 14:
8673                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8674                 break;
8675         }
8676
8677         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8678             intel_panel_use_ssc(dev_priv))
8679                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8680         else
8681                 dpll |= PLL_REF_INPUT_DREFCLK;
8682
8683         dpll |= DPLL_VCO_ENABLE;
8684
8685         crtc_state->dpll_hw_state.dpll = dpll;
8686         crtc_state->dpll_hw_state.fp0 = fp;
8687         crtc_state->dpll_hw_state.fp1 = fp2;
8688 }
8689
8690 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8691                                        struct intel_crtc_state *crtc_state)
8692 {
8693         struct drm_device *dev = crtc->base.dev;
8694         struct drm_i915_private *dev_priv = to_i915(dev);
8695         const struct intel_limit *limit;
8696         int refclk = 120000;
8697
8698         memset(&crtc_state->dpll_hw_state, 0,
8699                sizeof(crtc_state->dpll_hw_state));
8700
8701         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8702         if (!crtc_state->has_pch_encoder)
8703                 return 0;
8704
8705         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8706                 if (intel_panel_use_ssc(dev_priv)) {
8707                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8708                                       dev_priv->vbt.lvds_ssc_freq);
8709                         refclk = dev_priv->vbt.lvds_ssc_freq;
8710                 }
8711
8712                 if (intel_is_dual_link_lvds(dev)) {
8713                         if (refclk == 100000)
8714                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8715                         else
8716                                 limit = &intel_limits_ironlake_dual_lvds;
8717                 } else {
8718                         if (refclk == 100000)
8719                                 limit = &intel_limits_ironlake_single_lvds_100m;
8720                         else
8721                                 limit = &intel_limits_ironlake_single_lvds;
8722                 }
8723         } else {
8724                 limit = &intel_limits_ironlake_dac;
8725         }
8726
8727         if (!crtc_state->clock_set &&
8728             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8729                                 refclk, NULL, &crtc_state->dpll)) {
8730                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8731                 return -EINVAL;
8732         }
8733
8734         ironlake_compute_dpll(crtc, crtc_state, NULL);
8735
8736         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8737                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
8738                               pipe_name(crtc->pipe));
8739                 return -EINVAL;
8740         }
8741
8742         return 0;
8743 }
8744
8745 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8746                                          struct intel_link_m_n *m_n)
8747 {
8748         struct drm_device *dev = crtc->base.dev;
8749         struct drm_i915_private *dev_priv = to_i915(dev);
8750         enum pipe pipe = crtc->pipe;
8751
8752         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8753         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8754         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8755                 & ~TU_SIZE_MASK;
8756         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8757         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8758                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8759 }
8760
8761 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8762                                          enum transcoder transcoder,
8763                                          struct intel_link_m_n *m_n,
8764                                          struct intel_link_m_n *m2_n2)
8765 {
8766         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8767         enum pipe pipe = crtc->pipe;
8768
8769         if (INTEL_GEN(dev_priv) >= 5) {
8770                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8771                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8772                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8773                         & ~TU_SIZE_MASK;
8774                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8775                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8776                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8777
8778                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
8779                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8780                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8781                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8782                                         & ~TU_SIZE_MASK;
8783                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8784                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8785                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8786                 }
8787         } else {
8788                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8789                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8790                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8791                         & ~TU_SIZE_MASK;
8792                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8793                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8794                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8795         }
8796 }
8797
8798 void intel_dp_get_m_n(struct intel_crtc *crtc,
8799                       struct intel_crtc_state *pipe_config)
8800 {
8801         if (pipe_config->has_pch_encoder)
8802                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8803         else
8804                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8805                                              &pipe_config->dp_m_n,
8806                                              &pipe_config->dp_m2_n2);
8807 }
8808
8809 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8810                                         struct intel_crtc_state *pipe_config)
8811 {
8812         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8813                                      &pipe_config->fdi_m_n, NULL);
8814 }
8815
8816 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8817                                     struct intel_crtc_state *pipe_config)
8818 {
8819         struct drm_device *dev = crtc->base.dev;
8820         struct drm_i915_private *dev_priv = to_i915(dev);
8821         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8822         uint32_t ps_ctrl = 0;
8823         int id = -1;
8824         int i;
8825
8826         /* find scaler attached to this pipe */
8827         for (i = 0; i < crtc->num_scalers; i++) {
8828                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8829                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8830                         id = i;
8831                         pipe_config->pch_pfit.enabled = true;
8832                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8833                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8834                         break;
8835                 }
8836         }
8837
8838         scaler_state->scaler_id = id;
8839         if (id >= 0) {
8840                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8841         } else {
8842                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8843         }
8844 }
8845
8846 static void
8847 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8848                                  struct intel_initial_plane_config *plane_config)
8849 {
8850         struct drm_device *dev = crtc->base.dev;
8851         struct drm_i915_private *dev_priv = to_i915(dev);
8852         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8853         enum plane_id plane_id = plane->id;
8854         enum pipe pipe;
8855         u32 val, base, offset, stride_mult, tiling, alpha;
8856         int fourcc, pixel_format;
8857         unsigned int aligned_height;
8858         struct drm_framebuffer *fb;
8859         struct intel_framebuffer *intel_fb;
8860
8861         if (!plane->get_hw_state(plane, &pipe))
8862                 return;
8863
8864         WARN_ON(pipe != crtc->pipe);
8865
8866         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8867         if (!intel_fb) {
8868                 DRM_DEBUG_KMS("failed to alloc fb\n");
8869                 return;
8870         }
8871
8872         fb = &intel_fb->base;
8873
8874         fb->dev = dev;
8875
8876         val = I915_READ(PLANE_CTL(pipe, plane_id));
8877
8878         if (INTEL_GEN(dev_priv) >= 11)
8879                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8880         else
8881                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8882
8883         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8884                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8885                 alpha &= PLANE_COLOR_ALPHA_MASK;
8886         } else {
8887                 alpha = val & PLANE_CTL_ALPHA_MASK;
8888         }
8889
8890         fourcc = skl_format_to_fourcc(pixel_format,
8891                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8892         fb->format = drm_format_info(fourcc);
8893
8894         tiling = val & PLANE_CTL_TILED_MASK;
8895         switch (tiling) {
8896         case PLANE_CTL_TILED_LINEAR:
8897                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8898                 break;
8899         case PLANE_CTL_TILED_X:
8900                 plane_config->tiling = I915_TILING_X;
8901                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8902                 break;
8903         case PLANE_CTL_TILED_Y:
8904                 plane_config->tiling = I915_TILING_Y;
8905                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8906                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8907                 else
8908                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8909                 break;
8910         case PLANE_CTL_TILED_YF:
8911                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8912                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8913                 else
8914                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8915                 break;
8916         default:
8917                 MISSING_CASE(tiling);
8918                 goto error;
8919         }
8920
8921         /*
8922          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
8923          * while i915 HW rotation is clockwise, thats why this swapping.
8924          */
8925         switch (val & PLANE_CTL_ROTATE_MASK) {
8926         case PLANE_CTL_ROTATE_0:
8927                 plane_config->rotation = DRM_MODE_ROTATE_0;
8928                 break;
8929         case PLANE_CTL_ROTATE_90:
8930                 plane_config->rotation = DRM_MODE_ROTATE_270;
8931                 break;
8932         case PLANE_CTL_ROTATE_180:
8933                 plane_config->rotation = DRM_MODE_ROTATE_180;
8934                 break;
8935         case PLANE_CTL_ROTATE_270:
8936                 plane_config->rotation = DRM_MODE_ROTATE_90;
8937                 break;
8938         }
8939
8940         if (INTEL_GEN(dev_priv) >= 10 &&
8941             val & PLANE_CTL_FLIP_HORIZONTAL)
8942                 plane_config->rotation |= DRM_MODE_REFLECT_X;
8943
8944         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8945         plane_config->base = base;
8946
8947         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8948
8949         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8950         fb->height = ((val >> 16) & 0xfff) + 1;
8951         fb->width = ((val >> 0) & 0x1fff) + 1;
8952
8953         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8954         stride_mult = intel_fb_stride_alignment(fb, 0);
8955         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8956
8957         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8958
8959         plane_config->size = fb->pitches[0] * aligned_height;
8960
8961         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8962                       crtc->base.name, plane->base.name, fb->width, fb->height,
8963                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8964                       plane_config->size);
8965
8966         plane_config->fb = intel_fb;
8967         return;
8968
8969 error:
8970         kfree(intel_fb);
8971 }
8972
8973 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8974                                      struct intel_crtc_state *pipe_config)
8975 {
8976         struct drm_device *dev = crtc->base.dev;
8977         struct drm_i915_private *dev_priv = to_i915(dev);
8978         uint32_t tmp;
8979
8980         tmp = I915_READ(PF_CTL(crtc->pipe));
8981
8982         if (tmp & PF_ENABLE) {
8983                 pipe_config->pch_pfit.enabled = true;
8984                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8985                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8986
8987                 /* We currently do not free assignements of panel fitters on
8988                  * ivb/hsw (since we don't use the higher upscaling modes which
8989                  * differentiates them) so just WARN about this case for now. */
8990                 if (IS_GEN7(dev_priv)) {
8991                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8992                                 PF_PIPE_SEL_IVB(crtc->pipe));
8993                 }
8994         }
8995 }
8996
8997 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8998                                      struct intel_crtc_state *pipe_config)
8999 {
9000         struct drm_device *dev = crtc->base.dev;
9001         struct drm_i915_private *dev_priv = to_i915(dev);
9002         enum intel_display_power_domain power_domain;
9003         uint32_t tmp;
9004         bool ret;
9005
9006         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9007         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9008                 return false;
9009
9010         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
9011         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9012         pipe_config->shared_dpll = NULL;
9013
9014         ret = false;
9015         tmp = I915_READ(PIPECONF(crtc->pipe));
9016         if (!(tmp & PIPECONF_ENABLE))
9017                 goto out;
9018
9019         switch (tmp & PIPECONF_BPC_MASK) {
9020         case PIPECONF_6BPC:
9021                 pipe_config->pipe_bpp = 18;
9022                 break;
9023         case PIPECONF_8BPC:
9024                 pipe_config->pipe_bpp = 24;
9025                 break;
9026         case PIPECONF_10BPC:
9027                 pipe_config->pipe_bpp = 30;
9028                 break;
9029         case PIPECONF_12BPC:
9030                 pipe_config->pipe_bpp = 36;
9031                 break;
9032         default:
9033                 break;
9034         }
9035
9036         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9037                 pipe_config->limited_color_range = true;
9038
9039         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9040                 struct intel_shared_dpll *pll;
9041                 enum intel_dpll_id pll_id;
9042
9043                 pipe_config->has_pch_encoder = true;
9044
9045                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9046                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9047                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9048
9049                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9050
9051                 if (HAS_PCH_IBX(dev_priv)) {
9052                         /*
9053                          * The pipe->pch transcoder and pch transcoder->pll
9054                          * mapping is fixed.
9055                          */
9056                         pll_id = (enum intel_dpll_id) crtc->pipe;
9057                 } else {
9058                         tmp = I915_READ(PCH_DPLL_SEL);
9059                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9060                                 pll_id = DPLL_ID_PCH_PLL_B;
9061                         else
9062                                 pll_id= DPLL_ID_PCH_PLL_A;
9063                 }
9064
9065                 pipe_config->shared_dpll =
9066                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9067                 pll = pipe_config->shared_dpll;
9068
9069                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9070                                                 &pipe_config->dpll_hw_state));
9071
9072                 tmp = pipe_config->dpll_hw_state.dpll;
9073                 pipe_config->pixel_multiplier =
9074                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9075                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9076
9077                 ironlake_pch_clock_get(crtc, pipe_config);
9078         } else {
9079                 pipe_config->pixel_multiplier = 1;
9080         }
9081
9082         intel_get_pipe_timings(crtc, pipe_config);
9083         intel_get_pipe_src_size(crtc, pipe_config);
9084
9085         ironlake_get_pfit_config(crtc, pipe_config);
9086
9087         ret = true;
9088
9089 out:
9090         intel_display_power_put(dev_priv, power_domain);
9091
9092         return ret;
9093 }
9094
9095 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9096 {
9097         struct drm_device *dev = &dev_priv->drm;
9098         struct intel_crtc *crtc;
9099
9100         for_each_intel_crtc(dev, crtc)
9101                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9102                      pipe_name(crtc->pipe));
9103
9104         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
9105                         "Display power well on\n");
9106         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9107         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9108         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9109         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9110         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9111              "CPU PWM1 enabled\n");
9112         if (IS_HASWELL(dev_priv))
9113                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9114                      "CPU PWM2 enabled\n");
9115         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9116              "PCH PWM1 enabled\n");
9117         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9118              "Utility pin enabled\n");
9119         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9120
9121         /*
9122          * In theory we can still leave IRQs enabled, as long as only the HPD
9123          * interrupts remain enabled. We used to check for that, but since it's
9124          * gen-specific and since we only disable LCPLL after we fully disable
9125          * the interrupts, the check below should be enough.
9126          */
9127         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9128 }
9129
9130 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9131 {
9132         if (IS_HASWELL(dev_priv))
9133                 return I915_READ(D_COMP_HSW);
9134         else
9135                 return I915_READ(D_COMP_BDW);
9136 }
9137
9138 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9139 {
9140         if (IS_HASWELL(dev_priv)) {
9141                 mutex_lock(&dev_priv->pcu_lock);
9142                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9143                                             val))
9144                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9145                 mutex_unlock(&dev_priv->pcu_lock);
9146         } else {
9147                 I915_WRITE(D_COMP_BDW, val);
9148                 POSTING_READ(D_COMP_BDW);
9149         }
9150 }
9151
9152 /*
9153  * This function implements pieces of two sequences from BSpec:
9154  * - Sequence for display software to disable LCPLL
9155  * - Sequence for display software to allow package C8+
9156  * The steps implemented here are just the steps that actually touch the LCPLL
9157  * register. Callers should take care of disabling all the display engine
9158  * functions, doing the mode unset, fixing interrupts, etc.
9159  */
9160 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9161                               bool switch_to_fclk, bool allow_power_down)
9162 {
9163         uint32_t val;
9164
9165         assert_can_disable_lcpll(dev_priv);
9166
9167         val = I915_READ(LCPLL_CTL);
9168
9169         if (switch_to_fclk) {
9170                 val |= LCPLL_CD_SOURCE_FCLK;
9171                 I915_WRITE(LCPLL_CTL, val);
9172
9173                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9174                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9175                         DRM_ERROR("Switching to FCLK failed\n");
9176
9177                 val = I915_READ(LCPLL_CTL);
9178         }
9179
9180         val |= LCPLL_PLL_DISABLE;
9181         I915_WRITE(LCPLL_CTL, val);
9182         POSTING_READ(LCPLL_CTL);
9183
9184         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9185                 DRM_ERROR("LCPLL still locked\n");
9186
9187         val = hsw_read_dcomp(dev_priv);
9188         val |= D_COMP_COMP_DISABLE;
9189         hsw_write_dcomp(dev_priv, val);
9190         ndelay(100);
9191
9192         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9193                      1))
9194                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9195
9196         if (allow_power_down) {
9197                 val = I915_READ(LCPLL_CTL);
9198                 val |= LCPLL_POWER_DOWN_ALLOW;
9199                 I915_WRITE(LCPLL_CTL, val);
9200                 POSTING_READ(LCPLL_CTL);
9201         }
9202 }
9203
9204 /*
9205  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9206  * source.
9207  */
9208 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9209 {
9210         uint32_t val;
9211
9212         val = I915_READ(LCPLL_CTL);
9213
9214         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9215                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9216                 return;
9217
9218         /*
9219          * Make sure we're not on PC8 state before disabling PC8, otherwise
9220          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9221          */
9222         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9223
9224         if (val & LCPLL_POWER_DOWN_ALLOW) {
9225                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9226                 I915_WRITE(LCPLL_CTL, val);
9227                 POSTING_READ(LCPLL_CTL);
9228         }
9229
9230         val = hsw_read_dcomp(dev_priv);
9231         val |= D_COMP_COMP_FORCE;
9232         val &= ~D_COMP_COMP_DISABLE;
9233         hsw_write_dcomp(dev_priv, val);
9234
9235         val = I915_READ(LCPLL_CTL);
9236         val &= ~LCPLL_PLL_DISABLE;
9237         I915_WRITE(LCPLL_CTL, val);
9238
9239         if (intel_wait_for_register(dev_priv,
9240                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9241                                     5))
9242                 DRM_ERROR("LCPLL not locked yet\n");
9243
9244         if (val & LCPLL_CD_SOURCE_FCLK) {
9245                 val = I915_READ(LCPLL_CTL);
9246                 val &= ~LCPLL_CD_SOURCE_FCLK;
9247                 I915_WRITE(LCPLL_CTL, val);
9248
9249                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9250                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9251                         DRM_ERROR("Switching back to LCPLL failed\n");
9252         }
9253
9254         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9255
9256         intel_update_cdclk(dev_priv);
9257         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9258 }
9259
9260 /*
9261  * Package states C8 and deeper are really deep PC states that can only be
9262  * reached when all the devices on the system allow it, so even if the graphics
9263  * device allows PC8+, it doesn't mean the system will actually get to these
9264  * states. Our driver only allows PC8+ when going into runtime PM.
9265  *
9266  * The requirements for PC8+ are that all the outputs are disabled, the power
9267  * well is disabled and most interrupts are disabled, and these are also
9268  * requirements for runtime PM. When these conditions are met, we manually do
9269  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9270  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9271  * hang the machine.
9272  *
9273  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9274  * the state of some registers, so when we come back from PC8+ we need to
9275  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9276  * need to take care of the registers kept by RC6. Notice that this happens even
9277  * if we don't put the device in PCI D3 state (which is what currently happens
9278  * because of the runtime PM support).
9279  *
9280  * For more, read "Display Sequences for Package C8" on the hardware
9281  * documentation.
9282  */
9283 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9284 {
9285         uint32_t val;
9286
9287         DRM_DEBUG_KMS("Enabling package C8+\n");
9288
9289         if (HAS_PCH_LPT_LP(dev_priv)) {
9290                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9291                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9292                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9293         }
9294
9295         lpt_disable_clkout_dp(dev_priv);
9296         hsw_disable_lcpll(dev_priv, true, true);
9297 }
9298
9299 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9300 {
9301         uint32_t val;
9302
9303         DRM_DEBUG_KMS("Disabling package C8+\n");
9304
9305         hsw_restore_lcpll(dev_priv);
9306         lpt_init_pch_refclk(dev_priv);
9307
9308         if (HAS_PCH_LPT_LP(dev_priv)) {
9309                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9310                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9311                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9312         }
9313 }
9314
9315 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9316                                       struct intel_crtc_state *crtc_state)
9317 {
9318         struct intel_atomic_state *state =
9319                 to_intel_atomic_state(crtc_state->base.state);
9320
9321         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9322                 struct intel_encoder *encoder =
9323                         intel_get_crtc_new_encoder(state, crtc_state);
9324
9325                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9326                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9327                                       pipe_name(crtc->pipe));
9328                         return -EINVAL;
9329                 }
9330         }
9331
9332         return 0;
9333 }
9334
9335 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9336                                    enum port port,
9337                                    struct intel_crtc_state *pipe_config)
9338 {
9339         enum intel_dpll_id id;
9340         u32 temp;
9341
9342         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9343         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9344
9345         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9346                 return;
9347
9348         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9349 }
9350
9351 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9352                                 enum port port,
9353                                 struct intel_crtc_state *pipe_config)
9354 {
9355         enum intel_dpll_id id;
9356         u32 temp;
9357
9358         /* TODO: TBT pll not implemented. */
9359         if (intel_port_is_combophy(dev_priv, port)) {
9360                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9361                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9362                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9363
9364                 if (WARN_ON(!intel_dpll_is_combophy(id)))
9365                         return;
9366         } else if (intel_port_is_tc(dev_priv, port)) {
9367                 id = icl_port_to_mg_pll_id(port);
9368         } else {
9369                 WARN(1, "Invalid port %x\n", port);
9370                 return;
9371         }
9372
9373         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9374 }
9375
9376 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9377                                 enum port port,
9378                                 struct intel_crtc_state *pipe_config)
9379 {
9380         enum intel_dpll_id id;
9381
9382         switch (port) {
9383         case PORT_A:
9384                 id = DPLL_ID_SKL_DPLL0;
9385                 break;
9386         case PORT_B:
9387                 id = DPLL_ID_SKL_DPLL1;
9388                 break;
9389         case PORT_C:
9390                 id = DPLL_ID_SKL_DPLL2;
9391                 break;
9392         default:
9393                 DRM_ERROR("Incorrect port type\n");
9394                 return;
9395         }
9396
9397         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9398 }
9399
9400 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9401                                 enum port port,
9402                                 struct intel_crtc_state *pipe_config)
9403 {
9404         enum intel_dpll_id id;
9405         u32 temp;
9406
9407         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9408         id = temp >> (port * 3 + 1);
9409
9410         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9411                 return;
9412
9413         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9414 }
9415
9416 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9417                                 enum port port,
9418                                 struct intel_crtc_state *pipe_config)
9419 {
9420         enum intel_dpll_id id;
9421         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9422
9423         switch (ddi_pll_sel) {
9424         case PORT_CLK_SEL_WRPLL1:
9425                 id = DPLL_ID_WRPLL1;
9426                 break;
9427         case PORT_CLK_SEL_WRPLL2:
9428                 id = DPLL_ID_WRPLL2;
9429                 break;
9430         case PORT_CLK_SEL_SPLL:
9431                 id = DPLL_ID_SPLL;
9432                 break;
9433         case PORT_CLK_SEL_LCPLL_810:
9434                 id = DPLL_ID_LCPLL_810;
9435                 break;
9436         case PORT_CLK_SEL_LCPLL_1350:
9437                 id = DPLL_ID_LCPLL_1350;
9438                 break;
9439         case PORT_CLK_SEL_LCPLL_2700:
9440                 id = DPLL_ID_LCPLL_2700;
9441                 break;
9442         default:
9443                 MISSING_CASE(ddi_pll_sel);
9444                 /* fall through */
9445         case PORT_CLK_SEL_NONE:
9446                 return;
9447         }
9448
9449         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9450 }
9451
9452 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9453                                      struct intel_crtc_state *pipe_config,
9454                                      u64 *power_domain_mask)
9455 {
9456         struct drm_device *dev = crtc->base.dev;
9457         struct drm_i915_private *dev_priv = to_i915(dev);
9458         enum intel_display_power_domain power_domain;
9459         u32 tmp;
9460
9461         /*
9462          * The pipe->transcoder mapping is fixed with the exception of the eDP
9463          * transcoder handled below.
9464          */
9465         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9466
9467         /*
9468          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9469          * consistency and less surprising code; it's in always on power).
9470          */
9471         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9472         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9473                 enum pipe trans_edp_pipe;
9474                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9475                 default:
9476                         WARN(1, "unknown pipe linked to edp transcoder\n");
9477                         /* fall through */
9478                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9479                 case TRANS_DDI_EDP_INPUT_A_ON:
9480                         trans_edp_pipe = PIPE_A;
9481                         break;
9482                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9483                         trans_edp_pipe = PIPE_B;
9484                         break;
9485                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9486                         trans_edp_pipe = PIPE_C;
9487                         break;
9488                 }
9489
9490                 if (trans_edp_pipe == crtc->pipe)
9491                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9492         }
9493
9494         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9495         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9496                 return false;
9497         *power_domain_mask |= BIT_ULL(power_domain);
9498
9499         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9500
9501         return tmp & PIPECONF_ENABLE;
9502 }
9503
9504 static bool bxt_get_dsi_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         enum port port;
9512         enum transcoder cpu_transcoder;
9513         u32 tmp;
9514
9515         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9516                 if (port == PORT_A)
9517                         cpu_transcoder = TRANSCODER_DSI_A;
9518                 else
9519                         cpu_transcoder = TRANSCODER_DSI_C;
9520
9521                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9522                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9523                         continue;
9524                 *power_domain_mask |= BIT_ULL(power_domain);
9525
9526                 /*
9527                  * The PLL needs to be enabled with a valid divider
9528                  * configuration, otherwise accessing DSI registers will hang
9529                  * the machine. See BSpec North Display Engine
9530                  * registers/MIPI[BXT]. We can break out here early, since we
9531                  * need the same DSI PLL to be enabled for both DSI ports.
9532                  */
9533                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9534                         break;
9535
9536                 /* XXX: this works for video mode only */
9537                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9538                 if (!(tmp & DPI_ENABLE))
9539                         continue;
9540
9541                 tmp = I915_READ(MIPI_CTRL(port));
9542                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9543                         continue;
9544
9545                 pipe_config->cpu_transcoder = cpu_transcoder;
9546                 break;
9547         }
9548
9549         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9550 }
9551
9552 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9553                                        struct intel_crtc_state *pipe_config)
9554 {
9555         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9556         struct intel_shared_dpll *pll;
9557         enum port port;
9558         uint32_t tmp;
9559
9560         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9561
9562         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9563
9564         if (IS_ICELAKE(dev_priv))
9565                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9566         else if (IS_CANNONLAKE(dev_priv))
9567                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9568         else if (IS_GEN9_BC(dev_priv))
9569                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9570         else if (IS_GEN9_LP(dev_priv))
9571                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9572         else
9573                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9574
9575         pll = pipe_config->shared_dpll;
9576         if (pll) {
9577                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9578                                                 &pipe_config->dpll_hw_state));
9579         }
9580
9581         /*
9582          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9583          * DDI E. So just check whether this pipe is wired to DDI E and whether
9584          * the PCH transcoder is on.
9585          */
9586         if (INTEL_GEN(dev_priv) < 9 &&
9587             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9588                 pipe_config->has_pch_encoder = true;
9589
9590                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9591                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9592                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9593
9594                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9595         }
9596 }
9597
9598 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9599                                     struct intel_crtc_state *pipe_config)
9600 {
9601         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9602         enum intel_display_power_domain power_domain;
9603         u64 power_domain_mask;
9604         bool active;
9605
9606         intel_crtc_init_scalers(crtc, pipe_config);
9607
9608         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9609         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9610                 return false;
9611         power_domain_mask = BIT_ULL(power_domain);
9612
9613         pipe_config->shared_dpll = NULL;
9614
9615         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9616
9617         if (IS_GEN9_LP(dev_priv) &&
9618             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9619                 WARN_ON(active);
9620                 active = true;
9621         }
9622
9623         if (!active)
9624                 goto out;
9625
9626         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9627                 haswell_get_ddi_port_state(crtc, pipe_config);
9628                 intel_get_pipe_timings(crtc, pipe_config);
9629         }
9630
9631         intel_get_pipe_src_size(crtc, pipe_config);
9632         intel_get_crtc_ycbcr_config(crtc, pipe_config);
9633
9634         pipe_config->gamma_mode =
9635                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9636
9637         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9638         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9639                 power_domain_mask |= BIT_ULL(power_domain);
9640                 if (INTEL_GEN(dev_priv) >= 9)
9641                         skylake_get_pfit_config(crtc, pipe_config);
9642                 else
9643                         ironlake_get_pfit_config(crtc, pipe_config);
9644         }
9645
9646         if (hsw_crtc_supports_ips(crtc)) {
9647                 if (IS_HASWELL(dev_priv))
9648                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9649                 else {
9650                         /*
9651                          * We cannot readout IPS state on broadwell, set to
9652                          * true so we can set it to a defined state on first
9653                          * commit.
9654                          */
9655                         pipe_config->ips_enabled = true;
9656                 }
9657         }
9658
9659         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9660             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9661                 pipe_config->pixel_multiplier =
9662                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9663         } else {
9664                 pipe_config->pixel_multiplier = 1;
9665         }
9666
9667 out:
9668         for_each_power_domain(power_domain, power_domain_mask)
9669                 intel_display_power_put(dev_priv, power_domain);
9670
9671         return active;
9672 }
9673
9674 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9675 {
9676         struct drm_i915_private *dev_priv =
9677                 to_i915(plane_state->base.plane->dev);
9678         const struct drm_framebuffer *fb = plane_state->base.fb;
9679         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9680         u32 base;
9681
9682         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9683                 base = obj->phys_handle->busaddr;
9684         else
9685                 base = intel_plane_ggtt_offset(plane_state);
9686
9687         base += plane_state->color_plane[0].offset;
9688
9689         /* ILK+ do this automagically */
9690         if (HAS_GMCH_DISPLAY(dev_priv) &&
9691             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9692                 base += (plane_state->base.crtc_h *
9693                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9694
9695         return base;
9696 }
9697
9698 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9699 {
9700         int x = plane_state->base.crtc_x;
9701         int y = plane_state->base.crtc_y;
9702         u32 pos = 0;
9703
9704         if (x < 0) {
9705                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9706                 x = -x;
9707         }
9708         pos |= x << CURSOR_X_SHIFT;
9709
9710         if (y < 0) {
9711                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9712                 y = -y;
9713         }
9714         pos |= y << CURSOR_Y_SHIFT;
9715
9716         return pos;
9717 }
9718
9719 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9720 {
9721         const struct drm_mode_config *config =
9722                 &plane_state->base.plane->dev->mode_config;
9723         int width = plane_state->base.crtc_w;
9724         int height = plane_state->base.crtc_h;
9725
9726         return width > 0 && width <= config->cursor_width &&
9727                 height > 0 && height <= config->cursor_height;
9728 }
9729
9730 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
9731 {
9732         const struct drm_framebuffer *fb = plane_state->base.fb;
9733         unsigned int rotation = plane_state->base.rotation;
9734         int src_x, src_y;
9735         u32 offset;
9736         int ret;
9737
9738         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
9739         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
9740
9741         ret = intel_plane_check_stride(plane_state);
9742         if (ret)
9743                 return ret;
9744
9745         src_x = plane_state->base.src_x >> 16;
9746         src_y = plane_state->base.src_y >> 16;
9747
9748         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9749         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
9750                                                     plane_state, 0);
9751
9752         if (src_x != 0 || src_y != 0) {
9753                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9754                 return -EINVAL;
9755         }
9756
9757         plane_state->color_plane[0].offset = offset;
9758
9759         return 0;
9760 }
9761
9762 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9763                               struct intel_plane_state *plane_state)
9764 {
9765         const struct drm_framebuffer *fb = plane_state->base.fb;
9766         int ret;
9767
9768         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9769                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9770                 return -EINVAL;
9771         }
9772
9773         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9774                                                   &crtc_state->base,
9775                                                   DRM_PLANE_HELPER_NO_SCALING,
9776                                                   DRM_PLANE_HELPER_NO_SCALING,
9777                                                   true, true);
9778         if (ret)
9779                 return ret;
9780
9781         if (!plane_state->base.visible)
9782                 return 0;
9783
9784         ret = intel_plane_check_src_coordinates(plane_state);
9785         if (ret)
9786                 return ret;
9787
9788         ret = intel_cursor_check_surface(plane_state);
9789         if (ret)
9790                 return ret;
9791
9792         return 0;
9793 }
9794
9795 static unsigned int
9796 i845_cursor_max_stride(struct intel_plane *plane,
9797                        u32 pixel_format, u64 modifier,
9798                        unsigned int rotation)
9799 {
9800         return 2048;
9801 }
9802
9803 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9804                            const struct intel_plane_state *plane_state)
9805 {
9806         return CURSOR_ENABLE |
9807                 CURSOR_GAMMA_ENABLE |
9808                 CURSOR_FORMAT_ARGB |
9809                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
9810 }
9811
9812 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9813 {
9814         int width = plane_state->base.crtc_w;
9815
9816         /*
9817          * 845g/865g are only limited by the width of their cursors,
9818          * the height is arbitrary up to the precision of the register.
9819          */
9820         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9821 }
9822
9823 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
9824                              struct intel_plane_state *plane_state)
9825 {
9826         const struct drm_framebuffer *fb = plane_state->base.fb;
9827         int ret;
9828
9829         ret = intel_check_cursor(crtc_state, plane_state);
9830         if (ret)
9831                 return ret;
9832
9833         /* if we want to turn off the cursor ignore width and height */
9834         if (!fb)
9835                 return 0;
9836
9837         /* Check for which cursor types we support */
9838         if (!i845_cursor_size_ok(plane_state)) {
9839                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9840                           plane_state->base.crtc_w,
9841                           plane_state->base.crtc_h);
9842                 return -EINVAL;
9843         }
9844
9845         WARN_ON(plane_state->base.visible &&
9846                 plane_state->color_plane[0].stride != fb->pitches[0]);
9847
9848         switch (fb->pitches[0]) {
9849         case 256:
9850         case 512:
9851         case 1024:
9852         case 2048:
9853                 break;
9854         default:
9855                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9856                               fb->pitches[0]);
9857                 return -EINVAL;
9858         }
9859
9860         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9861
9862         return 0;
9863 }
9864
9865 static void i845_update_cursor(struct intel_plane *plane,
9866                                const struct intel_crtc_state *crtc_state,
9867                                const struct intel_plane_state *plane_state)
9868 {
9869         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9870         u32 cntl = 0, base = 0, pos = 0, size = 0;
9871         unsigned long irqflags;
9872
9873         if (plane_state && plane_state->base.visible) {
9874                 unsigned int width = plane_state->base.crtc_w;
9875                 unsigned int height = plane_state->base.crtc_h;
9876
9877                 cntl = plane_state->ctl;
9878                 size = (height << 12) | width;
9879
9880                 base = intel_cursor_base(plane_state);
9881                 pos = intel_cursor_position(plane_state);
9882         }
9883
9884         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9885
9886         /* On these chipsets we can only modify the base/size/stride
9887          * whilst the cursor is disabled.
9888          */
9889         if (plane->cursor.base != base ||
9890             plane->cursor.size != size ||
9891             plane->cursor.cntl != cntl) {
9892                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9893                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9894                 I915_WRITE_FW(CURSIZE, size);
9895                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9896                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9897
9898                 plane->cursor.base = base;
9899                 plane->cursor.size = size;
9900                 plane->cursor.cntl = cntl;
9901         } else {
9902                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9903         }
9904
9905         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9906 }
9907
9908 static void i845_disable_cursor(struct intel_plane *plane,
9909                                 const struct intel_crtc_state *crtc_state)
9910 {
9911         i845_update_cursor(plane, crtc_state, NULL);
9912 }
9913
9914 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
9915                                      enum pipe *pipe)
9916 {
9917         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9918         enum intel_display_power_domain power_domain;
9919         bool ret;
9920
9921         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9922         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9923                 return false;
9924
9925         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9926
9927         *pipe = PIPE_A;
9928
9929         intel_display_power_put(dev_priv, power_domain);
9930
9931         return ret;
9932 }
9933
9934 static unsigned int
9935 i9xx_cursor_max_stride(struct intel_plane *plane,
9936                        u32 pixel_format, u64 modifier,
9937                        unsigned int rotation)
9938 {
9939         return plane->base.dev->mode_config.cursor_width * 4;
9940 }
9941
9942 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9943                            const struct intel_plane_state *plane_state)
9944 {
9945         struct drm_i915_private *dev_priv =
9946                 to_i915(plane_state->base.plane->dev);
9947         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9948         u32 cntl = 0;
9949
9950         if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
9951                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
9952
9953         if (INTEL_GEN(dev_priv) <= 10) {
9954                 cntl |= MCURSOR_GAMMA_ENABLE;
9955
9956                 if (HAS_DDI(dev_priv))
9957                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
9958         }
9959
9960         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9961                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9962
9963         switch (plane_state->base.crtc_w) {
9964         case 64:
9965                 cntl |= MCURSOR_MODE_64_ARGB_AX;
9966                 break;
9967         case 128:
9968                 cntl |= MCURSOR_MODE_128_ARGB_AX;
9969                 break;
9970         case 256:
9971                 cntl |= MCURSOR_MODE_256_ARGB_AX;
9972                 break;
9973         default:
9974                 MISSING_CASE(plane_state->base.crtc_w);
9975                 return 0;
9976         }
9977
9978         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9979                 cntl |= MCURSOR_ROTATE_180;
9980
9981         return cntl;
9982 }
9983
9984 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9985 {
9986         struct drm_i915_private *dev_priv =
9987                 to_i915(plane_state->base.plane->dev);
9988         int width = plane_state->base.crtc_w;
9989         int height = plane_state->base.crtc_h;
9990
9991         if (!intel_cursor_size_ok(plane_state))
9992                 return false;
9993
9994         /* Cursor width is limited to a few power-of-two sizes */
9995         switch (width) {
9996         case 256:
9997         case 128:
9998         case 64:
9999                 break;
10000         default:
10001                 return false;
10002         }
10003
10004         /*
10005          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10006          * height from 8 lines up to the cursor width, when the
10007          * cursor is not rotated. Everything else requires square
10008          * cursors.
10009          */
10010         if (HAS_CUR_FBC(dev_priv) &&
10011             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10012                 if (height < 8 || height > width)
10013                         return false;
10014         } else {
10015                 if (height != width)
10016                         return false;
10017         }
10018
10019         return true;
10020 }
10021
10022 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10023                              struct intel_plane_state *plane_state)
10024 {
10025         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10026         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10027         const struct drm_framebuffer *fb = plane_state->base.fb;
10028         enum pipe pipe = plane->pipe;
10029         int ret;
10030
10031         ret = intel_check_cursor(crtc_state, plane_state);
10032         if (ret)
10033                 return ret;
10034
10035         /* if we want to turn off the cursor ignore width and height */
10036         if (!fb)
10037                 return 0;
10038
10039         /* Check for which cursor types we support */
10040         if (!i9xx_cursor_size_ok(plane_state)) {
10041                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10042                           plane_state->base.crtc_w,
10043                           plane_state->base.crtc_h);
10044                 return -EINVAL;
10045         }
10046
10047         WARN_ON(plane_state->base.visible &&
10048                 plane_state->color_plane[0].stride != fb->pitches[0]);
10049
10050         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10051                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10052                               fb->pitches[0], plane_state->base.crtc_w);
10053                 return -EINVAL;
10054         }
10055
10056         /*
10057          * There's something wrong with the cursor on CHV pipe C.
10058          * If it straddles the left edge of the screen then
10059          * moving it away from the edge or disabling it often
10060          * results in a pipe underrun, and often that can lead to
10061          * dead pipe (constant underrun reported, and it scans
10062          * out just a solid color). To recover from that, the
10063          * display power well must be turned off and on again.
10064          * Refuse the put the cursor into that compromised position.
10065          */
10066         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10067             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10068                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10069                 return -EINVAL;
10070         }
10071
10072         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10073
10074         return 0;
10075 }
10076
10077 static void i9xx_update_cursor(struct intel_plane *plane,
10078                                const struct intel_crtc_state *crtc_state,
10079                                const struct intel_plane_state *plane_state)
10080 {
10081         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10082         enum pipe pipe = plane->pipe;
10083         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10084         unsigned long irqflags;
10085
10086         if (plane_state && plane_state->base.visible) {
10087                 cntl = plane_state->ctl;
10088
10089                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10090                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10091
10092                 base = intel_cursor_base(plane_state);
10093                 pos = intel_cursor_position(plane_state);
10094         }
10095
10096         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10097
10098         /*
10099          * On some platforms writing CURCNTR first will also
10100          * cause CURPOS to be armed by the CURBASE write.
10101          * Without the CURCNTR write the CURPOS write would
10102          * arm itself. Thus we always update CURCNTR before
10103          * CURPOS.
10104          *
10105          * On other platforms CURPOS always requires the
10106          * CURBASE write to arm the update. Additonally
10107          * a write to any of the cursor register will cancel
10108          * an already armed cursor update. Thus leaving out
10109          * the CURBASE write after CURPOS could lead to a
10110          * cursor that doesn't appear to move, or even change
10111          * shape. Thus we always write CURBASE.
10112          *
10113          * The other registers are armed by by the CURBASE write
10114          * except when the plane is getting enabled at which time
10115          * the CURCNTR write arms the update.
10116          */
10117         if (plane->cursor.base != base ||
10118             plane->cursor.size != fbc_ctl ||
10119             plane->cursor.cntl != cntl) {
10120                 if (HAS_CUR_FBC(dev_priv))
10121                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10122                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10123                 I915_WRITE_FW(CURPOS(pipe), pos);
10124                 I915_WRITE_FW(CURBASE(pipe), base);
10125
10126                 plane->cursor.base = base;
10127                 plane->cursor.size = fbc_ctl;
10128                 plane->cursor.cntl = cntl;
10129         } else {
10130                 I915_WRITE_FW(CURPOS(pipe), pos);
10131                 I915_WRITE_FW(CURBASE(pipe), base);
10132         }
10133
10134         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10135 }
10136
10137 static void i9xx_disable_cursor(struct intel_plane *plane,
10138                                 const struct intel_crtc_state *crtc_state)
10139 {
10140         i9xx_update_cursor(plane, crtc_state, NULL);
10141 }
10142
10143 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10144                                      enum pipe *pipe)
10145 {
10146         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10147         enum intel_display_power_domain power_domain;
10148         bool ret;
10149         u32 val;
10150
10151         /*
10152          * Not 100% correct for planes that can move between pipes,
10153          * but that's only the case for gen2-3 which don't have any
10154          * display power wells.
10155          */
10156         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10157         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10158                 return false;
10159
10160         val = I915_READ(CURCNTR(plane->pipe));
10161
10162         ret = val & MCURSOR_MODE;
10163
10164         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10165                 *pipe = plane->pipe;
10166         else
10167                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10168                         MCURSOR_PIPE_SELECT_SHIFT;
10169
10170         intel_display_power_put(dev_priv, power_domain);
10171
10172         return ret;
10173 }
10174
10175 /* VESA 640x480x72Hz mode to set on the pipe */
10176 static const struct drm_display_mode load_detect_mode = {
10177         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10178                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10179 };
10180
10181 struct drm_framebuffer *
10182 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10183                          struct drm_mode_fb_cmd2 *mode_cmd)
10184 {
10185         struct intel_framebuffer *intel_fb;
10186         int ret;
10187
10188         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10189         if (!intel_fb)
10190                 return ERR_PTR(-ENOMEM);
10191
10192         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10193         if (ret)
10194                 goto err;
10195
10196         return &intel_fb->base;
10197
10198 err:
10199         kfree(intel_fb);
10200         return ERR_PTR(ret);
10201 }
10202
10203 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10204                                         struct drm_crtc *crtc)
10205 {
10206         struct drm_plane *plane;
10207         struct drm_plane_state *plane_state;
10208         int ret, i;
10209
10210         ret = drm_atomic_add_affected_planes(state, crtc);
10211         if (ret)
10212                 return ret;
10213
10214         for_each_new_plane_in_state(state, plane, plane_state, i) {
10215                 if (plane_state->crtc != crtc)
10216                         continue;
10217
10218                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10219                 if (ret)
10220                         return ret;
10221
10222                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10223         }
10224
10225         return 0;
10226 }
10227
10228 int intel_get_load_detect_pipe(struct drm_connector *connector,
10229                                const struct drm_display_mode *mode,
10230                                struct intel_load_detect_pipe *old,
10231                                struct drm_modeset_acquire_ctx *ctx)
10232 {
10233         struct intel_crtc *intel_crtc;
10234         struct intel_encoder *intel_encoder =
10235                 intel_attached_encoder(connector);
10236         struct drm_crtc *possible_crtc;
10237         struct drm_encoder *encoder = &intel_encoder->base;
10238         struct drm_crtc *crtc = NULL;
10239         struct drm_device *dev = encoder->dev;
10240         struct drm_i915_private *dev_priv = to_i915(dev);
10241         struct drm_mode_config *config = &dev->mode_config;
10242         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10243         struct drm_connector_state *connector_state;
10244         struct intel_crtc_state *crtc_state;
10245         int ret, i = -1;
10246
10247         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10248                       connector->base.id, connector->name,
10249                       encoder->base.id, encoder->name);
10250
10251         old->restore_state = NULL;
10252
10253         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10254
10255         /*
10256          * Algorithm gets a little messy:
10257          *
10258          *   - if the connector already has an assigned crtc, use it (but make
10259          *     sure it's on first)
10260          *
10261          *   - try to find the first unused crtc that can drive this connector,
10262          *     and use that if we find one
10263          */
10264
10265         /* See if we already have a CRTC for this connector */
10266         if (connector->state->crtc) {
10267                 crtc = connector->state->crtc;
10268
10269                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10270                 if (ret)
10271                         goto fail;
10272
10273                 /* Make sure the crtc and connector are running */
10274                 goto found;
10275         }
10276
10277         /* Find an unused one (if possible) */
10278         for_each_crtc(dev, possible_crtc) {
10279                 i++;
10280                 if (!(encoder->possible_crtcs & (1 << i)))
10281                         continue;
10282
10283                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10284                 if (ret)
10285                         goto fail;
10286
10287                 if (possible_crtc->state->enable) {
10288                         drm_modeset_unlock(&possible_crtc->mutex);
10289                         continue;
10290                 }
10291
10292                 crtc = possible_crtc;
10293                 break;
10294         }
10295
10296         /*
10297          * If we didn't find an unused CRTC, don't use any.
10298          */
10299         if (!crtc) {
10300                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10301                 ret = -ENODEV;
10302                 goto fail;
10303         }
10304
10305 found:
10306         intel_crtc = to_intel_crtc(crtc);
10307
10308         state = drm_atomic_state_alloc(dev);
10309         restore_state = drm_atomic_state_alloc(dev);
10310         if (!state || !restore_state) {
10311                 ret = -ENOMEM;
10312                 goto fail;
10313         }
10314
10315         state->acquire_ctx = ctx;
10316         restore_state->acquire_ctx = ctx;
10317
10318         connector_state = drm_atomic_get_connector_state(state, connector);
10319         if (IS_ERR(connector_state)) {
10320                 ret = PTR_ERR(connector_state);
10321                 goto fail;
10322         }
10323
10324         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10325         if (ret)
10326                 goto fail;
10327
10328         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10329         if (IS_ERR(crtc_state)) {
10330                 ret = PTR_ERR(crtc_state);
10331                 goto fail;
10332         }
10333
10334         crtc_state->base.active = crtc_state->base.enable = true;
10335
10336         if (!mode)
10337                 mode = &load_detect_mode;
10338
10339         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10340         if (ret)
10341                 goto fail;
10342
10343         ret = intel_modeset_disable_planes(state, crtc);
10344         if (ret)
10345                 goto fail;
10346
10347         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10348         if (!ret)
10349                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10350         if (!ret)
10351                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10352         if (ret) {
10353                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10354                 goto fail;
10355         }
10356
10357         ret = drm_atomic_commit(state);
10358         if (ret) {
10359                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10360                 goto fail;
10361         }
10362
10363         old->restore_state = restore_state;
10364         drm_atomic_state_put(state);
10365
10366         /* let the connector get through one full cycle before testing */
10367         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10368         return true;
10369
10370 fail:
10371         if (state) {
10372                 drm_atomic_state_put(state);
10373                 state = NULL;
10374         }
10375         if (restore_state) {
10376                 drm_atomic_state_put(restore_state);
10377                 restore_state = NULL;
10378         }
10379
10380         if (ret == -EDEADLK)
10381                 return ret;
10382
10383         return false;
10384 }
10385
10386 void intel_release_load_detect_pipe(struct drm_connector *connector,
10387                                     struct intel_load_detect_pipe *old,
10388                                     struct drm_modeset_acquire_ctx *ctx)
10389 {
10390         struct intel_encoder *intel_encoder =
10391                 intel_attached_encoder(connector);
10392         struct drm_encoder *encoder = &intel_encoder->base;
10393         struct drm_atomic_state *state = old->restore_state;
10394         int ret;
10395
10396         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10397                       connector->base.id, connector->name,
10398                       encoder->base.id, encoder->name);
10399
10400         if (!state)
10401                 return;
10402
10403         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10404         if (ret)
10405                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10406         drm_atomic_state_put(state);
10407 }
10408
10409 static int i9xx_pll_refclk(struct drm_device *dev,
10410                            const struct intel_crtc_state *pipe_config)
10411 {
10412         struct drm_i915_private *dev_priv = to_i915(dev);
10413         u32 dpll = pipe_config->dpll_hw_state.dpll;
10414
10415         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10416                 return dev_priv->vbt.lvds_ssc_freq;
10417         else if (HAS_PCH_SPLIT(dev_priv))
10418                 return 120000;
10419         else if (!IS_GEN2(dev_priv))
10420                 return 96000;
10421         else
10422                 return 48000;
10423 }
10424
10425 /* Returns the clock of the currently programmed mode of the given pipe. */
10426 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10427                                 struct intel_crtc_state *pipe_config)
10428 {
10429         struct drm_device *dev = crtc->base.dev;
10430         struct drm_i915_private *dev_priv = to_i915(dev);
10431         int pipe = pipe_config->cpu_transcoder;
10432         u32 dpll = pipe_config->dpll_hw_state.dpll;
10433         u32 fp;
10434         struct dpll clock;
10435         int port_clock;
10436         int refclk = i9xx_pll_refclk(dev, pipe_config);
10437
10438         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10439                 fp = pipe_config->dpll_hw_state.fp0;
10440         else
10441                 fp = pipe_config->dpll_hw_state.fp1;
10442
10443         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10444         if (IS_PINEVIEW(dev_priv)) {
10445                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10446                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10447         } else {
10448                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10449                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10450         }
10451
10452         if (!IS_GEN2(dev_priv)) {
10453                 if (IS_PINEVIEW(dev_priv))
10454                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10455                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10456                 else
10457                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10458                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10459
10460                 switch (dpll & DPLL_MODE_MASK) {
10461                 case DPLLB_MODE_DAC_SERIAL:
10462                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10463                                 5 : 10;
10464                         break;
10465                 case DPLLB_MODE_LVDS:
10466                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10467                                 7 : 14;
10468                         break;
10469                 default:
10470                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10471                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10472                         return;
10473                 }
10474
10475                 if (IS_PINEVIEW(dev_priv))
10476                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10477                 else
10478                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10479         } else {
10480                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10481                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10482
10483                 if (is_lvds) {
10484                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10485                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10486
10487                         if (lvds & LVDS_CLKB_POWER_UP)
10488                                 clock.p2 = 7;
10489                         else
10490                                 clock.p2 = 14;
10491                 } else {
10492                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10493                                 clock.p1 = 2;
10494                         else {
10495                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10496                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10497                         }
10498                         if (dpll & PLL_P2_DIVIDE_BY_4)
10499                                 clock.p2 = 4;
10500                         else
10501                                 clock.p2 = 2;
10502                 }
10503
10504                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10505         }
10506
10507         /*
10508          * This value includes pixel_multiplier. We will use
10509          * port_clock to compute adjusted_mode.crtc_clock in the
10510          * encoder's get_config() function.
10511          */
10512         pipe_config->port_clock = port_clock;
10513 }
10514
10515 int intel_dotclock_calculate(int link_freq,
10516                              const struct intel_link_m_n *m_n)
10517 {
10518         /*
10519          * The calculation for the data clock is:
10520          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10521          * But we want to avoid losing precison if possible, so:
10522          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10523          *
10524          * and the link clock is simpler:
10525          * link_clock = (m * link_clock) / n
10526          */
10527
10528         if (!m_n->link_n)
10529                 return 0;
10530
10531         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10532 }
10533
10534 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10535                                    struct intel_crtc_state *pipe_config)
10536 {
10537         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10538
10539         /* read out port_clock from the DPLL */
10540         i9xx_crtc_clock_get(crtc, pipe_config);
10541
10542         /*
10543          * In case there is an active pipe without active ports,
10544          * we may need some idea for the dotclock anyway.
10545          * Calculate one based on the FDI configuration.
10546          */
10547         pipe_config->base.adjusted_mode.crtc_clock =
10548                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10549                                          &pipe_config->fdi_m_n);
10550 }
10551
10552 /* Returns the currently programmed mode of the given encoder. */
10553 struct drm_display_mode *
10554 intel_encoder_current_mode(struct intel_encoder *encoder)
10555 {
10556         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10557         struct intel_crtc_state *crtc_state;
10558         struct drm_display_mode *mode;
10559         struct intel_crtc *crtc;
10560         enum pipe pipe;
10561
10562         if (!encoder->get_hw_state(encoder, &pipe))
10563                 return NULL;
10564
10565         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10566
10567         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10568         if (!mode)
10569                 return NULL;
10570
10571         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10572         if (!crtc_state) {
10573                 kfree(mode);
10574                 return NULL;
10575         }
10576
10577         crtc_state->base.crtc = &crtc->base;
10578
10579         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10580                 kfree(crtc_state);
10581                 kfree(mode);
10582                 return NULL;
10583         }
10584
10585         encoder->get_config(encoder, crtc_state);
10586
10587         intel_mode_from_pipe_config(mode, crtc_state);
10588
10589         kfree(crtc_state);
10590
10591         return mode;
10592 }
10593
10594 static void intel_crtc_destroy(struct drm_crtc *crtc)
10595 {
10596         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10597
10598         drm_crtc_cleanup(crtc);
10599         kfree(intel_crtc);
10600 }
10601
10602 /**
10603  * intel_wm_need_update - Check whether watermarks need updating
10604  * @plane: drm plane
10605  * @state: new plane state
10606  *
10607  * Check current plane state versus the new one to determine whether
10608  * watermarks need to be recalculated.
10609  *
10610  * Returns true or false.
10611  */
10612 static bool intel_wm_need_update(struct drm_plane *plane,
10613                                  struct drm_plane_state *state)
10614 {
10615         struct intel_plane_state *new = to_intel_plane_state(state);
10616         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10617
10618         /* Update watermarks on tiling or size changes. */
10619         if (new->base.visible != cur->base.visible)
10620                 return true;
10621
10622         if (!cur->base.fb || !new->base.fb)
10623                 return false;
10624
10625         if (cur->base.fb->modifier != new->base.fb->modifier ||
10626             cur->base.rotation != new->base.rotation ||
10627             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10628             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10629             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10630             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10631                 return true;
10632
10633         return false;
10634 }
10635
10636 static bool needs_scaling(const struct intel_plane_state *state)
10637 {
10638         int src_w = drm_rect_width(&state->base.src) >> 16;
10639         int src_h = drm_rect_height(&state->base.src) >> 16;
10640         int dst_w = drm_rect_width(&state->base.dst);
10641         int dst_h = drm_rect_height(&state->base.dst);
10642
10643         return (src_w != dst_w || src_h != dst_h);
10644 }
10645
10646 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10647                                     struct drm_crtc_state *crtc_state,
10648                                     const struct intel_plane_state *old_plane_state,
10649                                     struct drm_plane_state *plane_state)
10650 {
10651         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10652         struct drm_crtc *crtc = crtc_state->crtc;
10653         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10654         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10655         struct drm_device *dev = crtc->dev;
10656         struct drm_i915_private *dev_priv = to_i915(dev);
10657         bool mode_changed = needs_modeset(crtc_state);
10658         bool was_crtc_enabled = old_crtc_state->base.active;
10659         bool is_crtc_enabled = crtc_state->active;
10660         bool turn_off, turn_on, visible, was_visible;
10661         struct drm_framebuffer *fb = plane_state->fb;
10662         int ret;
10663
10664         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10665                 ret = skl_update_scaler_plane(
10666                         to_intel_crtc_state(crtc_state),
10667                         to_intel_plane_state(plane_state));
10668                 if (ret)
10669                         return ret;
10670         }
10671
10672         was_visible = old_plane_state->base.visible;
10673         visible = plane_state->visible;
10674
10675         if (!was_crtc_enabled && WARN_ON(was_visible))
10676                 was_visible = false;
10677
10678         /*
10679          * Visibility is calculated as if the crtc was on, but
10680          * after scaler setup everything depends on it being off
10681          * when the crtc isn't active.
10682          *
10683          * FIXME this is wrong for watermarks. Watermarks should also
10684          * be computed as if the pipe would be active. Perhaps move
10685          * per-plane wm computation to the .check_plane() hook, and
10686          * only combine the results from all planes in the current place?
10687          */
10688         if (!is_crtc_enabled) {
10689                 plane_state->visible = visible = false;
10690                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10691         }
10692
10693         if (!was_visible && !visible)
10694                 return 0;
10695
10696         if (fb != old_plane_state->base.fb)
10697                 pipe_config->fb_changed = true;
10698
10699         turn_off = was_visible && (!visible || mode_changed);
10700         turn_on = visible && (!was_visible || mode_changed);
10701
10702         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10703                          intel_crtc->base.base.id, intel_crtc->base.name,
10704                          plane->base.base.id, plane->base.name,
10705                          fb ? fb->base.id : -1);
10706
10707         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10708                          plane->base.base.id, plane->base.name,
10709                          was_visible, visible,
10710                          turn_off, turn_on, mode_changed);
10711
10712         if (turn_on) {
10713                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10714                         pipe_config->update_wm_pre = true;
10715
10716                 /* must disable cxsr around plane enable/disable */
10717                 if (plane->id != PLANE_CURSOR)
10718                         pipe_config->disable_cxsr = true;
10719         } else if (turn_off) {
10720                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10721                         pipe_config->update_wm_post = true;
10722
10723                 /* must disable cxsr around plane enable/disable */
10724                 if (plane->id != PLANE_CURSOR)
10725                         pipe_config->disable_cxsr = true;
10726         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10727                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10728                         /* FIXME bollocks */
10729                         pipe_config->update_wm_pre = true;
10730                         pipe_config->update_wm_post = true;
10731                 }
10732         }
10733
10734         if (visible || was_visible)
10735                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10736
10737         /*
10738          * ILK/SNB DVSACNTR/Sprite Enable
10739          * IVB SPR_CTL/Sprite Enable
10740          * "When in Self Refresh Big FIFO mode, a write to enable the
10741          *  plane will be internally buffered and delayed while Big FIFO
10742          *  mode is exiting."
10743          *
10744          * Which means that enabling the sprite can take an extra frame
10745          * when we start in big FIFO mode (LP1+). Thus we need to drop
10746          * down to LP0 and wait for vblank in order to make sure the
10747          * sprite gets enabled on the next vblank after the register write.
10748          * Doing otherwise would risk enabling the sprite one frame after
10749          * we've already signalled flip completion. We can resume LP1+
10750          * once the sprite has been enabled.
10751          *
10752          *
10753          * WaCxSRDisabledForSpriteScaling:ivb
10754          * IVB SPR_SCALE/Scaling Enable
10755          * "Low Power watermarks must be disabled for at least one
10756          *  frame before enabling sprite scaling, and kept disabled
10757          *  until sprite scaling is disabled."
10758          *
10759          * ILK/SNB DVSASCALE/Scaling Enable
10760          * "When in Self Refresh Big FIFO mode, scaling enable will be
10761          *  masked off while Big FIFO mode is exiting."
10762          *
10763          * Despite the w/a only being listed for IVB we assume that
10764          * the ILK/SNB note has similar ramifications, hence we apply
10765          * the w/a on all three platforms.
10766          */
10767         if (plane->id == PLANE_SPRITE0 &&
10768             (IS_GEN5(dev_priv) || IS_GEN6(dev_priv) ||
10769              IS_IVYBRIDGE(dev_priv)) &&
10770             (turn_on || (!needs_scaling(old_plane_state) &&
10771                          needs_scaling(to_intel_plane_state(plane_state)))))
10772                 pipe_config->disable_lp_wm = true;
10773
10774         return 0;
10775 }
10776
10777 static bool encoders_cloneable(const struct intel_encoder *a,
10778                                const struct intel_encoder *b)
10779 {
10780         /* masks could be asymmetric, so check both ways */
10781         return a == b || (a->cloneable & (1 << b->type) &&
10782                           b->cloneable & (1 << a->type));
10783 }
10784
10785 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10786                                          struct intel_crtc *crtc,
10787                                          struct intel_encoder *encoder)
10788 {
10789         struct intel_encoder *source_encoder;
10790         struct drm_connector *connector;
10791         struct drm_connector_state *connector_state;
10792         int i;
10793
10794         for_each_new_connector_in_state(state, connector, connector_state, i) {
10795                 if (connector_state->crtc != &crtc->base)
10796                         continue;
10797
10798                 source_encoder =
10799                         to_intel_encoder(connector_state->best_encoder);
10800                 if (!encoders_cloneable(encoder, source_encoder))
10801                         return false;
10802         }
10803
10804         return true;
10805 }
10806
10807 static int icl_add_linked_planes(struct intel_atomic_state *state)
10808 {
10809         struct intel_plane *plane, *linked;
10810         struct intel_plane_state *plane_state, *linked_plane_state;
10811         int i;
10812
10813         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10814                 linked = plane_state->linked_plane;
10815
10816                 if (!linked)
10817                         continue;
10818
10819                 linked_plane_state = intel_atomic_get_plane_state(state, linked);
10820                 if (IS_ERR(linked_plane_state))
10821                         return PTR_ERR(linked_plane_state);
10822
10823                 WARN_ON(linked_plane_state->linked_plane != plane);
10824                 WARN_ON(linked_plane_state->slave == plane_state->slave);
10825         }
10826
10827         return 0;
10828 }
10829
10830 static int icl_check_nv12_planes(struct intel_crtc_state *crtc_state)
10831 {
10832         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10833         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10834         struct intel_atomic_state *state = to_intel_atomic_state(crtc_state->base.state);
10835         struct intel_plane *plane, *linked;
10836         struct intel_plane_state *plane_state;
10837         int i;
10838
10839         if (INTEL_GEN(dev_priv) < 11)
10840                 return 0;
10841
10842         /*
10843          * Destroy all old plane links and make the slave plane invisible
10844          * in the crtc_state->active_planes mask.
10845          */
10846         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10847                 if (plane->pipe != crtc->pipe || !plane_state->linked_plane)
10848                         continue;
10849
10850                 plane_state->linked_plane = NULL;
10851                 if (plane_state->slave && !plane_state->base.visible) {
10852                         crtc_state->active_planes &= ~BIT(plane->id);
10853                         crtc_state->update_planes |= BIT(plane->id);
10854                 }
10855
10856                 plane_state->slave = false;
10857         }
10858
10859         if (!crtc_state->nv12_planes)
10860                 return 0;
10861
10862         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10863                 struct intel_plane_state *linked_state = NULL;
10864
10865                 if (plane->pipe != crtc->pipe ||
10866                     !(crtc_state->nv12_planes & BIT(plane->id)))
10867                         continue;
10868
10869                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, linked) {
10870                         if (!icl_is_nv12_y_plane(linked->id))
10871                                 continue;
10872
10873                         if (crtc_state->active_planes & BIT(linked->id))
10874                                 continue;
10875
10876                         linked_state = intel_atomic_get_plane_state(state, linked);
10877                         if (IS_ERR(linked_state))
10878                                 return PTR_ERR(linked_state);
10879
10880                         break;
10881                 }
10882
10883                 if (!linked_state) {
10884                         DRM_DEBUG_KMS("Need %d free Y planes for NV12\n",
10885                                       hweight8(crtc_state->nv12_planes));
10886
10887                         return -EINVAL;
10888                 }
10889
10890                 plane_state->linked_plane = linked;
10891
10892                 linked_state->slave = true;
10893                 linked_state->linked_plane = plane;
10894                 crtc_state->active_planes |= BIT(linked->id);
10895                 crtc_state->update_planes |= BIT(linked->id);
10896                 DRM_DEBUG_KMS("Using %s as Y plane for %s\n", linked->base.name, plane->base.name);
10897         }
10898
10899         return 0;
10900 }
10901
10902 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10903                                    struct drm_crtc_state *crtc_state)
10904 {
10905         struct drm_device *dev = crtc->dev;
10906         struct drm_i915_private *dev_priv = to_i915(dev);
10907         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10908         struct intel_crtc_state *pipe_config =
10909                 to_intel_crtc_state(crtc_state);
10910         int ret;
10911         bool mode_changed = needs_modeset(crtc_state);
10912
10913         if (mode_changed && !crtc_state->active)
10914                 pipe_config->update_wm_post = true;
10915
10916         if (mode_changed && crtc_state->enable &&
10917             dev_priv->display.crtc_compute_clock &&
10918             !WARN_ON(pipe_config->shared_dpll)) {
10919                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10920                                                            pipe_config);
10921                 if (ret)
10922                         return ret;
10923         }
10924
10925         if (crtc_state->color_mgmt_changed) {
10926                 ret = intel_color_check(crtc, crtc_state);
10927                 if (ret)
10928                         return ret;
10929
10930                 /*
10931                  * Changing color management on Intel hardware is
10932                  * handled as part of planes update.
10933                  */
10934                 crtc_state->planes_changed = true;
10935         }
10936
10937         ret = 0;
10938         if (dev_priv->display.compute_pipe_wm) {
10939                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10940                 if (ret) {
10941                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10942                         return ret;
10943                 }
10944         }
10945
10946         if (dev_priv->display.compute_intermediate_wm) {
10947                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10948                         return 0;
10949
10950                 /*
10951                  * Calculate 'intermediate' watermarks that satisfy both the
10952                  * old state and the new state.  We can program these
10953                  * immediately.
10954                  */
10955                 ret = dev_priv->display.compute_intermediate_wm(dev,
10956                                                                 intel_crtc,
10957                                                                 pipe_config);
10958                 if (ret) {
10959                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10960                         return ret;
10961                 }
10962         }
10963
10964         if (INTEL_GEN(dev_priv) >= 9) {
10965                 if (mode_changed)
10966                         ret = skl_update_scaler_crtc(pipe_config);
10967
10968                 if (!ret)
10969                         ret = icl_check_nv12_planes(pipe_config);
10970                 if (!ret)
10971                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10972                                                             pipe_config);
10973                 if (!ret)
10974                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10975                                                          pipe_config);
10976         }
10977
10978         if (HAS_IPS(dev_priv))
10979                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10980
10981         return ret;
10982 }
10983
10984 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10985         .atomic_check = intel_crtc_atomic_check,
10986 };
10987
10988 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10989 {
10990         struct intel_connector *connector;
10991         struct drm_connector_list_iter conn_iter;
10992
10993         drm_connector_list_iter_begin(dev, &conn_iter);
10994         for_each_intel_connector_iter(connector, &conn_iter) {
10995                 if (connector->base.state->crtc)
10996                         drm_connector_put(&connector->base);
10997
10998                 if (connector->base.encoder) {
10999                         connector->base.state->best_encoder =
11000                                 connector->base.encoder;
11001                         connector->base.state->crtc =
11002                                 connector->base.encoder->crtc;
11003
11004                         drm_connector_get(&connector->base);
11005                 } else {
11006                         connector->base.state->best_encoder = NULL;
11007                         connector->base.state->crtc = NULL;
11008                 }
11009         }
11010         drm_connector_list_iter_end(&conn_iter);
11011 }
11012
11013 static int
11014 compute_sink_pipe_bpp(const struct drm_connector_state *conn_state,
11015                       struct intel_crtc_state *pipe_config)
11016 {
11017         struct drm_connector *connector = conn_state->connector;
11018         const struct drm_display_info *info = &connector->display_info;
11019         int bpp;
11020
11021         switch (conn_state->max_bpc) {
11022         case 6 ... 7:
11023                 bpp = 6 * 3;
11024                 break;
11025         case 8 ... 9:
11026                 bpp = 8 * 3;
11027                 break;
11028         case 10 ... 11:
11029                 bpp = 10 * 3;
11030                 break;
11031         case 12:
11032                 bpp = 12 * 3;
11033                 break;
11034         default:
11035                 return -EINVAL;
11036         }
11037
11038         if (bpp < pipe_config->pipe_bpp) {
11039                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] Limiting display bpp to %d instead of "
11040                               "EDID bpp %d, requested bpp %d, max platform bpp %d\n",
11041                               connector->base.id, connector->name,
11042                               bpp, 3 * info->bpc, 3 * conn_state->max_requested_bpc,
11043                               pipe_config->pipe_bpp);
11044
11045                 pipe_config->pipe_bpp = bpp;
11046         }
11047
11048         return 0;
11049 }
11050
11051 static int
11052 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11053                           struct intel_crtc_state *pipe_config)
11054 {
11055         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11056         struct drm_atomic_state *state = pipe_config->base.state;
11057         struct drm_connector *connector;
11058         struct drm_connector_state *connector_state;
11059         int bpp, i;
11060
11061         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11062             IS_CHERRYVIEW(dev_priv)))
11063                 bpp = 10*3;
11064         else if (INTEL_GEN(dev_priv) >= 5)
11065                 bpp = 12*3;
11066         else
11067                 bpp = 8*3;
11068
11069         pipe_config->pipe_bpp = bpp;
11070
11071         /* Clamp display bpp to connector max bpp */
11072         for_each_new_connector_in_state(state, connector, connector_state, i) {
11073                 int ret;
11074
11075                 if (connector_state->crtc != &crtc->base)
11076                         continue;
11077
11078                 ret = compute_sink_pipe_bpp(connector_state, pipe_config);
11079                 if (ret)
11080                         return ret;
11081         }
11082
11083         return 0;
11084 }
11085
11086 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11087 {
11088         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11089                         "type: 0x%x flags: 0x%x\n",
11090                 mode->crtc_clock,
11091                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11092                 mode->crtc_hsync_end, mode->crtc_htotal,
11093                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11094                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11095 }
11096
11097 static inline void
11098 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11099                       unsigned int lane_count, struct intel_link_m_n *m_n)
11100 {
11101         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11102                       id, lane_count,
11103                       m_n->gmch_m, m_n->gmch_n,
11104                       m_n->link_m, m_n->link_n, m_n->tu);
11105 }
11106
11107 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
11108
11109 static const char * const output_type_str[] = {
11110         OUTPUT_TYPE(UNUSED),
11111         OUTPUT_TYPE(ANALOG),
11112         OUTPUT_TYPE(DVO),
11113         OUTPUT_TYPE(SDVO),
11114         OUTPUT_TYPE(LVDS),
11115         OUTPUT_TYPE(TVOUT),
11116         OUTPUT_TYPE(HDMI),
11117         OUTPUT_TYPE(DP),
11118         OUTPUT_TYPE(EDP),
11119         OUTPUT_TYPE(DSI),
11120         OUTPUT_TYPE(DDI),
11121         OUTPUT_TYPE(DP_MST),
11122 };
11123
11124 #undef OUTPUT_TYPE
11125
11126 static void snprintf_output_types(char *buf, size_t len,
11127                                   unsigned int output_types)
11128 {
11129         char *str = buf;
11130         int i;
11131
11132         str[0] = '\0';
11133
11134         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11135                 int r;
11136
11137                 if ((output_types & BIT(i)) == 0)
11138                         continue;
11139
11140                 r = snprintf(str, len, "%s%s",
11141                              str != buf ? "," : "", output_type_str[i]);
11142                 if (r >= len)
11143                         break;
11144                 str += r;
11145                 len -= r;
11146
11147                 output_types &= ~BIT(i);
11148         }
11149
11150         WARN_ON_ONCE(output_types != 0);
11151 }
11152
11153 static const char * const output_format_str[] = {
11154         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
11155         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
11156         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
11157         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
11158 };
11159
11160 static const char *output_formats(enum intel_output_format format)
11161 {
11162         if (format >= ARRAY_SIZE(output_format_str))
11163                 format = INTEL_OUTPUT_FORMAT_INVALID;
11164         return output_format_str[format];
11165 }
11166
11167 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11168                                    struct intel_crtc_state *pipe_config,
11169                                    const char *context)
11170 {
11171         struct drm_device *dev = crtc->base.dev;
11172         struct drm_i915_private *dev_priv = to_i915(dev);
11173         struct drm_plane *plane;
11174         struct intel_plane *intel_plane;
11175         struct intel_plane_state *state;
11176         struct drm_framebuffer *fb;
11177         char buf[64];
11178
11179         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11180                       crtc->base.base.id, crtc->base.name, context);
11181
11182         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
11183         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
11184                       buf, pipe_config->output_types);
11185
11186         DRM_DEBUG_KMS("output format: %s\n",
11187                       output_formats(pipe_config->output_format));
11188
11189         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11190                       transcoder_name(pipe_config->cpu_transcoder),
11191                       pipe_config->pipe_bpp, pipe_config->dither);
11192
11193         if (pipe_config->has_pch_encoder)
11194                 intel_dump_m_n_config(pipe_config, "fdi",
11195                                       pipe_config->fdi_lanes,
11196                                       &pipe_config->fdi_m_n);
11197
11198         if (intel_crtc_has_dp_encoder(pipe_config)) {
11199                 intel_dump_m_n_config(pipe_config, "dp m_n",
11200                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11201                 if (pipe_config->has_drrs)
11202                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11203                                               pipe_config->lane_count,
11204                                               &pipe_config->dp_m2_n2);
11205         }
11206
11207         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11208                       pipe_config->has_audio, pipe_config->has_infoframe);
11209
11210         DRM_DEBUG_KMS("requested mode:\n");
11211         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11212         DRM_DEBUG_KMS("adjusted mode:\n");
11213         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11214         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11215         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11216                       pipe_config->port_clock,
11217                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11218                       pipe_config->pixel_rate);
11219
11220         if (INTEL_GEN(dev_priv) >= 9)
11221                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11222                               crtc->num_scalers,
11223                               pipe_config->scaler_state.scaler_users,
11224                               pipe_config->scaler_state.scaler_id);
11225
11226         if (HAS_GMCH_DISPLAY(dev_priv))
11227                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11228                               pipe_config->gmch_pfit.control,
11229                               pipe_config->gmch_pfit.pgm_ratios,
11230                               pipe_config->gmch_pfit.lvds_border_bits);
11231         else
11232                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11233                               pipe_config->pch_pfit.pos,
11234                               pipe_config->pch_pfit.size,
11235                               enableddisabled(pipe_config->pch_pfit.enabled));
11236
11237         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11238                       pipe_config->ips_enabled, pipe_config->double_wide);
11239
11240         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11241
11242         DRM_DEBUG_KMS("planes on this crtc\n");
11243         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11244                 struct drm_format_name_buf format_name;
11245                 intel_plane = to_intel_plane(plane);
11246                 if (intel_plane->pipe != crtc->pipe)
11247                         continue;
11248
11249                 state = to_intel_plane_state(plane->state);
11250                 fb = state->base.fb;
11251                 if (!fb) {
11252                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11253                                       plane->base.id, plane->name, state->scaler_id);
11254                         continue;
11255                 }
11256
11257                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11258                               plane->base.id, plane->name,
11259                               fb->base.id, fb->width, fb->height,
11260                               drm_get_format_name(fb->format->format, &format_name));
11261                 if (INTEL_GEN(dev_priv) >= 9)
11262                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11263                                       state->scaler_id,
11264                                       state->base.src.x1 >> 16,
11265                                       state->base.src.y1 >> 16,
11266                                       drm_rect_width(&state->base.src) >> 16,
11267                                       drm_rect_height(&state->base.src) >> 16,
11268                                       state->base.dst.x1, state->base.dst.y1,
11269                                       drm_rect_width(&state->base.dst),
11270                                       drm_rect_height(&state->base.dst));
11271         }
11272 }
11273
11274 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11275 {
11276         struct drm_device *dev = state->dev;
11277         struct drm_connector *connector;
11278         struct drm_connector_list_iter conn_iter;
11279         unsigned int used_ports = 0;
11280         unsigned int used_mst_ports = 0;
11281         bool ret = true;
11282
11283         /*
11284          * Walk the connector list instead of the encoder
11285          * list to detect the problem on ddi platforms
11286          * where there's just one encoder per digital port.
11287          */
11288         drm_connector_list_iter_begin(dev, &conn_iter);
11289         drm_for_each_connector_iter(connector, &conn_iter) {
11290                 struct drm_connector_state *connector_state;
11291                 struct intel_encoder *encoder;
11292
11293                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11294                 if (!connector_state)
11295                         connector_state = connector->state;
11296
11297                 if (!connector_state->best_encoder)
11298                         continue;
11299
11300                 encoder = to_intel_encoder(connector_state->best_encoder);
11301
11302                 WARN_ON(!connector_state->crtc);
11303
11304                 switch (encoder->type) {
11305                         unsigned int port_mask;
11306                 case INTEL_OUTPUT_DDI:
11307                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11308                                 break;
11309                         /* else: fall through */
11310                 case INTEL_OUTPUT_DP:
11311                 case INTEL_OUTPUT_HDMI:
11312                 case INTEL_OUTPUT_EDP:
11313                         port_mask = 1 << encoder->port;
11314
11315                         /* the same port mustn't appear more than once */
11316                         if (used_ports & port_mask)
11317                                 ret = false;
11318
11319                         used_ports |= port_mask;
11320                         break;
11321                 case INTEL_OUTPUT_DP_MST:
11322                         used_mst_ports |=
11323                                 1 << encoder->port;
11324                         break;
11325                 default:
11326                         break;
11327                 }
11328         }
11329         drm_connector_list_iter_end(&conn_iter);
11330
11331         /* can't mix MST and SST/HDMI on the same port */
11332         if (used_ports & used_mst_ports)
11333                 return false;
11334
11335         return ret;
11336 }
11337
11338 static void
11339 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11340 {
11341         struct drm_i915_private *dev_priv =
11342                 to_i915(crtc_state->base.crtc->dev);
11343         struct intel_crtc_scaler_state scaler_state;
11344         struct intel_dpll_hw_state dpll_hw_state;
11345         struct intel_shared_dpll *shared_dpll;
11346         struct intel_crtc_wm_state wm_state;
11347         bool force_thru, ips_force_disable;
11348
11349         /* FIXME: before the switch to atomic started, a new pipe_config was
11350          * kzalloc'd. Code that depends on any field being zero should be
11351          * fixed, so that the crtc_state can be safely duplicated. For now,
11352          * only fields that are know to not cause problems are preserved. */
11353
11354         scaler_state = crtc_state->scaler_state;
11355         shared_dpll = crtc_state->shared_dpll;
11356         dpll_hw_state = crtc_state->dpll_hw_state;
11357         force_thru = crtc_state->pch_pfit.force_thru;
11358         ips_force_disable = crtc_state->ips_force_disable;
11359         if (IS_G4X(dev_priv) ||
11360             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11361                 wm_state = crtc_state->wm;
11362
11363         /* Keep base drm_crtc_state intact, only clear our extended struct */
11364         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11365         memset(&crtc_state->base + 1, 0,
11366                sizeof(*crtc_state) - sizeof(crtc_state->base));
11367
11368         crtc_state->scaler_state = scaler_state;
11369         crtc_state->shared_dpll = shared_dpll;
11370         crtc_state->dpll_hw_state = dpll_hw_state;
11371         crtc_state->pch_pfit.force_thru = force_thru;
11372         crtc_state->ips_force_disable = ips_force_disable;
11373         if (IS_G4X(dev_priv) ||
11374             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11375                 crtc_state->wm = wm_state;
11376 }
11377
11378 static int
11379 intel_modeset_pipe_config(struct drm_crtc *crtc,
11380                           struct intel_crtc_state *pipe_config)
11381 {
11382         struct drm_atomic_state *state = pipe_config->base.state;
11383         struct intel_encoder *encoder;
11384         struct drm_connector *connector;
11385         struct drm_connector_state *connector_state;
11386         int base_bpp, ret;
11387         int i;
11388         bool retry = true;
11389
11390         clear_intel_crtc_state(pipe_config);
11391
11392         pipe_config->cpu_transcoder =
11393                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11394
11395         /*
11396          * Sanitize sync polarity flags based on requested ones. If neither
11397          * positive or negative polarity is requested, treat this as meaning
11398          * negative polarity.
11399          */
11400         if (!(pipe_config->base.adjusted_mode.flags &
11401               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11402                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11403
11404         if (!(pipe_config->base.adjusted_mode.flags &
11405               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11406                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11407
11408         ret = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11409                                         pipe_config);
11410         if (ret)
11411                 return ret;
11412
11413         base_bpp = pipe_config->pipe_bpp;
11414
11415         /*
11416          * Determine the real pipe dimensions. Note that stereo modes can
11417          * increase the actual pipe size due to the frame doubling and
11418          * insertion of additional space for blanks between the frame. This
11419          * is stored in the crtc timings. We use the requested mode to do this
11420          * computation to clearly distinguish it from the adjusted mode, which
11421          * can be changed by the connectors in the below retry loop.
11422          */
11423         drm_mode_get_hv_timing(&pipe_config->base.mode,
11424                                &pipe_config->pipe_src_w,
11425                                &pipe_config->pipe_src_h);
11426
11427         for_each_new_connector_in_state(state, connector, connector_state, i) {
11428                 if (connector_state->crtc != crtc)
11429                         continue;
11430
11431                 encoder = to_intel_encoder(connector_state->best_encoder);
11432
11433                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11434                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11435                         return -EINVAL;
11436                 }
11437
11438                 /*
11439                  * Determine output_types before calling the .compute_config()
11440                  * hooks so that the hooks can use this information safely.
11441                  */
11442                 if (encoder->compute_output_type)
11443                         pipe_config->output_types |=
11444                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11445                                                                  connector_state));
11446                 else
11447                         pipe_config->output_types |= BIT(encoder->type);
11448         }
11449
11450 encoder_retry:
11451         /* Ensure the port clock defaults are reset when retrying. */
11452         pipe_config->port_clock = 0;
11453         pipe_config->pixel_multiplier = 1;
11454
11455         /* Fill in default crtc timings, allow encoders to overwrite them. */
11456         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11457                               CRTC_STEREO_DOUBLE);
11458
11459         /* Pass our mode to the connectors and the CRTC to give them a chance to
11460          * adjust it according to limitations or connector properties, and also
11461          * a chance to reject the mode entirely.
11462          */
11463         for_each_new_connector_in_state(state, connector, connector_state, i) {
11464                 if (connector_state->crtc != crtc)
11465                         continue;
11466
11467                 encoder = to_intel_encoder(connector_state->best_encoder);
11468
11469                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11470                         DRM_DEBUG_KMS("Encoder config failure\n");
11471                         return -EINVAL;
11472                 }
11473         }
11474
11475         /* Set default port clock if not overwritten by the encoder. Needs to be
11476          * done afterwards in case the encoder adjusts the mode. */
11477         if (!pipe_config->port_clock)
11478                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11479                         * pipe_config->pixel_multiplier;
11480
11481         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11482         if (ret == -EDEADLK)
11483                 return ret;
11484         if (ret < 0) {
11485                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11486                 return ret;
11487         }
11488
11489         if (ret == RETRY) {
11490                 if (WARN(!retry, "loop in pipe configuration computation\n"))
11491                         return -EINVAL;
11492
11493                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11494                 retry = false;
11495                 goto encoder_retry;
11496         }
11497
11498         /* Dithering seems to not pass-through bits correctly when it should, so
11499          * only enable it on 6bpc panels and when its not a compliance
11500          * test requesting 6bpc video pattern.
11501          */
11502         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11503                 !pipe_config->dither_force_disable;
11504         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11505                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11506
11507         return 0;
11508 }
11509
11510 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11511 {
11512         int diff;
11513
11514         if (clock1 == clock2)
11515                 return true;
11516
11517         if (!clock1 || !clock2)
11518                 return false;
11519
11520         diff = abs(clock1 - clock2);
11521
11522         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11523                 return true;
11524
11525         return false;
11526 }
11527
11528 static bool
11529 intel_compare_m_n(unsigned int m, unsigned int n,
11530                   unsigned int m2, unsigned int n2,
11531                   bool exact)
11532 {
11533         if (m == m2 && n == n2)
11534                 return true;
11535
11536         if (exact || !m || !n || !m2 || !n2)
11537                 return false;
11538
11539         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11540
11541         if (n > n2) {
11542                 while (n > n2) {
11543                         m2 <<= 1;
11544                         n2 <<= 1;
11545                 }
11546         } else if (n < n2) {
11547                 while (n < n2) {
11548                         m <<= 1;
11549                         n <<= 1;
11550                 }
11551         }
11552
11553         if (n != n2)
11554                 return false;
11555
11556         return intel_fuzzy_clock_check(m, m2);
11557 }
11558
11559 static bool
11560 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11561                        struct intel_link_m_n *m2_n2,
11562                        bool adjust)
11563 {
11564         if (m_n->tu == m2_n2->tu &&
11565             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11566                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11567             intel_compare_m_n(m_n->link_m, m_n->link_n,
11568                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11569                 if (adjust)
11570                         *m2_n2 = *m_n;
11571
11572                 return true;
11573         }
11574
11575         return false;
11576 }
11577
11578 static void __printf(3, 4)
11579 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11580 {
11581         struct va_format vaf;
11582         va_list args;
11583
11584         va_start(args, format);
11585         vaf.fmt = format;
11586         vaf.va = &args;
11587
11588         if (adjust)
11589                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11590         else
11591                 drm_err("mismatch in %s %pV", name, &vaf);
11592
11593         va_end(args);
11594 }
11595
11596 static bool
11597 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11598                           struct intel_crtc_state *current_config,
11599                           struct intel_crtc_state *pipe_config,
11600                           bool adjust)
11601 {
11602         bool ret = true;
11603         bool fixup_inherited = adjust &&
11604                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11605                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11606
11607 #define PIPE_CONF_CHECK_X(name) do { \
11608         if (current_config->name != pipe_config->name) { \
11609                 pipe_config_err(adjust, __stringify(name), \
11610                           "(expected 0x%08x, found 0x%08x)\n", \
11611                           current_config->name, \
11612                           pipe_config->name); \
11613                 ret = false; \
11614         } \
11615 } while (0)
11616
11617 #define PIPE_CONF_CHECK_I(name) do { \
11618         if (current_config->name != pipe_config->name) { \
11619                 pipe_config_err(adjust, __stringify(name), \
11620                           "(expected %i, found %i)\n", \
11621                           current_config->name, \
11622                           pipe_config->name); \
11623                 ret = false; \
11624         } \
11625 } while (0)
11626
11627 #define PIPE_CONF_CHECK_BOOL(name) do { \
11628         if (current_config->name != pipe_config->name) { \
11629                 pipe_config_err(adjust, __stringify(name), \
11630                           "(expected %s, found %s)\n", \
11631                           yesno(current_config->name), \
11632                           yesno(pipe_config->name)); \
11633                 ret = false; \
11634         } \
11635 } while (0)
11636
11637 /*
11638  * Checks state where we only read out the enabling, but not the entire
11639  * state itself (like full infoframes or ELD for audio). These states
11640  * require a full modeset on bootup to fix up.
11641  */
11642 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11643         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11644                 PIPE_CONF_CHECK_BOOL(name); \
11645         } else { \
11646                 pipe_config_err(adjust, __stringify(name), \
11647                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11648                           yesno(current_config->name), \
11649                           yesno(pipe_config->name)); \
11650                 ret = false; \
11651         } \
11652 } while (0)
11653
11654 #define PIPE_CONF_CHECK_P(name) do { \
11655         if (current_config->name != pipe_config->name) { \
11656                 pipe_config_err(adjust, __stringify(name), \
11657                           "(expected %p, found %p)\n", \
11658                           current_config->name, \
11659                           pipe_config->name); \
11660                 ret = false; \
11661         } \
11662 } while (0)
11663
11664 #define PIPE_CONF_CHECK_M_N(name) do { \
11665         if (!intel_compare_link_m_n(&current_config->name, \
11666                                     &pipe_config->name,\
11667                                     adjust)) { \
11668                 pipe_config_err(adjust, __stringify(name), \
11669                           "(expected tu %i gmch %i/%i link %i/%i, " \
11670                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11671                           current_config->name.tu, \
11672                           current_config->name.gmch_m, \
11673                           current_config->name.gmch_n, \
11674                           current_config->name.link_m, \
11675                           current_config->name.link_n, \
11676                           pipe_config->name.tu, \
11677                           pipe_config->name.gmch_m, \
11678                           pipe_config->name.gmch_n, \
11679                           pipe_config->name.link_m, \
11680                           pipe_config->name.link_n); \
11681                 ret = false; \
11682         } \
11683 } while (0)
11684
11685 /* This is required for BDW+ where there is only one set of registers for
11686  * switching between high and low RR.
11687  * This macro can be used whenever a comparison has to be made between one
11688  * hw state and multiple sw state variables.
11689  */
11690 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11691         if (!intel_compare_link_m_n(&current_config->name, \
11692                                     &pipe_config->name, adjust) && \
11693             !intel_compare_link_m_n(&current_config->alt_name, \
11694                                     &pipe_config->name, adjust)) { \
11695                 pipe_config_err(adjust, __stringify(name), \
11696                           "(expected tu %i gmch %i/%i link %i/%i, " \
11697                           "or tu %i gmch %i/%i link %i/%i, " \
11698                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11699                           current_config->name.tu, \
11700                           current_config->name.gmch_m, \
11701                           current_config->name.gmch_n, \
11702                           current_config->name.link_m, \
11703                           current_config->name.link_n, \
11704                           current_config->alt_name.tu, \
11705                           current_config->alt_name.gmch_m, \
11706                           current_config->alt_name.gmch_n, \
11707                           current_config->alt_name.link_m, \
11708                           current_config->alt_name.link_n, \
11709                           pipe_config->name.tu, \
11710                           pipe_config->name.gmch_m, \
11711                           pipe_config->name.gmch_n, \
11712                           pipe_config->name.link_m, \
11713                           pipe_config->name.link_n); \
11714                 ret = false; \
11715         } \
11716 } while (0)
11717
11718 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11719         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11720                 pipe_config_err(adjust, __stringify(name), \
11721                           "(%x) (expected %i, found %i)\n", \
11722                           (mask), \
11723                           current_config->name & (mask), \
11724                           pipe_config->name & (mask)); \
11725                 ret = false; \
11726         } \
11727 } while (0)
11728
11729 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11730         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11731                 pipe_config_err(adjust, __stringify(name), \
11732                           "(expected %i, found %i)\n", \
11733                           current_config->name, \
11734                           pipe_config->name); \
11735                 ret = false; \
11736         } \
11737 } while (0)
11738
11739 #define PIPE_CONF_QUIRK(quirk)  \
11740         ((current_config->quirks | pipe_config->quirks) & (quirk))
11741
11742         PIPE_CONF_CHECK_I(cpu_transcoder);
11743
11744         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11745         PIPE_CONF_CHECK_I(fdi_lanes);
11746         PIPE_CONF_CHECK_M_N(fdi_m_n);
11747
11748         PIPE_CONF_CHECK_I(lane_count);
11749         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11750
11751         if (INTEL_GEN(dev_priv) < 8) {
11752                 PIPE_CONF_CHECK_M_N(dp_m_n);
11753
11754                 if (current_config->has_drrs)
11755                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11756         } else
11757                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11758
11759         PIPE_CONF_CHECK_X(output_types);
11760
11761         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11762         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11763         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11764         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11765         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11766         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11767
11768         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11769         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11770         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11771         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11772         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11773         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11774
11775         PIPE_CONF_CHECK_I(pixel_multiplier);
11776         PIPE_CONF_CHECK_I(output_format);
11777         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11778         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11779             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11780                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11781
11782         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11783         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11784         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11785
11786         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11787
11788         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11789                               DRM_MODE_FLAG_INTERLACE);
11790
11791         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11792                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11793                                       DRM_MODE_FLAG_PHSYNC);
11794                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11795                                       DRM_MODE_FLAG_NHSYNC);
11796                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11797                                       DRM_MODE_FLAG_PVSYNC);
11798                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11799                                       DRM_MODE_FLAG_NVSYNC);
11800         }
11801
11802         PIPE_CONF_CHECK_X(gmch_pfit.control);
11803         /* pfit ratios are autocomputed by the hw on gen4+ */
11804         if (INTEL_GEN(dev_priv) < 4)
11805                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11806         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11807
11808         if (!adjust) {
11809                 PIPE_CONF_CHECK_I(pipe_src_w);
11810                 PIPE_CONF_CHECK_I(pipe_src_h);
11811
11812                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11813                 if (current_config->pch_pfit.enabled) {
11814                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11815                         PIPE_CONF_CHECK_X(pch_pfit.size);
11816                 }
11817
11818                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11819                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11820         }
11821
11822         PIPE_CONF_CHECK_BOOL(double_wide);
11823
11824         PIPE_CONF_CHECK_P(shared_dpll);
11825         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11826         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11827         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11828         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11829         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11830         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11831         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11832         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11833         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11834         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11835         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11836         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11837         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11838         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11839         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11840         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11841         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11842         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11843         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11844         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11845         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11846         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11847         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11848         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11849         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11850         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11851         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11852         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11853         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11854         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11855         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11856
11857         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11858         PIPE_CONF_CHECK_X(dsi_pll.div);
11859
11860         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11861                 PIPE_CONF_CHECK_I(pipe_bpp);
11862
11863         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11864         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11865
11866         PIPE_CONF_CHECK_I(min_voltage_level);
11867
11868 #undef PIPE_CONF_CHECK_X
11869 #undef PIPE_CONF_CHECK_I
11870 #undef PIPE_CONF_CHECK_BOOL
11871 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11872 #undef PIPE_CONF_CHECK_P
11873 #undef PIPE_CONF_CHECK_FLAGS
11874 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11875 #undef PIPE_CONF_QUIRK
11876
11877         return ret;
11878 }
11879
11880 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11881                                            const struct intel_crtc_state *pipe_config)
11882 {
11883         if (pipe_config->has_pch_encoder) {
11884                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11885                                                             &pipe_config->fdi_m_n);
11886                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11887
11888                 /*
11889                  * FDI already provided one idea for the dotclock.
11890                  * Yell if the encoder disagrees.
11891                  */
11892                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11893                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11894                      fdi_dotclock, dotclock);
11895         }
11896 }
11897
11898 static void verify_wm_state(struct drm_crtc *crtc,
11899                             struct drm_crtc_state *new_state)
11900 {
11901         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11902         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11903         struct skl_pipe_wm hw_wm, *sw_wm;
11904         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11905         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11906         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11907         const enum pipe pipe = intel_crtc->pipe;
11908         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11909
11910         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11911                 return;
11912
11913         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11914         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11915
11916         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11917         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11918
11919         if (INTEL_GEN(dev_priv) >= 11)
11920                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
11921                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
11922                                   sw_ddb->enabled_slices,
11923                                   hw_ddb.enabled_slices);
11924         /* planes */
11925         for_each_universal_plane(dev_priv, pipe, plane) {
11926                 hw_plane_wm = &hw_wm.planes[plane];
11927                 sw_plane_wm = &sw_wm->planes[plane];
11928
11929                 /* Watermarks */
11930                 for (level = 0; level <= max_level; level++) {
11931                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11932                                                 &sw_plane_wm->wm[level]))
11933                                 continue;
11934
11935                         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",
11936                                   pipe_name(pipe), plane + 1, level,
11937                                   sw_plane_wm->wm[level].plane_en,
11938                                   sw_plane_wm->wm[level].plane_res_b,
11939                                   sw_plane_wm->wm[level].plane_res_l,
11940                                   hw_plane_wm->wm[level].plane_en,
11941                                   hw_plane_wm->wm[level].plane_res_b,
11942                                   hw_plane_wm->wm[level].plane_res_l);
11943                 }
11944
11945                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11946                                          &sw_plane_wm->trans_wm)) {
11947                         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",
11948                                   pipe_name(pipe), plane + 1,
11949                                   sw_plane_wm->trans_wm.plane_en,
11950                                   sw_plane_wm->trans_wm.plane_res_b,
11951                                   sw_plane_wm->trans_wm.plane_res_l,
11952                                   hw_plane_wm->trans_wm.plane_en,
11953                                   hw_plane_wm->trans_wm.plane_res_b,
11954                                   hw_plane_wm->trans_wm.plane_res_l);
11955                 }
11956
11957                 /* DDB */
11958                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11959                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11960
11961                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11962                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11963                                   pipe_name(pipe), plane + 1,
11964                                   sw_ddb_entry->start, sw_ddb_entry->end,
11965                                   hw_ddb_entry->start, hw_ddb_entry->end);
11966                 }
11967         }
11968
11969         /*
11970          * cursor
11971          * If the cursor plane isn't active, we may not have updated it's ddb
11972          * allocation. In that case since the ddb allocation will be updated
11973          * once the plane becomes visible, we can skip this check
11974          */
11975         if (1) {
11976                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11977                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11978
11979                 /* Watermarks */
11980                 for (level = 0; level <= max_level; level++) {
11981                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11982                                                 &sw_plane_wm->wm[level]))
11983                                 continue;
11984
11985                         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",
11986                                   pipe_name(pipe), level,
11987                                   sw_plane_wm->wm[level].plane_en,
11988                                   sw_plane_wm->wm[level].plane_res_b,
11989                                   sw_plane_wm->wm[level].plane_res_l,
11990                                   hw_plane_wm->wm[level].plane_en,
11991                                   hw_plane_wm->wm[level].plane_res_b,
11992                                   hw_plane_wm->wm[level].plane_res_l);
11993                 }
11994
11995                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11996                                          &sw_plane_wm->trans_wm)) {
11997                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11998                                   pipe_name(pipe),
11999                                   sw_plane_wm->trans_wm.plane_en,
12000                                   sw_plane_wm->trans_wm.plane_res_b,
12001                                   sw_plane_wm->trans_wm.plane_res_l,
12002                                   hw_plane_wm->trans_wm.plane_en,
12003                                   hw_plane_wm->trans_wm.plane_res_b,
12004                                   hw_plane_wm->trans_wm.plane_res_l);
12005                 }
12006
12007                 /* DDB */
12008                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12009                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12010
12011                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12012                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12013                                   pipe_name(pipe),
12014                                   sw_ddb_entry->start, sw_ddb_entry->end,
12015                                   hw_ddb_entry->start, hw_ddb_entry->end);
12016                 }
12017         }
12018 }
12019
12020 static void
12021 verify_connector_state(struct drm_device *dev,
12022                        struct drm_atomic_state *state,
12023                        struct drm_crtc *crtc)
12024 {
12025         struct drm_connector *connector;
12026         struct drm_connector_state *new_conn_state;
12027         int i;
12028
12029         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12030                 struct drm_encoder *encoder = connector->encoder;
12031                 struct drm_crtc_state *crtc_state = NULL;
12032
12033                 if (new_conn_state->crtc != crtc)
12034                         continue;
12035
12036                 if (crtc)
12037                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12038
12039                 intel_connector_verify_state(crtc_state, new_conn_state);
12040
12041                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12042                      "connector's atomic encoder doesn't match legacy encoder\n");
12043         }
12044 }
12045
12046 static void
12047 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12048 {
12049         struct intel_encoder *encoder;
12050         struct drm_connector *connector;
12051         struct drm_connector_state *old_conn_state, *new_conn_state;
12052         int i;
12053
12054         for_each_intel_encoder(dev, encoder) {
12055                 bool enabled = false, found = false;
12056                 enum pipe pipe;
12057
12058                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12059                               encoder->base.base.id,
12060                               encoder->base.name);
12061
12062                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12063                                                    new_conn_state, i) {
12064                         if (old_conn_state->best_encoder == &encoder->base)
12065                                 found = true;
12066
12067                         if (new_conn_state->best_encoder != &encoder->base)
12068                                 continue;
12069                         found = enabled = true;
12070
12071                         I915_STATE_WARN(new_conn_state->crtc !=
12072                                         encoder->base.crtc,
12073                              "connector's crtc doesn't match encoder crtc\n");
12074                 }
12075
12076                 if (!found)
12077                         continue;
12078
12079                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12080                      "encoder's enabled state mismatch "
12081                      "(expected %i, found %i)\n",
12082                      !!encoder->base.crtc, enabled);
12083
12084                 if (!encoder->base.crtc) {
12085                         bool active;
12086
12087                         active = encoder->get_hw_state(encoder, &pipe);
12088                         I915_STATE_WARN(active,
12089                              "encoder detached but still enabled on pipe %c.\n",
12090                              pipe_name(pipe));
12091                 }
12092         }
12093 }
12094
12095 static void
12096 verify_crtc_state(struct drm_crtc *crtc,
12097                   struct drm_crtc_state *old_crtc_state,
12098                   struct drm_crtc_state *new_crtc_state)
12099 {
12100         struct drm_device *dev = crtc->dev;
12101         struct drm_i915_private *dev_priv = to_i915(dev);
12102         struct intel_encoder *encoder;
12103         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12104         struct intel_crtc_state *pipe_config, *sw_config;
12105         struct drm_atomic_state *old_state;
12106         bool active;
12107
12108         old_state = old_crtc_state->state;
12109         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12110         pipe_config = to_intel_crtc_state(old_crtc_state);
12111         memset(pipe_config, 0, sizeof(*pipe_config));
12112         pipe_config->base.crtc = crtc;
12113         pipe_config->base.state = old_state;
12114
12115         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12116
12117         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12118
12119         /* we keep both pipes enabled on 830 */
12120         if (IS_I830(dev_priv))
12121                 active = new_crtc_state->active;
12122
12123         I915_STATE_WARN(new_crtc_state->active != active,
12124              "crtc active state doesn't match with hw state "
12125              "(expected %i, found %i)\n", new_crtc_state->active, active);
12126
12127         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12128              "transitional active state does not match atomic hw state "
12129              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12130
12131         for_each_encoder_on_crtc(dev, crtc, encoder) {
12132                 enum pipe pipe;
12133
12134                 active = encoder->get_hw_state(encoder, &pipe);
12135                 I915_STATE_WARN(active != new_crtc_state->active,
12136                         "[ENCODER:%i] active %i with crtc active %i\n",
12137                         encoder->base.base.id, active, new_crtc_state->active);
12138
12139                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12140                                 "Encoder connected to wrong pipe %c\n",
12141                                 pipe_name(pipe));
12142
12143                 if (active)
12144                         encoder->get_config(encoder, pipe_config);
12145         }
12146
12147         intel_crtc_compute_pixel_rate(pipe_config);
12148
12149         if (!new_crtc_state->active)
12150                 return;
12151
12152         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12153
12154         sw_config = to_intel_crtc_state(new_crtc_state);
12155         if (!intel_pipe_config_compare(dev_priv, sw_config,
12156                                        pipe_config, false)) {
12157                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12158                 intel_dump_pipe_config(intel_crtc, pipe_config,
12159                                        "[hw state]");
12160                 intel_dump_pipe_config(intel_crtc, sw_config,
12161                                        "[sw state]");
12162         }
12163 }
12164
12165 static void
12166 intel_verify_planes(struct intel_atomic_state *state)
12167 {
12168         struct intel_plane *plane;
12169         const struct intel_plane_state *plane_state;
12170         int i;
12171
12172         for_each_new_intel_plane_in_state(state, plane,
12173                                           plane_state, i)
12174                 assert_plane(plane, plane_state->base.visible);
12175 }
12176
12177 static void
12178 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12179                          struct intel_shared_dpll *pll,
12180                          struct drm_crtc *crtc,
12181                          struct drm_crtc_state *new_state)
12182 {
12183         struct intel_dpll_hw_state dpll_hw_state;
12184         unsigned int crtc_mask;
12185         bool active;
12186
12187         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12188
12189         DRM_DEBUG_KMS("%s\n", pll->info->name);
12190
12191         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12192
12193         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12194                 I915_STATE_WARN(!pll->on && pll->active_mask,
12195                      "pll in active use but not on in sw tracking\n");
12196                 I915_STATE_WARN(pll->on && !pll->active_mask,
12197                      "pll is on but not used by any active crtc\n");
12198                 I915_STATE_WARN(pll->on != active,
12199                      "pll on state mismatch (expected %i, found %i)\n",
12200                      pll->on, active);
12201         }
12202
12203         if (!crtc) {
12204                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12205                                 "more active pll users than references: %x vs %x\n",
12206                                 pll->active_mask, pll->state.crtc_mask);
12207
12208                 return;
12209         }
12210
12211         crtc_mask = drm_crtc_mask(crtc);
12212
12213         if (new_state->active)
12214                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12215                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12216                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12217         else
12218                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12219                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12220                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12221
12222         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12223                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12224                         crtc_mask, pll->state.crtc_mask);
12225
12226         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12227                                           &dpll_hw_state,
12228                                           sizeof(dpll_hw_state)),
12229                         "pll hw state mismatch\n");
12230 }
12231
12232 static void
12233 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12234                          struct drm_crtc_state *old_crtc_state,
12235                          struct drm_crtc_state *new_crtc_state)
12236 {
12237         struct drm_i915_private *dev_priv = to_i915(dev);
12238         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12239         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12240
12241         if (new_state->shared_dpll)
12242                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12243
12244         if (old_state->shared_dpll &&
12245             old_state->shared_dpll != new_state->shared_dpll) {
12246                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12247                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12248
12249                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12250                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12251                                 pipe_name(drm_crtc_index(crtc)));
12252                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12253                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12254                                 pipe_name(drm_crtc_index(crtc)));
12255         }
12256 }
12257
12258 static void
12259 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12260                           struct drm_atomic_state *state,
12261                           struct drm_crtc_state *old_state,
12262                           struct drm_crtc_state *new_state)
12263 {
12264         if (!needs_modeset(new_state) &&
12265             !to_intel_crtc_state(new_state)->update_pipe)
12266                 return;
12267
12268         verify_wm_state(crtc, new_state);
12269         verify_connector_state(crtc->dev, state, crtc);
12270         verify_crtc_state(crtc, old_state, new_state);
12271         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12272 }
12273
12274 static void
12275 verify_disabled_dpll_state(struct drm_device *dev)
12276 {
12277         struct drm_i915_private *dev_priv = to_i915(dev);
12278         int i;
12279
12280         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12281                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12282 }
12283
12284 static void
12285 intel_modeset_verify_disabled(struct drm_device *dev,
12286                               struct drm_atomic_state *state)
12287 {
12288         verify_encoder_state(dev, state);
12289         verify_connector_state(dev, state, NULL);
12290         verify_disabled_dpll_state(dev);
12291 }
12292
12293 static void update_scanline_offset(const struct intel_crtc_state *crtc_state)
12294 {
12295         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
12296         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12297
12298         /*
12299          * The scanline counter increments at the leading edge of hsync.
12300          *
12301          * On most platforms it starts counting from vtotal-1 on the
12302          * first active line. That means the scanline counter value is
12303          * always one less than what we would expect. Ie. just after
12304          * start of vblank, which also occurs at start of hsync (on the
12305          * last active line), the scanline counter will read vblank_start-1.
12306          *
12307          * On gen2 the scanline counter starts counting from 1 instead
12308          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12309          * to keep the value positive), instead of adding one.
12310          *
12311          * On HSW+ the behaviour of the scanline counter depends on the output
12312          * type. For DP ports it behaves like most other platforms, but on HDMI
12313          * there's an extra 1 line difference. So we need to add two instead of
12314          * one to the value.
12315          *
12316          * On VLV/CHV DSI the scanline counter would appear to increment
12317          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12318          * that means we can't tell whether we're in vblank or not while
12319          * we're on that particular line. We must still set scanline_offset
12320          * to 1 so that the vblank timestamps come out correct when we query
12321          * the scanline counter from within the vblank interrupt handler.
12322          * However if queried just before the start of vblank we'll get an
12323          * answer that's slightly in the future.
12324          */
12325         if (IS_GEN2(dev_priv)) {
12326                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
12327                 int vtotal;
12328
12329                 vtotal = adjusted_mode->crtc_vtotal;
12330                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12331                         vtotal /= 2;
12332
12333                 crtc->scanline_offset = vtotal - 1;
12334         } else if (HAS_DDI(dev_priv) &&
12335                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
12336                 crtc->scanline_offset = 2;
12337         } else
12338                 crtc->scanline_offset = 1;
12339 }
12340
12341 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12342 {
12343         struct drm_device *dev = state->dev;
12344         struct drm_i915_private *dev_priv = to_i915(dev);
12345         struct drm_crtc *crtc;
12346         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12347         int i;
12348
12349         if (!dev_priv->display.crtc_compute_clock)
12350                 return;
12351
12352         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12353                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12354                 struct intel_shared_dpll *old_dpll =
12355                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12356
12357                 if (!needs_modeset(new_crtc_state))
12358                         continue;
12359
12360                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12361
12362                 if (!old_dpll)
12363                         continue;
12364
12365                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12366         }
12367 }
12368
12369 /*
12370  * This implements the workaround described in the "notes" section of the mode
12371  * set sequence documentation. When going from no pipes or single pipe to
12372  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12373  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12374  */
12375 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12376 {
12377         struct drm_crtc_state *crtc_state;
12378         struct intel_crtc *intel_crtc;
12379         struct drm_crtc *crtc;
12380         struct intel_crtc_state *first_crtc_state = NULL;
12381         struct intel_crtc_state *other_crtc_state = NULL;
12382         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12383         int i;
12384
12385         /* look at all crtc's that are going to be enabled in during modeset */
12386         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12387                 intel_crtc = to_intel_crtc(crtc);
12388
12389                 if (!crtc_state->active || !needs_modeset(crtc_state))
12390                         continue;
12391
12392                 if (first_crtc_state) {
12393                         other_crtc_state = to_intel_crtc_state(crtc_state);
12394                         break;
12395                 } else {
12396                         first_crtc_state = to_intel_crtc_state(crtc_state);
12397                         first_pipe = intel_crtc->pipe;
12398                 }
12399         }
12400
12401         /* No workaround needed? */
12402         if (!first_crtc_state)
12403                 return 0;
12404
12405         /* w/a possibly needed, check how many crtc's are already enabled. */
12406         for_each_intel_crtc(state->dev, intel_crtc) {
12407                 struct intel_crtc_state *pipe_config;
12408
12409                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12410                 if (IS_ERR(pipe_config))
12411                         return PTR_ERR(pipe_config);
12412
12413                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12414
12415                 if (!pipe_config->base.active ||
12416                     needs_modeset(&pipe_config->base))
12417                         continue;
12418
12419                 /* 2 or more enabled crtcs means no need for w/a */
12420                 if (enabled_pipe != INVALID_PIPE)
12421                         return 0;
12422
12423                 enabled_pipe = intel_crtc->pipe;
12424         }
12425
12426         if (enabled_pipe != INVALID_PIPE)
12427                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12428         else if (other_crtc_state)
12429                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12430
12431         return 0;
12432 }
12433
12434 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12435 {
12436         struct drm_crtc *crtc;
12437
12438         /* Add all pipes to the state */
12439         for_each_crtc(state->dev, crtc) {
12440                 struct drm_crtc_state *crtc_state;
12441
12442                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12443                 if (IS_ERR(crtc_state))
12444                         return PTR_ERR(crtc_state);
12445         }
12446
12447         return 0;
12448 }
12449
12450 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12451 {
12452         struct drm_crtc *crtc;
12453
12454         /*
12455          * Add all pipes to the state, and force
12456          * a modeset on all the active ones.
12457          */
12458         for_each_crtc(state->dev, crtc) {
12459                 struct drm_crtc_state *crtc_state;
12460                 int ret;
12461
12462                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12463                 if (IS_ERR(crtc_state))
12464                         return PTR_ERR(crtc_state);
12465
12466                 if (!crtc_state->active || needs_modeset(crtc_state))
12467                         continue;
12468
12469                 crtc_state->mode_changed = true;
12470
12471                 ret = drm_atomic_add_affected_connectors(state, crtc);
12472                 if (ret)
12473                         return ret;
12474
12475                 ret = drm_atomic_add_affected_planes(state, crtc);
12476                 if (ret)
12477                         return ret;
12478         }
12479
12480         return 0;
12481 }
12482
12483 static int intel_modeset_checks(struct drm_atomic_state *state)
12484 {
12485         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12486         struct drm_i915_private *dev_priv = to_i915(state->dev);
12487         struct drm_crtc *crtc;
12488         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12489         int ret = 0, i;
12490
12491         if (!check_digital_port_conflicts(state)) {
12492                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12493                 return -EINVAL;
12494         }
12495
12496         intel_state->modeset = true;
12497         intel_state->active_crtcs = dev_priv->active_crtcs;
12498         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12499         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12500
12501         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12502                 if (new_crtc_state->active)
12503                         intel_state->active_crtcs |= 1 << i;
12504                 else
12505                         intel_state->active_crtcs &= ~(1 << i);
12506
12507                 if (old_crtc_state->active != new_crtc_state->active)
12508                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12509         }
12510
12511         /*
12512          * See if the config requires any additional preparation, e.g.
12513          * to adjust global state with pipes off.  We need to do this
12514          * here so we can get the modeset_pipe updated config for the new
12515          * mode set on this crtc.  For other crtcs we need to use the
12516          * adjusted_mode bits in the crtc directly.
12517          */
12518         if (dev_priv->display.modeset_calc_cdclk) {
12519                 ret = dev_priv->display.modeset_calc_cdclk(state);
12520                 if (ret < 0)
12521                         return ret;
12522
12523                 /*
12524                  * Writes to dev_priv->cdclk.logical must protected by
12525                  * holding all the crtc locks, even if we don't end up
12526                  * touching the hardware
12527                  */
12528                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12529                                         &intel_state->cdclk.logical)) {
12530                         ret = intel_lock_all_pipes(state);
12531                         if (ret < 0)
12532                                 return ret;
12533                 }
12534
12535                 /* All pipes must be switched off while we change the cdclk. */
12536                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12537                                               &intel_state->cdclk.actual)) {
12538                         ret = intel_modeset_all_pipes(state);
12539                         if (ret < 0)
12540                                 return ret;
12541                 }
12542
12543                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12544                               intel_state->cdclk.logical.cdclk,
12545                               intel_state->cdclk.actual.cdclk);
12546                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12547                               intel_state->cdclk.logical.voltage_level,
12548                               intel_state->cdclk.actual.voltage_level);
12549         } else {
12550                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12551         }
12552
12553         intel_modeset_clear_plls(state);
12554
12555         if (IS_HASWELL(dev_priv))
12556                 return haswell_mode_set_planes_workaround(state);
12557
12558         return 0;
12559 }
12560
12561 /*
12562  * Handle calculation of various watermark data at the end of the atomic check
12563  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12564  * handlers to ensure that all derived state has been updated.
12565  */
12566 static int calc_watermark_data(struct drm_atomic_state *state)
12567 {
12568         struct drm_device *dev = state->dev;
12569         struct drm_i915_private *dev_priv = to_i915(dev);
12570
12571         /* Is there platform-specific watermark information to calculate? */
12572         if (dev_priv->display.compute_global_watermarks)
12573                 return dev_priv->display.compute_global_watermarks(state);
12574
12575         return 0;
12576 }
12577
12578 /**
12579  * intel_atomic_check - validate state object
12580  * @dev: drm device
12581  * @state: state to validate
12582  */
12583 static int intel_atomic_check(struct drm_device *dev,
12584                               struct drm_atomic_state *state)
12585 {
12586         struct drm_i915_private *dev_priv = to_i915(dev);
12587         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12588         struct drm_crtc *crtc;
12589         struct drm_crtc_state *old_crtc_state, *crtc_state;
12590         int ret, i;
12591         bool any_ms = false;
12592
12593         /* Catch I915_MODE_FLAG_INHERITED */
12594         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12595                                       crtc_state, i) {
12596                 if (crtc_state->mode.private_flags !=
12597                     old_crtc_state->mode.private_flags)
12598                         crtc_state->mode_changed = true;
12599         }
12600
12601         ret = drm_atomic_helper_check_modeset(dev, state);
12602         if (ret)
12603                 return ret;
12604
12605         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12606                 struct intel_crtc_state *pipe_config =
12607                         to_intel_crtc_state(crtc_state);
12608
12609                 if (!needs_modeset(crtc_state))
12610                         continue;
12611
12612                 if (!crtc_state->enable) {
12613                         any_ms = true;
12614                         continue;
12615                 }
12616
12617                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12618                 if (ret == -EDEADLK)
12619                         return ret;
12620                 if (ret) {
12621                         intel_dump_pipe_config(to_intel_crtc(crtc),
12622                                                pipe_config, "[failed]");
12623                         return ret;
12624                 }
12625
12626                 if (i915_modparams.fastboot &&
12627                     intel_pipe_config_compare(dev_priv,
12628                                         to_intel_crtc_state(old_crtc_state),
12629                                         pipe_config, true)) {
12630                         crtc_state->mode_changed = false;
12631                         pipe_config->update_pipe = true;
12632                 }
12633
12634                 if (needs_modeset(crtc_state))
12635                         any_ms = true;
12636
12637                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12638                                        needs_modeset(crtc_state) ?
12639                                        "[modeset]" : "[fastset]");
12640         }
12641
12642         if (any_ms) {
12643                 ret = intel_modeset_checks(state);
12644
12645                 if (ret)
12646                         return ret;
12647         } else {
12648                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12649         }
12650
12651         ret = icl_add_linked_planes(intel_state);
12652         if (ret)
12653                 return ret;
12654
12655         ret = drm_atomic_helper_check_planes(dev, state);
12656         if (ret)
12657                 return ret;
12658
12659         intel_fbc_choose_crtc(dev_priv, intel_state);
12660         return calc_watermark_data(state);
12661 }
12662
12663 static int intel_atomic_prepare_commit(struct drm_device *dev,
12664                                        struct drm_atomic_state *state)
12665 {
12666         return drm_atomic_helper_prepare_planes(dev, state);
12667 }
12668
12669 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12670 {
12671         struct drm_device *dev = crtc->base.dev;
12672
12673         if (!dev->max_vblank_count)
12674                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12675
12676         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12677 }
12678
12679 static void intel_update_crtc(struct drm_crtc *crtc,
12680                               struct drm_atomic_state *state,
12681                               struct drm_crtc_state *old_crtc_state,
12682                               struct drm_crtc_state *new_crtc_state)
12683 {
12684         struct drm_device *dev = crtc->dev;
12685         struct drm_i915_private *dev_priv = to_i915(dev);
12686         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12687         struct intel_crtc_state *old_intel_cstate = to_intel_crtc_state(old_crtc_state);
12688         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12689         bool modeset = needs_modeset(new_crtc_state);
12690         struct intel_plane_state *new_plane_state =
12691                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12692                                                  to_intel_plane(crtc->primary));
12693
12694         if (modeset) {
12695                 update_scanline_offset(pipe_config);
12696                 dev_priv->display.crtc_enable(pipe_config, state);
12697
12698                 /* vblanks work again, re-enable pipe CRC. */
12699                 intel_crtc_enable_pipe_crc(intel_crtc);
12700         } else {
12701                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12702                                        pipe_config);
12703         }
12704
12705         if (new_plane_state)
12706                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12707
12708         intel_begin_crtc_commit(crtc, old_crtc_state);
12709
12710         intel_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc,
12711                                     old_intel_cstate, pipe_config);
12712
12713         intel_finish_crtc_commit(crtc, old_crtc_state);
12714 }
12715
12716 static void intel_update_crtcs(struct drm_atomic_state *state)
12717 {
12718         struct drm_crtc *crtc;
12719         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12720         int i;
12721
12722         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12723                 if (!new_crtc_state->active)
12724                         continue;
12725
12726                 intel_update_crtc(crtc, state, old_crtc_state,
12727                                   new_crtc_state);
12728         }
12729 }
12730
12731 static void skl_update_crtcs(struct drm_atomic_state *state)
12732 {
12733         struct drm_i915_private *dev_priv = to_i915(state->dev);
12734         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12735         struct drm_crtc *crtc;
12736         struct intel_crtc *intel_crtc;
12737         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12738         struct intel_crtc_state *cstate;
12739         unsigned int updated = 0;
12740         bool progress;
12741         enum pipe pipe;
12742         int i;
12743         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12744         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12745         struct skl_ddb_entry entries[I915_MAX_PIPES] = {};
12746
12747         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12748                 /* ignore allocations for crtc's that have been turned off. */
12749                 if (new_crtc_state->active)
12750                         entries[i] = to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12751
12752         /* If 2nd DBuf slice required, enable it here */
12753         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12754                 icl_dbuf_slices_update(dev_priv, required_slices);
12755
12756         /*
12757          * Whenever the number of active pipes changes, we need to make sure we
12758          * update the pipes in the right order so that their ddb allocations
12759          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12760          * cause pipe underruns and other bad stuff.
12761          */
12762         do {
12763                 progress = false;
12764
12765                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12766                         bool vbl_wait = false;
12767                         unsigned int cmask = drm_crtc_mask(crtc);
12768
12769                         intel_crtc = to_intel_crtc(crtc);
12770                         cstate = to_intel_crtc_state(new_crtc_state);
12771                         pipe = intel_crtc->pipe;
12772
12773                         if (updated & cmask || !cstate->base.active)
12774                                 continue;
12775
12776                         if (skl_ddb_allocation_overlaps(&cstate->wm.skl.ddb,
12777                                                         entries,
12778                                                         INTEL_INFO(dev_priv)->num_pipes, i))
12779                                 continue;
12780
12781                         updated |= cmask;
12782                         entries[i] = cstate->wm.skl.ddb;
12783
12784                         /*
12785                          * If this is an already active pipe, it's DDB changed,
12786                          * and this isn't the last pipe that needs updating
12787                          * then we need to wait for a vblank to pass for the
12788                          * new ddb allocation to take effect.
12789                          */
12790                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12791                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12792                             !new_crtc_state->active_changed &&
12793                             intel_state->wm_results.dirty_pipes != updated)
12794                                 vbl_wait = true;
12795
12796                         intel_update_crtc(crtc, state, old_crtc_state,
12797                                           new_crtc_state);
12798
12799                         if (vbl_wait)
12800                                 intel_wait_for_vblank(dev_priv, pipe);
12801
12802                         progress = true;
12803                 }
12804         } while (progress);
12805
12806         /* If 2nd DBuf slice is no more required disable it */
12807         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12808                 icl_dbuf_slices_update(dev_priv, required_slices);
12809 }
12810
12811 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12812 {
12813         struct intel_atomic_state *state, *next;
12814         struct llist_node *freed;
12815
12816         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12817         llist_for_each_entry_safe(state, next, freed, freed)
12818                 drm_atomic_state_put(&state->base);
12819 }
12820
12821 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12822 {
12823         struct drm_i915_private *dev_priv =
12824                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12825
12826         intel_atomic_helper_free_state(dev_priv);
12827 }
12828
12829 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12830 {
12831         struct wait_queue_entry wait_fence, wait_reset;
12832         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12833
12834         init_wait_entry(&wait_fence, 0);
12835         init_wait_entry(&wait_reset, 0);
12836         for (;;) {
12837                 prepare_to_wait(&intel_state->commit_ready.wait,
12838                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12839                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12840                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12841
12842
12843                 if (i915_sw_fence_done(&intel_state->commit_ready)
12844                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12845                         break;
12846
12847                 schedule();
12848         }
12849         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12850         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12851 }
12852
12853 static void intel_atomic_cleanup_work(struct work_struct *work)
12854 {
12855         struct drm_atomic_state *state =
12856                 container_of(work, struct drm_atomic_state, commit_work);
12857         struct drm_i915_private *i915 = to_i915(state->dev);
12858
12859         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12860         drm_atomic_helper_commit_cleanup_done(state);
12861         drm_atomic_state_put(state);
12862
12863         intel_atomic_helper_free_state(i915);
12864 }
12865
12866 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12867 {
12868         struct drm_device *dev = state->dev;
12869         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12870         struct drm_i915_private *dev_priv = to_i915(dev);
12871         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12872         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
12873         struct drm_crtc *crtc;
12874         struct intel_crtc *intel_crtc;
12875         u64 put_domains[I915_MAX_PIPES] = {};
12876         int i;
12877
12878         intel_atomic_commit_fence_wait(intel_state);
12879
12880         drm_atomic_helper_wait_for_dependencies(state);
12881
12882         if (intel_state->modeset)
12883                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12884
12885         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12886                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
12887                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
12888                 intel_crtc = to_intel_crtc(crtc);
12889
12890                 if (needs_modeset(new_crtc_state) ||
12891                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12892
12893                         put_domains[intel_crtc->pipe] =
12894                                 modeset_get_crtc_power_domains(crtc,
12895                                         new_intel_crtc_state);
12896                 }
12897
12898                 if (!needs_modeset(new_crtc_state))
12899                         continue;
12900
12901                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
12902
12903                 if (old_crtc_state->active) {
12904                         intel_crtc_disable_planes(intel_state, intel_crtc);
12905
12906                         /*
12907                          * We need to disable pipe CRC before disabling the pipe,
12908                          * or we race against vblank off.
12909                          */
12910                         intel_crtc_disable_pipe_crc(intel_crtc);
12911
12912                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
12913                         intel_crtc->active = false;
12914                         intel_fbc_disable(intel_crtc);
12915                         intel_disable_shared_dpll(old_intel_crtc_state);
12916
12917                         /*
12918                          * Underruns don't always raise
12919                          * interrupts, so check manually.
12920                          */
12921                         intel_check_cpu_fifo_underruns(dev_priv);
12922                         intel_check_pch_fifo_underruns(dev_priv);
12923
12924                         /* FIXME unify this for all platforms */
12925                         if (!new_crtc_state->active &&
12926                             !HAS_GMCH_DISPLAY(dev_priv) &&
12927                             dev_priv->display.initial_watermarks)
12928                                 dev_priv->display.initial_watermarks(intel_state,
12929                                                                      new_intel_crtc_state);
12930                 }
12931         }
12932
12933         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12934         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12935                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12936
12937         if (intel_state->modeset) {
12938                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12939
12940                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12941
12942                 /*
12943                  * SKL workaround: bspec recommends we disable the SAGV when we
12944                  * have more then one pipe enabled
12945                  */
12946                 if (!intel_can_enable_sagv(state))
12947                         intel_disable_sagv(dev_priv);
12948
12949                 intel_modeset_verify_disabled(dev, state);
12950         }
12951
12952         /* Complete the events for pipes that have now been disabled */
12953         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12954                 bool modeset = needs_modeset(new_crtc_state);
12955
12956                 /* Complete events for now disable pipes here. */
12957                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12958                         spin_lock_irq(&dev->event_lock);
12959                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12960                         spin_unlock_irq(&dev->event_lock);
12961
12962                         new_crtc_state->event = NULL;
12963                 }
12964         }
12965
12966         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12967         dev_priv->display.update_crtcs(state);
12968
12969         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12970          * already, but still need the state for the delayed optimization. To
12971          * fix this:
12972          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12973          * - schedule that vblank worker _before_ calling hw_done
12974          * - at the start of commit_tail, cancel it _synchrously
12975          * - switch over to the vblank wait helper in the core after that since
12976          *   we don't need out special handling any more.
12977          */
12978         drm_atomic_helper_wait_for_flip_done(dev, state);
12979
12980         /*
12981          * Now that the vblank has passed, we can go ahead and program the
12982          * optimal watermarks on platforms that need two-step watermark
12983          * programming.
12984          *
12985          * TODO: Move this (and other cleanup) to an async worker eventually.
12986          */
12987         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12988                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
12989
12990                 if (dev_priv->display.optimize_watermarks)
12991                         dev_priv->display.optimize_watermarks(intel_state,
12992                                                               new_intel_crtc_state);
12993         }
12994
12995         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12996                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12997
12998                 if (put_domains[i])
12999                         modeset_put_power_domains(dev_priv, put_domains[i]);
13000
13001                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13002         }
13003
13004         if (intel_state->modeset)
13005                 intel_verify_planes(intel_state);
13006
13007         if (intel_state->modeset && intel_can_enable_sagv(state))
13008                 intel_enable_sagv(dev_priv);
13009
13010         drm_atomic_helper_commit_hw_done(state);
13011
13012         if (intel_state->modeset) {
13013                 /* As one of the primary mmio accessors, KMS has a high
13014                  * likelihood of triggering bugs in unclaimed access. After we
13015                  * finish modesetting, see if an error has been flagged, and if
13016                  * so enable debugging for the next modeset - and hope we catch
13017                  * the culprit.
13018                  */
13019                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13020                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13021         }
13022
13023         /*
13024          * Defer the cleanup of the old state to a separate worker to not
13025          * impede the current task (userspace for blocking modesets) that
13026          * are executed inline. For out-of-line asynchronous modesets/flips,
13027          * deferring to a new worker seems overkill, but we would place a
13028          * schedule point (cond_resched()) here anyway to keep latencies
13029          * down.
13030          */
13031         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
13032         queue_work(system_highpri_wq, &state->commit_work);
13033 }
13034
13035 static void intel_atomic_commit_work(struct work_struct *work)
13036 {
13037         struct drm_atomic_state *state =
13038                 container_of(work, struct drm_atomic_state, commit_work);
13039
13040         intel_atomic_commit_tail(state);
13041 }
13042
13043 static int __i915_sw_fence_call
13044 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13045                           enum i915_sw_fence_notify notify)
13046 {
13047         struct intel_atomic_state *state =
13048                 container_of(fence, struct intel_atomic_state, commit_ready);
13049
13050         switch (notify) {
13051         case FENCE_COMPLETE:
13052                 /* we do blocking waits in the worker, nothing to do here */
13053                 break;
13054         case FENCE_FREE:
13055                 {
13056                         struct intel_atomic_helper *helper =
13057                                 &to_i915(state->base.dev)->atomic_helper;
13058
13059                         if (llist_add(&state->freed, &helper->free_list))
13060                                 schedule_work(&helper->free_work);
13061                         break;
13062                 }
13063         }
13064
13065         return NOTIFY_DONE;
13066 }
13067
13068 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13069 {
13070         struct drm_plane_state *old_plane_state, *new_plane_state;
13071         struct drm_plane *plane;
13072         int i;
13073
13074         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13075                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13076                                   intel_fb_obj(new_plane_state->fb),
13077                                   to_intel_plane(plane)->frontbuffer_bit);
13078 }
13079
13080 /**
13081  * intel_atomic_commit - commit validated state object
13082  * @dev: DRM device
13083  * @state: the top-level driver state object
13084  * @nonblock: nonblocking commit
13085  *
13086  * This function commits a top-level state object that has been validated
13087  * with drm_atomic_helper_check().
13088  *
13089  * RETURNS
13090  * Zero for success or -errno.
13091  */
13092 static int intel_atomic_commit(struct drm_device *dev,
13093                                struct drm_atomic_state *state,
13094                                bool nonblock)
13095 {
13096         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13097         struct drm_i915_private *dev_priv = to_i915(dev);
13098         int ret = 0;
13099
13100         drm_atomic_state_get(state);
13101         i915_sw_fence_init(&intel_state->commit_ready,
13102                            intel_atomic_commit_ready);
13103
13104         /*
13105          * The intel_legacy_cursor_update() fast path takes care
13106          * of avoiding the vblank waits for simple cursor
13107          * movement and flips. For cursor on/off and size changes,
13108          * we want to perform the vblank waits so that watermark
13109          * updates happen during the correct frames. Gen9+ have
13110          * double buffered watermarks and so shouldn't need this.
13111          *
13112          * Unset state->legacy_cursor_update before the call to
13113          * drm_atomic_helper_setup_commit() because otherwise
13114          * drm_atomic_helper_wait_for_flip_done() is a noop and
13115          * we get FIFO underruns because we didn't wait
13116          * for vblank.
13117          *
13118          * FIXME doing watermarks and fb cleanup from a vblank worker
13119          * (assuming we had any) would solve these problems.
13120          */
13121         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
13122                 struct intel_crtc_state *new_crtc_state;
13123                 struct intel_crtc *crtc;
13124                 int i;
13125
13126                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
13127                         if (new_crtc_state->wm.need_postvbl_update ||
13128                             new_crtc_state->update_wm_post)
13129                                 state->legacy_cursor_update = false;
13130         }
13131
13132         ret = intel_atomic_prepare_commit(dev, state);
13133         if (ret) {
13134                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13135                 i915_sw_fence_commit(&intel_state->commit_ready);
13136                 return ret;
13137         }
13138
13139         ret = drm_atomic_helper_setup_commit(state, nonblock);
13140         if (!ret)
13141                 ret = drm_atomic_helper_swap_state(state, true);
13142
13143         if (ret) {
13144                 i915_sw_fence_commit(&intel_state->commit_ready);
13145
13146                 drm_atomic_helper_cleanup_planes(dev, state);
13147                 return ret;
13148         }
13149         dev_priv->wm.distrust_bios_wm = false;
13150         intel_shared_dpll_swap_state(state);
13151         intel_atomic_track_fbs(state);
13152
13153         if (intel_state->modeset) {
13154                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
13155                        sizeof(intel_state->min_cdclk));
13156                 memcpy(dev_priv->min_voltage_level,
13157                        intel_state->min_voltage_level,
13158                        sizeof(intel_state->min_voltage_level));
13159                 dev_priv->active_crtcs = intel_state->active_crtcs;
13160                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
13161                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
13162         }
13163
13164         drm_atomic_state_get(state);
13165         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13166
13167         i915_sw_fence_commit(&intel_state->commit_ready);
13168         if (nonblock && intel_state->modeset) {
13169                 queue_work(dev_priv->modeset_wq, &state->commit_work);
13170         } else if (nonblock) {
13171                 queue_work(system_unbound_wq, &state->commit_work);
13172         } else {
13173                 if (intel_state->modeset)
13174                         flush_workqueue(dev_priv->modeset_wq);
13175                 intel_atomic_commit_tail(state);
13176         }
13177
13178         return 0;
13179 }
13180
13181 static const struct drm_crtc_funcs intel_crtc_funcs = {
13182         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13183         .set_config = drm_atomic_helper_set_config,
13184         .destroy = intel_crtc_destroy,
13185         .page_flip = drm_atomic_helper_page_flip,
13186         .atomic_duplicate_state = intel_crtc_duplicate_state,
13187         .atomic_destroy_state = intel_crtc_destroy_state,
13188         .set_crc_source = intel_crtc_set_crc_source,
13189         .verify_crc_source = intel_crtc_verify_crc_source,
13190         .get_crc_sources = intel_crtc_get_crc_sources,
13191 };
13192
13193 struct wait_rps_boost {
13194         struct wait_queue_entry wait;
13195
13196         struct drm_crtc *crtc;
13197         struct i915_request *request;
13198 };
13199
13200 static int do_rps_boost(struct wait_queue_entry *_wait,
13201                         unsigned mode, int sync, void *key)
13202 {
13203         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13204         struct i915_request *rq = wait->request;
13205
13206         /*
13207          * If we missed the vblank, but the request is already running it
13208          * is reasonable to assume that it will complete before the next
13209          * vblank without our intervention, so leave RPS alone.
13210          */
13211         if (!i915_request_started(rq))
13212                 gen6_rps_boost(rq, NULL);
13213         i915_request_put(rq);
13214
13215         drm_crtc_vblank_put(wait->crtc);
13216
13217         list_del(&wait->wait.entry);
13218         kfree(wait);
13219         return 1;
13220 }
13221
13222 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13223                                        struct dma_fence *fence)
13224 {
13225         struct wait_rps_boost *wait;
13226
13227         if (!dma_fence_is_i915(fence))
13228                 return;
13229
13230         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13231                 return;
13232
13233         if (drm_crtc_vblank_get(crtc))
13234                 return;
13235
13236         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13237         if (!wait) {
13238                 drm_crtc_vblank_put(crtc);
13239                 return;
13240         }
13241
13242         wait->request = to_request(dma_fence_get(fence));
13243         wait->crtc = crtc;
13244
13245         wait->wait.func = do_rps_boost;
13246         wait->wait.flags = 0;
13247
13248         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13249 }
13250
13251 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13252 {
13253         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13254         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13255         struct drm_framebuffer *fb = plane_state->base.fb;
13256         struct i915_vma *vma;
13257
13258         if (plane->id == PLANE_CURSOR &&
13259             INTEL_INFO(dev_priv)->cursor_needs_physical) {
13260                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13261                 const int align = intel_cursor_alignment(dev_priv);
13262                 int err;
13263
13264                 err = i915_gem_object_attach_phys(obj, align);
13265                 if (err)
13266                         return err;
13267         }
13268
13269         vma = intel_pin_and_fence_fb_obj(fb,
13270                                          &plane_state->view,
13271                                          intel_plane_uses_fence(plane_state),
13272                                          &plane_state->flags);
13273         if (IS_ERR(vma))
13274                 return PTR_ERR(vma);
13275
13276         plane_state->vma = vma;
13277
13278         return 0;
13279 }
13280
13281 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13282 {
13283         struct i915_vma *vma;
13284
13285         vma = fetch_and_zero(&old_plane_state->vma);
13286         if (vma)
13287                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13288 }
13289
13290 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13291 {
13292         struct i915_sched_attr attr = {
13293                 .priority = I915_PRIORITY_DISPLAY,
13294         };
13295
13296         i915_gem_object_wait_priority(obj, 0, &attr);
13297 }
13298
13299 /**
13300  * intel_prepare_plane_fb - Prepare fb for usage on plane
13301  * @plane: drm plane to prepare for
13302  * @new_state: the plane state being prepared
13303  *
13304  * Prepares a framebuffer for usage on a display plane.  Generally this
13305  * involves pinning the underlying object and updating the frontbuffer tracking
13306  * bits.  Some older platforms need special physical address handling for
13307  * cursor planes.
13308  *
13309  * Must be called with struct_mutex held.
13310  *
13311  * Returns 0 on success, negative error code on failure.
13312  */
13313 int
13314 intel_prepare_plane_fb(struct drm_plane *plane,
13315                        struct drm_plane_state *new_state)
13316 {
13317         struct intel_atomic_state *intel_state =
13318                 to_intel_atomic_state(new_state->state);
13319         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13320         struct drm_framebuffer *fb = new_state->fb;
13321         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13322         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13323         int ret;
13324
13325         if (old_obj) {
13326                 struct drm_crtc_state *crtc_state =
13327                         drm_atomic_get_new_crtc_state(new_state->state,
13328                                                       plane->state->crtc);
13329
13330                 /* Big Hammer, we also need to ensure that any pending
13331                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13332                  * current scanout is retired before unpinning the old
13333                  * framebuffer. Note that we rely on userspace rendering
13334                  * into the buffer attached to the pipe they are waiting
13335                  * on. If not, userspace generates a GPU hang with IPEHR
13336                  * point to the MI_WAIT_FOR_EVENT.
13337                  *
13338                  * This should only fail upon a hung GPU, in which case we
13339                  * can safely continue.
13340                  */
13341                 if (needs_modeset(crtc_state)) {
13342                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13343                                                               old_obj->resv, NULL,
13344                                                               false, 0,
13345                                                               GFP_KERNEL);
13346                         if (ret < 0)
13347                                 return ret;
13348                 }
13349         }
13350
13351         if (new_state->fence) { /* explicit fencing */
13352                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13353                                                     new_state->fence,
13354                                                     I915_FENCE_TIMEOUT,
13355                                                     GFP_KERNEL);
13356                 if (ret < 0)
13357                         return ret;
13358         }
13359
13360         if (!obj)
13361                 return 0;
13362
13363         ret = i915_gem_object_pin_pages(obj);
13364         if (ret)
13365                 return ret;
13366
13367         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13368         if (ret) {
13369                 i915_gem_object_unpin_pages(obj);
13370                 return ret;
13371         }
13372
13373         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13374
13375         mutex_unlock(&dev_priv->drm.struct_mutex);
13376         i915_gem_object_unpin_pages(obj);
13377         if (ret)
13378                 return ret;
13379
13380         fb_obj_bump_render_priority(obj);
13381         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13382
13383         if (!new_state->fence) { /* implicit fencing */
13384                 struct dma_fence *fence;
13385
13386                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13387                                                       obj->resv, NULL,
13388                                                       false, I915_FENCE_TIMEOUT,
13389                                                       GFP_KERNEL);
13390                 if (ret < 0)
13391                         return ret;
13392
13393                 fence = reservation_object_get_excl_rcu(obj->resv);
13394                 if (fence) {
13395                         add_rps_boost_after_vblank(new_state->crtc, fence);
13396                         dma_fence_put(fence);
13397                 }
13398         } else {
13399                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13400         }
13401
13402         /*
13403          * We declare pageflips to be interactive and so merit a small bias
13404          * towards upclocking to deliver the frame on time. By only changing
13405          * the RPS thresholds to sample more regularly and aim for higher
13406          * clocks we can hopefully deliver low power workloads (like kodi)
13407          * that are not quite steady state without resorting to forcing
13408          * maximum clocks following a vblank miss (see do_rps_boost()).
13409          */
13410         if (!intel_state->rps_interactive) {
13411                 intel_rps_mark_interactive(dev_priv, true);
13412                 intel_state->rps_interactive = true;
13413         }
13414
13415         return 0;
13416 }
13417
13418 /**
13419  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13420  * @plane: drm plane to clean up for
13421  * @old_state: the state from the previous modeset
13422  *
13423  * Cleans up a framebuffer that has just been removed from a plane.
13424  *
13425  * Must be called with struct_mutex held.
13426  */
13427 void
13428 intel_cleanup_plane_fb(struct drm_plane *plane,
13429                        struct drm_plane_state *old_state)
13430 {
13431         struct intel_atomic_state *intel_state =
13432                 to_intel_atomic_state(old_state->state);
13433         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13434
13435         if (intel_state->rps_interactive) {
13436                 intel_rps_mark_interactive(dev_priv, false);
13437                 intel_state->rps_interactive = false;
13438         }
13439
13440         /* Should only be called after a successful intel_prepare_plane_fb()! */
13441         mutex_lock(&dev_priv->drm.struct_mutex);
13442         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13443         mutex_unlock(&dev_priv->drm.struct_mutex);
13444 }
13445
13446 int
13447 skl_max_scale(const struct intel_crtc_state *crtc_state,
13448               u32 pixel_format)
13449 {
13450         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13451         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13452         int max_scale, mult;
13453         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13454
13455         if (!crtc_state->base.enable)
13456                 return DRM_PLANE_HELPER_NO_SCALING;
13457
13458         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13459         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13460
13461         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13462                 max_dotclk *= 2;
13463
13464         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13465                 return DRM_PLANE_HELPER_NO_SCALING;
13466
13467         /*
13468          * skl max scale is lower of:
13469          *    close to 3 but not 3, -1 is for that purpose
13470          *            or
13471          *    cdclk/crtc_clock
13472          */
13473         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13474         tmpclk1 = (1 << 16) * mult - 1;
13475         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13476         max_scale = min(tmpclk1, tmpclk2);
13477
13478         return max_scale;
13479 }
13480
13481 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13482                                     struct drm_crtc_state *old_crtc_state)
13483 {
13484         struct drm_device *dev = crtc->dev;
13485         struct drm_i915_private *dev_priv = to_i915(dev);
13486         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13487         struct intel_crtc_state *old_intel_cstate =
13488                 to_intel_crtc_state(old_crtc_state);
13489         struct intel_atomic_state *old_intel_state =
13490                 to_intel_atomic_state(old_crtc_state->state);
13491         struct intel_crtc_state *intel_cstate =
13492                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13493         bool modeset = needs_modeset(&intel_cstate->base);
13494
13495         if (!modeset &&
13496             (intel_cstate->base.color_mgmt_changed ||
13497              intel_cstate->update_pipe)) {
13498                 intel_color_set_csc(&intel_cstate->base);
13499                 intel_color_load_luts(&intel_cstate->base);
13500         }
13501
13502         /* Perform vblank evasion around commit operation */
13503         intel_pipe_update_start(intel_cstate);
13504
13505         if (modeset)
13506                 goto out;
13507
13508         if (intel_cstate->update_pipe)
13509                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13510         else if (INTEL_GEN(dev_priv) >= 9)
13511                 skl_detach_scalers(intel_cstate);
13512
13513 out:
13514         if (dev_priv->display.atomic_update_watermarks)
13515                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13516                                                            intel_cstate);
13517 }
13518
13519 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13520                                   struct intel_crtc_state *crtc_state)
13521 {
13522         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13523
13524         if (!IS_GEN2(dev_priv))
13525                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13526
13527         if (crtc_state->has_pch_encoder) {
13528                 enum pipe pch_transcoder =
13529                         intel_crtc_pch_transcoder(crtc);
13530
13531                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13532         }
13533 }
13534
13535 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13536                                      struct drm_crtc_state *old_crtc_state)
13537 {
13538         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13539         struct intel_atomic_state *old_intel_state =
13540                 to_intel_atomic_state(old_crtc_state->state);
13541         struct intel_crtc_state *new_crtc_state =
13542                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13543
13544         intel_pipe_update_end(new_crtc_state);
13545
13546         if (new_crtc_state->update_pipe &&
13547             !needs_modeset(&new_crtc_state->base) &&
13548             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13549                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13550 }
13551
13552 /**
13553  * intel_plane_destroy - destroy a plane
13554  * @plane: plane to destroy
13555  *
13556  * Common destruction function for all types of planes (primary, cursor,
13557  * sprite).
13558  */
13559 void intel_plane_destroy(struct drm_plane *plane)
13560 {
13561         drm_plane_cleanup(plane);
13562         kfree(to_intel_plane(plane));
13563 }
13564
13565 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13566                                             u32 format, u64 modifier)
13567 {
13568         switch (modifier) {
13569         case DRM_FORMAT_MOD_LINEAR:
13570         case I915_FORMAT_MOD_X_TILED:
13571                 break;
13572         default:
13573                 return false;
13574         }
13575
13576         switch (format) {
13577         case DRM_FORMAT_C8:
13578         case DRM_FORMAT_RGB565:
13579         case DRM_FORMAT_XRGB1555:
13580         case DRM_FORMAT_XRGB8888:
13581                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13582                         modifier == I915_FORMAT_MOD_X_TILED;
13583         default:
13584                 return false;
13585         }
13586 }
13587
13588 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13589                                             u32 format, u64 modifier)
13590 {
13591         switch (modifier) {
13592         case DRM_FORMAT_MOD_LINEAR:
13593         case I915_FORMAT_MOD_X_TILED:
13594                 break;
13595         default:
13596                 return false;
13597         }
13598
13599         switch (format) {
13600         case DRM_FORMAT_C8:
13601         case DRM_FORMAT_RGB565:
13602         case DRM_FORMAT_XRGB8888:
13603         case DRM_FORMAT_XBGR8888:
13604         case DRM_FORMAT_XRGB2101010:
13605         case DRM_FORMAT_XBGR2101010:
13606                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13607                         modifier == I915_FORMAT_MOD_X_TILED;
13608         default:
13609                 return false;
13610         }
13611 }
13612
13613 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13614                                               u32 format, u64 modifier)
13615 {
13616         return modifier == DRM_FORMAT_MOD_LINEAR &&
13617                 format == DRM_FORMAT_ARGB8888;
13618 }
13619
13620 static const struct drm_plane_funcs i965_plane_funcs = {
13621         .update_plane = drm_atomic_helper_update_plane,
13622         .disable_plane = drm_atomic_helper_disable_plane,
13623         .destroy = intel_plane_destroy,
13624         .atomic_get_property = intel_plane_atomic_get_property,
13625         .atomic_set_property = intel_plane_atomic_set_property,
13626         .atomic_duplicate_state = intel_plane_duplicate_state,
13627         .atomic_destroy_state = intel_plane_destroy_state,
13628         .format_mod_supported = i965_plane_format_mod_supported,
13629 };
13630
13631 static const struct drm_plane_funcs i8xx_plane_funcs = {
13632         .update_plane = drm_atomic_helper_update_plane,
13633         .disable_plane = drm_atomic_helper_disable_plane,
13634         .destroy = intel_plane_destroy,
13635         .atomic_get_property = intel_plane_atomic_get_property,
13636         .atomic_set_property = intel_plane_atomic_set_property,
13637         .atomic_duplicate_state = intel_plane_duplicate_state,
13638         .atomic_destroy_state = intel_plane_destroy_state,
13639         .format_mod_supported = i8xx_plane_format_mod_supported,
13640 };
13641
13642 static int
13643 intel_legacy_cursor_update(struct drm_plane *plane,
13644                            struct drm_crtc *crtc,
13645                            struct drm_framebuffer *fb,
13646                            int crtc_x, int crtc_y,
13647                            unsigned int crtc_w, unsigned int crtc_h,
13648                            uint32_t src_x, uint32_t src_y,
13649                            uint32_t src_w, uint32_t src_h,
13650                            struct drm_modeset_acquire_ctx *ctx)
13651 {
13652         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13653         int ret;
13654         struct drm_plane_state *old_plane_state, *new_plane_state;
13655         struct intel_plane *intel_plane = to_intel_plane(plane);
13656         struct drm_framebuffer *old_fb;
13657         struct intel_crtc_state *crtc_state =
13658                 to_intel_crtc_state(crtc->state);
13659         struct intel_crtc_state *new_crtc_state;
13660
13661         /*
13662          * When crtc is inactive or there is a modeset pending,
13663          * wait for it to complete in the slowpath
13664          */
13665         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
13666             crtc_state->update_pipe)
13667                 goto slow;
13668
13669         old_plane_state = plane->state;
13670         /*
13671          * Don't do an async update if there is an outstanding commit modifying
13672          * the plane.  This prevents our async update's changes from getting
13673          * overridden by a previous synchronous update's state.
13674          */
13675         if (old_plane_state->commit &&
13676             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13677                 goto slow;
13678
13679         /*
13680          * If any parameters change that may affect watermarks,
13681          * take the slowpath. Only changing fb or position should be
13682          * in the fastpath.
13683          */
13684         if (old_plane_state->crtc != crtc ||
13685             old_plane_state->src_w != src_w ||
13686             old_plane_state->src_h != src_h ||
13687             old_plane_state->crtc_w != crtc_w ||
13688             old_plane_state->crtc_h != crtc_h ||
13689             !old_plane_state->fb != !fb)
13690                 goto slow;
13691
13692         new_plane_state = intel_plane_duplicate_state(plane);
13693         if (!new_plane_state)
13694                 return -ENOMEM;
13695
13696         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
13697         if (!new_crtc_state) {
13698                 ret = -ENOMEM;
13699                 goto out_free;
13700         }
13701
13702         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13703
13704         new_plane_state->src_x = src_x;
13705         new_plane_state->src_y = src_y;
13706         new_plane_state->src_w = src_w;
13707         new_plane_state->src_h = src_h;
13708         new_plane_state->crtc_x = crtc_x;
13709         new_plane_state->crtc_y = crtc_y;
13710         new_plane_state->crtc_w = crtc_w;
13711         new_plane_state->crtc_h = crtc_h;
13712
13713         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
13714                                                   to_intel_plane_state(old_plane_state),
13715                                                   to_intel_plane_state(new_plane_state));
13716         if (ret)
13717                 goto out_free;
13718
13719         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13720         if (ret)
13721                 goto out_free;
13722
13723         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13724         if (ret)
13725                 goto out_unlock;
13726
13727         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13728
13729         old_fb = old_plane_state->fb;
13730         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13731                           intel_plane->frontbuffer_bit);
13732
13733         /* Swap plane state */
13734         plane->state = new_plane_state;
13735
13736         /*
13737          * We cannot swap crtc_state as it may be in use by an atomic commit or
13738          * page flip that's running simultaneously. If we swap crtc_state and
13739          * destroy the old state, we will cause a use-after-free there.
13740          *
13741          * Only update active_planes, which is needed for our internal
13742          * bookkeeping. Either value will do the right thing when updating
13743          * planes atomically. If the cursor was part of the atomic update then
13744          * we would have taken the slowpath.
13745          */
13746         crtc_state->active_planes = new_crtc_state->active_planes;
13747
13748         if (plane->state->visible) {
13749                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13750                 intel_plane->update_plane(intel_plane, crtc_state,
13751                                           to_intel_plane_state(plane->state));
13752         } else {
13753                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13754                 intel_plane->disable_plane(intel_plane, crtc_state);
13755         }
13756
13757         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13758
13759 out_unlock:
13760         mutex_unlock(&dev_priv->drm.struct_mutex);
13761 out_free:
13762         if (new_crtc_state)
13763                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
13764         if (ret)
13765                 intel_plane_destroy_state(plane, new_plane_state);
13766         else
13767                 intel_plane_destroy_state(plane, old_plane_state);
13768         return ret;
13769
13770 slow:
13771         return drm_atomic_helper_update_plane(plane, crtc, fb,
13772                                               crtc_x, crtc_y, crtc_w, crtc_h,
13773                                               src_x, src_y, src_w, src_h, ctx);
13774 }
13775
13776 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13777         .update_plane = intel_legacy_cursor_update,
13778         .disable_plane = drm_atomic_helper_disable_plane,
13779         .destroy = intel_plane_destroy,
13780         .atomic_get_property = intel_plane_atomic_get_property,
13781         .atomic_set_property = intel_plane_atomic_set_property,
13782         .atomic_duplicate_state = intel_plane_duplicate_state,
13783         .atomic_destroy_state = intel_plane_destroy_state,
13784         .format_mod_supported = intel_cursor_format_mod_supported,
13785 };
13786
13787 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13788                                enum i9xx_plane_id i9xx_plane)
13789 {
13790         if (!HAS_FBC(dev_priv))
13791                 return false;
13792
13793         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13794                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13795         else if (IS_IVYBRIDGE(dev_priv))
13796                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13797                         i9xx_plane == PLANE_C;
13798         else if (INTEL_GEN(dev_priv) >= 4)
13799                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13800         else
13801                 return i9xx_plane == PLANE_A;
13802 }
13803
13804 static struct intel_plane *
13805 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13806 {
13807         struct intel_plane *plane;
13808         const struct drm_plane_funcs *plane_funcs;
13809         unsigned int supported_rotations;
13810         unsigned int possible_crtcs;
13811         const u64 *modifiers;
13812         const u32 *formats;
13813         int num_formats;
13814         int ret;
13815
13816         if (INTEL_GEN(dev_priv) >= 9)
13817                 return skl_universal_plane_create(dev_priv, pipe,
13818                                                   PLANE_PRIMARY);
13819
13820         plane = intel_plane_alloc();
13821         if (IS_ERR(plane))
13822                 return plane;
13823
13824         plane->pipe = pipe;
13825         /*
13826          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13827          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13828          */
13829         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13830                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
13831         else
13832                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
13833         plane->id = PLANE_PRIMARY;
13834         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
13835
13836         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
13837         if (plane->has_fbc) {
13838                 struct intel_fbc *fbc = &dev_priv->fbc;
13839
13840                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
13841         }
13842
13843         if (INTEL_GEN(dev_priv) >= 4) {
13844                 formats = i965_primary_formats;
13845                 num_formats = ARRAY_SIZE(i965_primary_formats);
13846                 modifiers = i9xx_format_modifiers;
13847
13848                 plane->max_stride = i9xx_plane_max_stride;
13849                 plane->update_plane = i9xx_update_plane;
13850                 plane->disable_plane = i9xx_disable_plane;
13851                 plane->get_hw_state = i9xx_plane_get_hw_state;
13852                 plane->check_plane = i9xx_plane_check;
13853
13854                 plane_funcs = &i965_plane_funcs;
13855         } else {
13856                 formats = i8xx_primary_formats;
13857                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13858                 modifiers = i9xx_format_modifiers;
13859
13860                 plane->max_stride = i9xx_plane_max_stride;
13861                 plane->update_plane = i9xx_update_plane;
13862                 plane->disable_plane = i9xx_disable_plane;
13863                 plane->get_hw_state = i9xx_plane_get_hw_state;
13864                 plane->check_plane = i9xx_plane_check;
13865
13866                 plane_funcs = &i8xx_plane_funcs;
13867         }
13868
13869         possible_crtcs = BIT(pipe);
13870
13871         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13872                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13873                                                possible_crtcs, plane_funcs,
13874                                                formats, num_formats, modifiers,
13875                                                DRM_PLANE_TYPE_PRIMARY,
13876                                                "primary %c", pipe_name(pipe));
13877         else
13878                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13879                                                possible_crtcs, plane_funcs,
13880                                                formats, num_formats, modifiers,
13881                                                DRM_PLANE_TYPE_PRIMARY,
13882                                                "plane %c",
13883                                                plane_name(plane->i9xx_plane));
13884         if (ret)
13885                 goto fail;
13886
13887         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13888                 supported_rotations =
13889                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13890                         DRM_MODE_REFLECT_X;
13891         } else if (INTEL_GEN(dev_priv) >= 4) {
13892                 supported_rotations =
13893                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13894         } else {
13895                 supported_rotations = DRM_MODE_ROTATE_0;
13896         }
13897
13898         if (INTEL_GEN(dev_priv) >= 4)
13899                 drm_plane_create_rotation_property(&plane->base,
13900                                                    DRM_MODE_ROTATE_0,
13901                                                    supported_rotations);
13902
13903         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
13904
13905         return plane;
13906
13907 fail:
13908         intel_plane_free(plane);
13909
13910         return ERR_PTR(ret);
13911 }
13912
13913 static struct intel_plane *
13914 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13915                           enum pipe pipe)
13916 {
13917         unsigned int possible_crtcs;
13918         struct intel_plane *cursor;
13919         int ret;
13920
13921         cursor = intel_plane_alloc();
13922         if (IS_ERR(cursor))
13923                 return cursor;
13924
13925         cursor->pipe = pipe;
13926         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13927         cursor->id = PLANE_CURSOR;
13928         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13929
13930         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13931                 cursor->max_stride = i845_cursor_max_stride;
13932                 cursor->update_plane = i845_update_cursor;
13933                 cursor->disable_plane = i845_disable_cursor;
13934                 cursor->get_hw_state = i845_cursor_get_hw_state;
13935                 cursor->check_plane = i845_check_cursor;
13936         } else {
13937                 cursor->max_stride = i9xx_cursor_max_stride;
13938                 cursor->update_plane = i9xx_update_cursor;
13939                 cursor->disable_plane = i9xx_disable_cursor;
13940                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13941                 cursor->check_plane = i9xx_check_cursor;
13942         }
13943
13944         cursor->cursor.base = ~0;
13945         cursor->cursor.cntl = ~0;
13946
13947         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13948                 cursor->cursor.size = ~0;
13949
13950         possible_crtcs = BIT(pipe);
13951
13952         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13953                                        possible_crtcs, &intel_cursor_plane_funcs,
13954                                        intel_cursor_formats,
13955                                        ARRAY_SIZE(intel_cursor_formats),
13956                                        cursor_format_modifiers,
13957                                        DRM_PLANE_TYPE_CURSOR,
13958                                        "cursor %c", pipe_name(pipe));
13959         if (ret)
13960                 goto fail;
13961
13962         if (INTEL_GEN(dev_priv) >= 4)
13963                 drm_plane_create_rotation_property(&cursor->base,
13964                                                    DRM_MODE_ROTATE_0,
13965                                                    DRM_MODE_ROTATE_0 |
13966                                                    DRM_MODE_ROTATE_180);
13967
13968         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13969
13970         return cursor;
13971
13972 fail:
13973         intel_plane_free(cursor);
13974
13975         return ERR_PTR(ret);
13976 }
13977
13978 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13979                                     struct intel_crtc_state *crtc_state)
13980 {
13981         struct intel_crtc_scaler_state *scaler_state =
13982                 &crtc_state->scaler_state;
13983         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13984         int i;
13985
13986         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13987         if (!crtc->num_scalers)
13988                 return;
13989
13990         for (i = 0; i < crtc->num_scalers; i++) {
13991                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13992
13993                 scaler->in_use = 0;
13994                 scaler->mode = 0;
13995         }
13996
13997         scaler_state->scaler_id = -1;
13998 }
13999
14000 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
14001 {
14002         struct intel_crtc *intel_crtc;
14003         struct intel_crtc_state *crtc_state = NULL;
14004         struct intel_plane *primary = NULL;
14005         struct intel_plane *cursor = NULL;
14006         int sprite, ret;
14007
14008         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14009         if (!intel_crtc)
14010                 return -ENOMEM;
14011
14012         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14013         if (!crtc_state) {
14014                 ret = -ENOMEM;
14015                 goto fail;
14016         }
14017         intel_crtc->config = crtc_state;
14018         intel_crtc->base.state = &crtc_state->base;
14019         crtc_state->base.crtc = &intel_crtc->base;
14020
14021         primary = intel_primary_plane_create(dev_priv, pipe);
14022         if (IS_ERR(primary)) {
14023                 ret = PTR_ERR(primary);
14024                 goto fail;
14025         }
14026         intel_crtc->plane_ids_mask |= BIT(primary->id);
14027
14028         for_each_sprite(dev_priv, pipe, sprite) {
14029                 struct intel_plane *plane;
14030
14031                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
14032                 if (IS_ERR(plane)) {
14033                         ret = PTR_ERR(plane);
14034                         goto fail;
14035                 }
14036                 intel_crtc->plane_ids_mask |= BIT(plane->id);
14037         }
14038
14039         cursor = intel_cursor_plane_create(dev_priv, pipe);
14040         if (IS_ERR(cursor)) {
14041                 ret = PTR_ERR(cursor);
14042                 goto fail;
14043         }
14044         intel_crtc->plane_ids_mask |= BIT(cursor->id);
14045
14046         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
14047                                         &primary->base, &cursor->base,
14048                                         &intel_crtc_funcs,
14049                                         "pipe %c", pipe_name(pipe));
14050         if (ret)
14051                 goto fail;
14052
14053         intel_crtc->pipe = pipe;
14054
14055         /* initialize shared scalers */
14056         intel_crtc_init_scalers(intel_crtc, crtc_state);
14057
14058         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14059                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14060         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14061
14062         if (INTEL_GEN(dev_priv) < 9) {
14063                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14064
14065                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14066                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14067                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14068         }
14069
14070         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14071
14072         intel_color_init(&intel_crtc->base);
14073
14074         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14075
14076         return 0;
14077
14078 fail:
14079         /*
14080          * drm_mode_config_cleanup() will free up any
14081          * crtcs/planes already initialized.
14082          */
14083         kfree(crtc_state);
14084         kfree(intel_crtc);
14085
14086         return ret;
14087 }
14088
14089 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14090                                       struct drm_file *file)
14091 {
14092         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14093         struct drm_crtc *drmmode_crtc;
14094         struct intel_crtc *crtc;
14095
14096         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14097         if (!drmmode_crtc)
14098                 return -ENOENT;
14099
14100         crtc = to_intel_crtc(drmmode_crtc);
14101         pipe_from_crtc_id->pipe = crtc->pipe;
14102
14103         return 0;
14104 }
14105
14106 static int intel_encoder_clones(struct intel_encoder *encoder)
14107 {
14108         struct drm_device *dev = encoder->base.dev;
14109         struct intel_encoder *source_encoder;
14110         int index_mask = 0;
14111         int entry = 0;
14112
14113         for_each_intel_encoder(dev, source_encoder) {
14114                 if (encoders_cloneable(encoder, source_encoder))
14115                         index_mask |= (1 << entry);
14116
14117                 entry++;
14118         }
14119
14120         return index_mask;
14121 }
14122
14123 static bool has_edp_a(struct drm_i915_private *dev_priv)
14124 {
14125         if (!IS_MOBILE(dev_priv))
14126                 return false;
14127
14128         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14129                 return false;
14130
14131         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14132                 return false;
14133
14134         return true;
14135 }
14136
14137 static bool intel_crt_present(struct drm_i915_private *dev_priv)
14138 {
14139         if (INTEL_GEN(dev_priv) >= 9)
14140                 return false;
14141
14142         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14143                 return false;
14144
14145         if (IS_CHERRYVIEW(dev_priv))
14146                 return false;
14147
14148         if (HAS_PCH_LPT_H(dev_priv) &&
14149             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14150                 return false;
14151
14152         /* DDI E can't be used if DDI A requires 4 lanes */
14153         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14154                 return false;
14155
14156         if (!dev_priv->vbt.int_crt_support)
14157                 return false;
14158
14159         return true;
14160 }
14161
14162 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14163 {
14164         int pps_num;
14165         int pps_idx;
14166
14167         if (HAS_DDI(dev_priv))
14168                 return;
14169         /*
14170          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14171          * everywhere where registers can be write protected.
14172          */
14173         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14174                 pps_num = 2;
14175         else
14176                 pps_num = 1;
14177
14178         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14179                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14180
14181                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14182                 I915_WRITE(PP_CONTROL(pps_idx), val);
14183         }
14184 }
14185
14186 static void intel_pps_init(struct drm_i915_private *dev_priv)
14187 {
14188         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14189                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14190         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14191                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14192         else
14193                 dev_priv->pps_mmio_base = PPS_BASE;
14194
14195         intel_pps_unlock_regs_wa(dev_priv);
14196 }
14197
14198 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14199 {
14200         struct intel_encoder *encoder;
14201         bool dpd_is_edp = false;
14202
14203         intel_pps_init(dev_priv);
14204
14205         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14206                 return;
14207
14208         /*
14209          * intel_edp_init_connector() depends on this completing first, to
14210          * prevent the registeration of both eDP and LVDS and the incorrect
14211          * sharing of the PPS.
14212          */
14213         intel_lvds_init(dev_priv);
14214
14215         if (intel_crt_present(dev_priv))
14216                 intel_crt_init(dev_priv);
14217
14218         if (IS_ICELAKE(dev_priv)) {
14219                 intel_ddi_init(dev_priv, PORT_A);
14220                 intel_ddi_init(dev_priv, PORT_B);
14221                 intel_ddi_init(dev_priv, PORT_C);
14222                 intel_ddi_init(dev_priv, PORT_D);
14223                 intel_ddi_init(dev_priv, PORT_E);
14224                 intel_ddi_init(dev_priv, PORT_F);
14225                 icl_dsi_init(dev_priv);
14226         } else if (IS_GEN9_LP(dev_priv)) {
14227                 /*
14228                  * FIXME: Broxton doesn't support port detection via the
14229                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14230                  * detect the ports.
14231                  */
14232                 intel_ddi_init(dev_priv, PORT_A);
14233                 intel_ddi_init(dev_priv, PORT_B);
14234                 intel_ddi_init(dev_priv, PORT_C);
14235
14236                 vlv_dsi_init(dev_priv);
14237         } else if (HAS_DDI(dev_priv)) {
14238                 int found;
14239
14240                 /*
14241                  * Haswell uses DDI functions to detect digital outputs.
14242                  * On SKL pre-D0 the strap isn't connected, so we assume
14243                  * it's there.
14244                  */
14245                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14246                 /* WaIgnoreDDIAStrap: skl */
14247                 if (found || IS_GEN9_BC(dev_priv))
14248                         intel_ddi_init(dev_priv, PORT_A);
14249
14250                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14251                  * register */
14252                 found = I915_READ(SFUSE_STRAP);
14253
14254                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14255                         intel_ddi_init(dev_priv, PORT_B);
14256                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14257                         intel_ddi_init(dev_priv, PORT_C);
14258                 if (found & SFUSE_STRAP_DDID_DETECTED)
14259                         intel_ddi_init(dev_priv, PORT_D);
14260                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14261                         intel_ddi_init(dev_priv, PORT_F);
14262                 /*
14263                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14264                  */
14265                 if (IS_GEN9_BC(dev_priv) &&
14266                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14267                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14268                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14269                         intel_ddi_init(dev_priv, PORT_E);
14270
14271         } else if (HAS_PCH_SPLIT(dev_priv)) {
14272                 int found;
14273                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14274
14275                 if (has_edp_a(dev_priv))
14276                         intel_dp_init(dev_priv, DP_A, PORT_A);
14277
14278                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14279                         /* PCH SDVOB multiplex with HDMIB */
14280                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14281                         if (!found)
14282                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14283                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14284                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14285                 }
14286
14287                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14288                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14289
14290                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14291                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14292
14293                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14294                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14295
14296                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14297                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14298         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14299                 bool has_edp, has_port;
14300
14301                 /*
14302                  * The DP_DETECTED bit is the latched state of the DDC
14303                  * SDA pin at boot. However since eDP doesn't require DDC
14304                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14305                  * eDP ports may have been muxed to an alternate function.
14306                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14307                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14308                  * detect eDP ports.
14309                  *
14310                  * Sadly the straps seem to be missing sometimes even for HDMI
14311                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14312                  * and VBT for the presence of the port. Additionally we can't
14313                  * trust the port type the VBT declares as we've seen at least
14314                  * HDMI ports that the VBT claim are DP or eDP.
14315                  */
14316                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14317                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14318                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14319                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14320                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14321                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14322
14323                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14324                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14325                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14326                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14327                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14328                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14329
14330                 if (IS_CHERRYVIEW(dev_priv)) {
14331                         /*
14332                          * eDP not supported on port D,
14333                          * so no need to worry about it
14334                          */
14335                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14336                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14337                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14338                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14339                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14340                 }
14341
14342                 vlv_dsi_init(dev_priv);
14343         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14344                 bool found = false;
14345
14346                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14347                         DRM_DEBUG_KMS("probing SDVOB\n");
14348                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14349                         if (!found && IS_G4X(dev_priv)) {
14350                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14351                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14352                         }
14353
14354                         if (!found && IS_G4X(dev_priv))
14355                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14356                 }
14357
14358                 /* Before G4X SDVOC doesn't have its own detect register */
14359
14360                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14361                         DRM_DEBUG_KMS("probing SDVOC\n");
14362                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14363                 }
14364
14365                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14366
14367                         if (IS_G4X(dev_priv)) {
14368                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14369                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14370                         }
14371                         if (IS_G4X(dev_priv))
14372                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14373                 }
14374
14375                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14376                         intel_dp_init(dev_priv, DP_D, PORT_D);
14377         } else if (IS_GEN2(dev_priv))
14378                 intel_dvo_init(dev_priv);
14379
14380         if (SUPPORTS_TV(dev_priv))
14381                 intel_tv_init(dev_priv);
14382
14383         intel_psr_init(dev_priv);
14384
14385         for_each_intel_encoder(&dev_priv->drm, encoder) {
14386                 encoder->base.possible_crtcs = encoder->crtc_mask;
14387                 encoder->base.possible_clones =
14388                         intel_encoder_clones(encoder);
14389         }
14390
14391         intel_init_pch_refclk(dev_priv);
14392
14393         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14394 }
14395
14396 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14397 {
14398         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14399         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14400
14401         drm_framebuffer_cleanup(fb);
14402
14403         i915_gem_object_lock(obj);
14404         WARN_ON(!obj->framebuffer_references--);
14405         i915_gem_object_unlock(obj);
14406
14407         i915_gem_object_put(obj);
14408
14409         kfree(intel_fb);
14410 }
14411
14412 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14413                                                 struct drm_file *file,
14414                                                 unsigned int *handle)
14415 {
14416         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14417
14418         if (obj->userptr.mm) {
14419                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14420                 return -EINVAL;
14421         }
14422
14423         return drm_gem_handle_create(file, &obj->base, handle);
14424 }
14425
14426 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14427                                         struct drm_file *file,
14428                                         unsigned flags, unsigned color,
14429                                         struct drm_clip_rect *clips,
14430                                         unsigned num_clips)
14431 {
14432         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14433
14434         i915_gem_object_flush_if_display(obj);
14435         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14436
14437         return 0;
14438 }
14439
14440 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14441         .destroy = intel_user_framebuffer_destroy,
14442         .create_handle = intel_user_framebuffer_create_handle,
14443         .dirty = intel_user_framebuffer_dirty,
14444 };
14445
14446 static
14447 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14448                          u32 pixel_format, u64 fb_modifier)
14449 {
14450         struct intel_crtc *crtc;
14451         struct intel_plane *plane;
14452
14453         /*
14454          * We assume the primary plane for pipe A has
14455          * the highest stride limits of them all.
14456          */
14457         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14458         plane = to_intel_plane(crtc->base.primary);
14459
14460         return plane->max_stride(plane, pixel_format, fb_modifier,
14461                                  DRM_MODE_ROTATE_0);
14462 }
14463
14464 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14465                                   struct drm_i915_gem_object *obj,
14466                                   struct drm_mode_fb_cmd2 *mode_cmd)
14467 {
14468         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14469         struct drm_framebuffer *fb = &intel_fb->base;
14470         u32 pitch_limit;
14471         unsigned int tiling, stride;
14472         int ret = -EINVAL;
14473         int i;
14474
14475         i915_gem_object_lock(obj);
14476         obj->framebuffer_references++;
14477         tiling = i915_gem_object_get_tiling(obj);
14478         stride = i915_gem_object_get_stride(obj);
14479         i915_gem_object_unlock(obj);
14480
14481         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14482                 /*
14483                  * If there's a fence, enforce that
14484                  * the fb modifier and tiling mode match.
14485                  */
14486                 if (tiling != I915_TILING_NONE &&
14487                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14488                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14489                         goto err;
14490                 }
14491         } else {
14492                 if (tiling == I915_TILING_X) {
14493                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14494                 } else if (tiling == I915_TILING_Y) {
14495                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14496                         goto err;
14497                 }
14498         }
14499
14500         if (!drm_any_plane_has_format(&dev_priv->drm,
14501                                       mode_cmd->pixel_format,
14502                                       mode_cmd->modifier[0])) {
14503                 struct drm_format_name_buf format_name;
14504
14505                 DRM_DEBUG_KMS("unsupported pixel format %s / modifier 0x%llx\n",
14506                               drm_get_format_name(mode_cmd->pixel_format,
14507                                                   &format_name),
14508                               mode_cmd->modifier[0]);
14509                 goto err;
14510         }
14511
14512         /*
14513          * gen2/3 display engine uses the fence if present,
14514          * so the tiling mode must match the fb modifier exactly.
14515          */
14516         if (INTEL_GEN(dev_priv) < 4 &&
14517             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14518                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14519                 goto err;
14520         }
14521
14522         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->pixel_format,
14523                                            mode_cmd->modifier[0]);
14524         if (mode_cmd->pitches[0] > pitch_limit) {
14525                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14526                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14527                               "tiled" : "linear",
14528                               mode_cmd->pitches[0], pitch_limit);
14529                 goto err;
14530         }
14531
14532         /*
14533          * If there's a fence, enforce that
14534          * the fb pitch and fence stride match.
14535          */
14536         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14537                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14538                               mode_cmd->pitches[0], stride);
14539                 goto err;
14540         }
14541
14542         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14543         if (mode_cmd->offsets[0] != 0)
14544                 goto err;
14545
14546         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14547
14548         if (fb->format->format == DRM_FORMAT_NV12 &&
14549             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14550              fb->height < SKL_MIN_YUV_420_SRC_H ||
14551              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14552                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14553                 goto err;
14554         }
14555
14556         for (i = 0; i < fb->format->num_planes; i++) {
14557                 u32 stride_alignment;
14558
14559                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14560                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14561                         goto err;
14562                 }
14563
14564                 stride_alignment = intel_fb_stride_alignment(fb, i);
14565
14566                 /*
14567                  * Display WA #0531: skl,bxt,kbl,glk
14568                  *
14569                  * Render decompression and plane width > 3840
14570                  * combined with horizontal panning requires the
14571                  * plane stride to be a multiple of 4. We'll just
14572                  * require the entire fb to accommodate that to avoid
14573                  * potential runtime errors at plane configuration time.
14574                  */
14575                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14576                     is_ccs_modifier(fb->modifier))
14577                         stride_alignment *= 4;
14578
14579                 if (fb->pitches[i] & (stride_alignment - 1)) {
14580                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14581                                       i, fb->pitches[i], stride_alignment);
14582                         goto err;
14583                 }
14584
14585                 fb->obj[i] = &obj->base;
14586         }
14587
14588         ret = intel_fill_fb_info(dev_priv, fb);
14589         if (ret)
14590                 goto err;
14591
14592         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14593         if (ret) {
14594                 DRM_ERROR("framebuffer init failed %d\n", ret);
14595                 goto err;
14596         }
14597
14598         return 0;
14599
14600 err:
14601         i915_gem_object_lock(obj);
14602         obj->framebuffer_references--;
14603         i915_gem_object_unlock(obj);
14604         return ret;
14605 }
14606
14607 static struct drm_framebuffer *
14608 intel_user_framebuffer_create(struct drm_device *dev,
14609                               struct drm_file *filp,
14610                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14611 {
14612         struct drm_framebuffer *fb;
14613         struct drm_i915_gem_object *obj;
14614         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14615
14616         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14617         if (!obj)
14618                 return ERR_PTR(-ENOENT);
14619
14620         fb = intel_framebuffer_create(obj, &mode_cmd);
14621         if (IS_ERR(fb))
14622                 i915_gem_object_put(obj);
14623
14624         return fb;
14625 }
14626
14627 static void intel_atomic_state_free(struct drm_atomic_state *state)
14628 {
14629         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14630
14631         drm_atomic_state_default_release(state);
14632
14633         i915_sw_fence_fini(&intel_state->commit_ready);
14634
14635         kfree(state);
14636 }
14637
14638 static enum drm_mode_status
14639 intel_mode_valid(struct drm_device *dev,
14640                  const struct drm_display_mode *mode)
14641 {
14642         struct drm_i915_private *dev_priv = to_i915(dev);
14643         int hdisplay_max, htotal_max;
14644         int vdisplay_max, vtotal_max;
14645
14646         /*
14647          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14648          * of DBLSCAN modes to the output's mode list when they detect
14649          * the scaling mode property on the connector. And they don't
14650          * ask the kernel to validate those modes in any way until
14651          * modeset time at which point the client gets a protocol error.
14652          * So in order to not upset those clients we silently ignore the
14653          * DBLSCAN flag on such connectors. For other connectors we will
14654          * reject modes with the DBLSCAN flag in encoder->compute_config().
14655          * And we always reject DBLSCAN modes in connector->mode_valid()
14656          * as we never want such modes on the connector's mode list.
14657          */
14658
14659         if (mode->vscan > 1)
14660                 return MODE_NO_VSCAN;
14661
14662         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14663                 return MODE_H_ILLEGAL;
14664
14665         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14666                            DRM_MODE_FLAG_NCSYNC |
14667                            DRM_MODE_FLAG_PCSYNC))
14668                 return MODE_HSYNC;
14669
14670         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14671                            DRM_MODE_FLAG_PIXMUX |
14672                            DRM_MODE_FLAG_CLKDIV2))
14673                 return MODE_BAD;
14674
14675         if (INTEL_GEN(dev_priv) >= 9 ||
14676             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14677                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14678                 vdisplay_max = 4096;
14679                 htotal_max = 8192;
14680                 vtotal_max = 8192;
14681         } else if (INTEL_GEN(dev_priv) >= 3) {
14682                 hdisplay_max = 4096;
14683                 vdisplay_max = 4096;
14684                 htotal_max = 8192;
14685                 vtotal_max = 8192;
14686         } else {
14687                 hdisplay_max = 2048;
14688                 vdisplay_max = 2048;
14689                 htotal_max = 4096;
14690                 vtotal_max = 4096;
14691         }
14692
14693         if (mode->hdisplay > hdisplay_max ||
14694             mode->hsync_start > htotal_max ||
14695             mode->hsync_end > htotal_max ||
14696             mode->htotal > htotal_max)
14697                 return MODE_H_ILLEGAL;
14698
14699         if (mode->vdisplay > vdisplay_max ||
14700             mode->vsync_start > vtotal_max ||
14701             mode->vsync_end > vtotal_max ||
14702             mode->vtotal > vtotal_max)
14703                 return MODE_V_ILLEGAL;
14704
14705         return MODE_OK;
14706 }
14707
14708 static const struct drm_mode_config_funcs intel_mode_funcs = {
14709         .fb_create = intel_user_framebuffer_create,
14710         .get_format_info = intel_get_format_info,
14711         .output_poll_changed = intel_fbdev_output_poll_changed,
14712         .mode_valid = intel_mode_valid,
14713         .atomic_check = intel_atomic_check,
14714         .atomic_commit = intel_atomic_commit,
14715         .atomic_state_alloc = intel_atomic_state_alloc,
14716         .atomic_state_clear = intel_atomic_state_clear,
14717         .atomic_state_free = intel_atomic_state_free,
14718 };
14719
14720 /**
14721  * intel_init_display_hooks - initialize the display modesetting hooks
14722  * @dev_priv: device private
14723  */
14724 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14725 {
14726         intel_init_cdclk_hooks(dev_priv);
14727
14728         if (INTEL_GEN(dev_priv) >= 9) {
14729                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14730                 dev_priv->display.get_initial_plane_config =
14731                         skylake_get_initial_plane_config;
14732                 dev_priv->display.crtc_compute_clock =
14733                         haswell_crtc_compute_clock;
14734                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14735                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14736         } else if (HAS_DDI(dev_priv)) {
14737                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14738                 dev_priv->display.get_initial_plane_config =
14739                         i9xx_get_initial_plane_config;
14740                 dev_priv->display.crtc_compute_clock =
14741                         haswell_crtc_compute_clock;
14742                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14743                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14744         } else if (HAS_PCH_SPLIT(dev_priv)) {
14745                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14746                 dev_priv->display.get_initial_plane_config =
14747                         i9xx_get_initial_plane_config;
14748                 dev_priv->display.crtc_compute_clock =
14749                         ironlake_crtc_compute_clock;
14750                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14751                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14752         } else if (IS_CHERRYVIEW(dev_priv)) {
14753                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14754                 dev_priv->display.get_initial_plane_config =
14755                         i9xx_get_initial_plane_config;
14756                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14757                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14758                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14759         } else if (IS_VALLEYVIEW(dev_priv)) {
14760                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14761                 dev_priv->display.get_initial_plane_config =
14762                         i9xx_get_initial_plane_config;
14763                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14764                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14765                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14766         } else if (IS_G4X(dev_priv)) {
14767                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14768                 dev_priv->display.get_initial_plane_config =
14769                         i9xx_get_initial_plane_config;
14770                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14771                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14772                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14773         } else if (IS_PINEVIEW(dev_priv)) {
14774                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14775                 dev_priv->display.get_initial_plane_config =
14776                         i9xx_get_initial_plane_config;
14777                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14778                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14779                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14780         } else if (!IS_GEN2(dev_priv)) {
14781                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14782                 dev_priv->display.get_initial_plane_config =
14783                         i9xx_get_initial_plane_config;
14784                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14785                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14786                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14787         } else {
14788                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14789                 dev_priv->display.get_initial_plane_config =
14790                         i9xx_get_initial_plane_config;
14791                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14792                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14793                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14794         }
14795
14796         if (IS_GEN5(dev_priv)) {
14797                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14798         } else if (IS_GEN6(dev_priv)) {
14799                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14800         } else if (IS_IVYBRIDGE(dev_priv)) {
14801                 /* FIXME: detect B0+ stepping and use auto training */
14802                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14803         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14804                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14805         }
14806
14807         if (INTEL_GEN(dev_priv) >= 9)
14808                 dev_priv->display.update_crtcs = skl_update_crtcs;
14809         else
14810                 dev_priv->display.update_crtcs = intel_update_crtcs;
14811 }
14812
14813 /* Disable the VGA plane that we never use */
14814 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14815 {
14816         struct pci_dev *pdev = dev_priv->drm.pdev;
14817         u8 sr1;
14818         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14819
14820         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14821         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14822         outb(SR01, VGA_SR_INDEX);
14823         sr1 = inb(VGA_SR_DATA);
14824         outb(sr1 | 1<<5, VGA_SR_DATA);
14825         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14826         udelay(300);
14827
14828         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14829         POSTING_READ(vga_reg);
14830 }
14831
14832 void intel_modeset_init_hw(struct drm_device *dev)
14833 {
14834         struct drm_i915_private *dev_priv = to_i915(dev);
14835
14836         intel_update_cdclk(dev_priv);
14837         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14838         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14839 }
14840
14841 /*
14842  * Calculate what we think the watermarks should be for the state we've read
14843  * out of the hardware and then immediately program those watermarks so that
14844  * we ensure the hardware settings match our internal state.
14845  *
14846  * We can calculate what we think WM's should be by creating a duplicate of the
14847  * current state (which was constructed during hardware readout) and running it
14848  * through the atomic check code to calculate new watermark values in the
14849  * state object.
14850  */
14851 static void sanitize_watermarks(struct drm_device *dev)
14852 {
14853         struct drm_i915_private *dev_priv = to_i915(dev);
14854         struct drm_atomic_state *state;
14855         struct intel_atomic_state *intel_state;
14856         struct drm_crtc *crtc;
14857         struct drm_crtc_state *cstate;
14858         struct drm_modeset_acquire_ctx ctx;
14859         int ret;
14860         int i;
14861
14862         /* Only supported on platforms that use atomic watermark design */
14863         if (!dev_priv->display.optimize_watermarks)
14864                 return;
14865
14866         /*
14867          * We need to hold connection_mutex before calling duplicate_state so
14868          * that the connector loop is protected.
14869          */
14870         drm_modeset_acquire_init(&ctx, 0);
14871 retry:
14872         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14873         if (ret == -EDEADLK) {
14874                 drm_modeset_backoff(&ctx);
14875                 goto retry;
14876         } else if (WARN_ON(ret)) {
14877                 goto fail;
14878         }
14879
14880         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14881         if (WARN_ON(IS_ERR(state)))
14882                 goto fail;
14883
14884         intel_state = to_intel_atomic_state(state);
14885
14886         /*
14887          * Hardware readout is the only time we don't want to calculate
14888          * intermediate watermarks (since we don't trust the current
14889          * watermarks).
14890          */
14891         if (!HAS_GMCH_DISPLAY(dev_priv))
14892                 intel_state->skip_intermediate_wm = true;
14893
14894         ret = intel_atomic_check(dev, state);
14895         if (ret) {
14896                 /*
14897                  * If we fail here, it means that the hardware appears to be
14898                  * programmed in a way that shouldn't be possible, given our
14899                  * understanding of watermark requirements.  This might mean a
14900                  * mistake in the hardware readout code or a mistake in the
14901                  * watermark calculations for a given platform.  Raise a WARN
14902                  * so that this is noticeable.
14903                  *
14904                  * If this actually happens, we'll have to just leave the
14905                  * BIOS-programmed watermarks untouched and hope for the best.
14906                  */
14907                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14908                 goto put_state;
14909         }
14910
14911         /* Write calculated watermark values back */
14912         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14913                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14914
14915                 cs->wm.need_postvbl_update = true;
14916                 dev_priv->display.optimize_watermarks(intel_state, cs);
14917
14918                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14919         }
14920
14921 put_state:
14922         drm_atomic_state_put(state);
14923 fail:
14924         drm_modeset_drop_locks(&ctx);
14925         drm_modeset_acquire_fini(&ctx);
14926 }
14927
14928 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14929 {
14930         if (IS_GEN5(dev_priv)) {
14931                 u32 fdi_pll_clk =
14932                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14933
14934                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14935         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14936                 dev_priv->fdi_pll_freq = 270000;
14937         } else {
14938                 return;
14939         }
14940
14941         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14942 }
14943
14944 static int intel_initial_commit(struct drm_device *dev)
14945 {
14946         struct drm_atomic_state *state = NULL;
14947         struct drm_modeset_acquire_ctx ctx;
14948         struct drm_crtc *crtc;
14949         struct drm_crtc_state *crtc_state;
14950         int ret = 0;
14951
14952         state = drm_atomic_state_alloc(dev);
14953         if (!state)
14954                 return -ENOMEM;
14955
14956         drm_modeset_acquire_init(&ctx, 0);
14957
14958 retry:
14959         state->acquire_ctx = &ctx;
14960
14961         drm_for_each_crtc(crtc, dev) {
14962                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
14963                 if (IS_ERR(crtc_state)) {
14964                         ret = PTR_ERR(crtc_state);
14965                         goto out;
14966                 }
14967
14968                 if (crtc_state->active) {
14969                         ret = drm_atomic_add_affected_planes(state, crtc);
14970                         if (ret)
14971                                 goto out;
14972
14973                         /*
14974                          * FIXME hack to force a LUT update to avoid the
14975                          * plane update forcing the pipe gamma on without
14976                          * having a proper LUT loaded. Remove once we
14977                          * have readout for pipe gamma enable.
14978                          */
14979                         crtc_state->color_mgmt_changed = true;
14980                 }
14981         }
14982
14983         ret = drm_atomic_commit(state);
14984
14985 out:
14986         if (ret == -EDEADLK) {
14987                 drm_atomic_state_clear(state);
14988                 drm_modeset_backoff(&ctx);
14989                 goto retry;
14990         }
14991
14992         drm_atomic_state_put(state);
14993
14994         drm_modeset_drop_locks(&ctx);
14995         drm_modeset_acquire_fini(&ctx);
14996
14997         return ret;
14998 }
14999
15000 int intel_modeset_init(struct drm_device *dev)
15001 {
15002         struct drm_i915_private *dev_priv = to_i915(dev);
15003         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15004         enum pipe pipe;
15005         struct intel_crtc *crtc;
15006         int ret;
15007
15008         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15009
15010         drm_mode_config_init(dev);
15011
15012         dev->mode_config.min_width = 0;
15013         dev->mode_config.min_height = 0;
15014
15015         dev->mode_config.preferred_depth = 24;
15016         dev->mode_config.prefer_shadow = 1;
15017
15018         dev->mode_config.allow_fb_modifiers = true;
15019
15020         dev->mode_config.funcs = &intel_mode_funcs;
15021
15022         init_llist_head(&dev_priv->atomic_helper.free_list);
15023         INIT_WORK(&dev_priv->atomic_helper.free_work,
15024                   intel_atomic_helper_free_state_worker);
15025
15026         intel_init_quirks(dev_priv);
15027
15028         intel_fbc_init(dev_priv);
15029
15030         intel_init_pm(dev_priv);
15031
15032         /*
15033          * There may be no VBT; and if the BIOS enabled SSC we can
15034          * just keep using it to avoid unnecessary flicker.  Whereas if the
15035          * BIOS isn't using it, don't assume it will work even if the VBT
15036          * indicates as much.
15037          */
15038         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15039                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15040                                             DREF_SSC1_ENABLE);
15041
15042                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15043                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15044                                      bios_lvds_use_ssc ? "en" : "dis",
15045                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15046                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15047                 }
15048         }
15049
15050         /* maximum framebuffer dimensions */
15051         if (IS_GEN2(dev_priv)) {
15052                 dev->mode_config.max_width = 2048;
15053                 dev->mode_config.max_height = 2048;
15054         } else if (IS_GEN3(dev_priv)) {
15055                 dev->mode_config.max_width = 4096;
15056                 dev->mode_config.max_height = 4096;
15057         } else {
15058                 dev->mode_config.max_width = 8192;
15059                 dev->mode_config.max_height = 8192;
15060         }
15061
15062         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15063                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15064                 dev->mode_config.cursor_height = 1023;
15065         } else if (IS_GEN2(dev_priv)) {
15066                 dev->mode_config.cursor_width = 64;
15067                 dev->mode_config.cursor_height = 64;
15068         } else {
15069                 dev->mode_config.cursor_width = 256;
15070                 dev->mode_config.cursor_height = 256;
15071         }
15072
15073         dev->mode_config.fb_base = ggtt->gmadr.start;
15074
15075         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15076                       INTEL_INFO(dev_priv)->num_pipes,
15077                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15078
15079         for_each_pipe(dev_priv, pipe) {
15080                 ret = intel_crtc_init(dev_priv, pipe);
15081                 if (ret) {
15082                         drm_mode_config_cleanup(dev);
15083                         return ret;
15084                 }
15085         }
15086
15087         intel_shared_dpll_init(dev);
15088         intel_update_fdi_pll_freq(dev_priv);
15089
15090         intel_update_czclk(dev_priv);
15091         intel_modeset_init_hw(dev);
15092
15093         if (dev_priv->max_cdclk_freq == 0)
15094                 intel_update_max_cdclk(dev_priv);
15095
15096         /* Just disable it once at startup */
15097         i915_disable_vga(dev_priv);
15098         intel_setup_outputs(dev_priv);
15099
15100         drm_modeset_lock_all(dev);
15101         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15102         drm_modeset_unlock_all(dev);
15103
15104         for_each_intel_crtc(dev, crtc) {
15105                 struct intel_initial_plane_config plane_config = {};
15106
15107                 if (!crtc->active)
15108                         continue;
15109
15110                 /*
15111                  * Note that reserving the BIOS fb up front prevents us
15112                  * from stuffing other stolen allocations like the ring
15113                  * on top.  This prevents some ugliness at boot time, and
15114                  * can even allow for smooth boot transitions if the BIOS
15115                  * fb is large enough for the active pipe configuration.
15116                  */
15117                 dev_priv->display.get_initial_plane_config(crtc,
15118                                                            &plane_config);
15119
15120                 /*
15121                  * If the fb is shared between multiple heads, we'll
15122                  * just get the first one.
15123                  */
15124                 intel_find_initial_plane_obj(crtc, &plane_config);
15125         }
15126
15127         /*
15128          * Make sure hardware watermarks really match the state we read out.
15129          * Note that we need to do this after reconstructing the BIOS fb's
15130          * since the watermark calculation done here will use pstate->fb.
15131          */
15132         if (!HAS_GMCH_DISPLAY(dev_priv))
15133                 sanitize_watermarks(dev);
15134
15135         /*
15136          * Force all active planes to recompute their states. So that on
15137          * mode_setcrtc after probe, all the intel_plane_state variables
15138          * are already calculated and there is no assert_plane warnings
15139          * during bootup.
15140          */
15141         ret = intel_initial_commit(dev);
15142         if (ret)
15143                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15144
15145         return 0;
15146 }
15147
15148 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15149 {
15150         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15151         /* 640x480@60Hz, ~25175 kHz */
15152         struct dpll clock = {
15153                 .m1 = 18,
15154                 .m2 = 7,
15155                 .p1 = 13,
15156                 .p2 = 4,
15157                 .n = 2,
15158         };
15159         u32 dpll, fp;
15160         int i;
15161
15162         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15163
15164         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15165                       pipe_name(pipe), clock.vco, clock.dot);
15166
15167         fp = i9xx_dpll_compute_fp(&clock);
15168         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15169                 DPLL_VGA_MODE_DIS |
15170                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15171                 PLL_P2_DIVIDE_BY_4 |
15172                 PLL_REF_INPUT_DREFCLK |
15173                 DPLL_VCO_ENABLE;
15174
15175         I915_WRITE(FP0(pipe), fp);
15176         I915_WRITE(FP1(pipe), fp);
15177
15178         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15179         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15180         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15181         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15182         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15183         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15184         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15185
15186         /*
15187          * Apparently we need to have VGA mode enabled prior to changing
15188          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15189          * dividers, even though the register value does change.
15190          */
15191         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15192         I915_WRITE(DPLL(pipe), dpll);
15193
15194         /* Wait for the clocks to stabilize. */
15195         POSTING_READ(DPLL(pipe));
15196         udelay(150);
15197
15198         /* The pixel multiplier can only be updated once the
15199          * DPLL is enabled and the clocks are stable.
15200          *
15201          * So write it again.
15202          */
15203         I915_WRITE(DPLL(pipe), dpll);
15204
15205         /* We do this three times for luck */
15206         for (i = 0; i < 3 ; i++) {
15207                 I915_WRITE(DPLL(pipe), dpll);
15208                 POSTING_READ(DPLL(pipe));
15209                 udelay(150); /* wait for warmup */
15210         }
15211
15212         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15213         POSTING_READ(PIPECONF(pipe));
15214
15215         intel_wait_for_pipe_scanline_moving(crtc);
15216 }
15217
15218 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15219 {
15220         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15221
15222         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15223                       pipe_name(pipe));
15224
15225         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15226         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15227         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15228         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15229         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15230
15231         I915_WRITE(PIPECONF(pipe), 0);
15232         POSTING_READ(PIPECONF(pipe));
15233
15234         intel_wait_for_pipe_scanline_stopped(crtc);
15235
15236         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15237         POSTING_READ(DPLL(pipe));
15238 }
15239
15240 static void
15241 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15242 {
15243         struct intel_crtc *crtc;
15244
15245         if (INTEL_GEN(dev_priv) >= 4)
15246                 return;
15247
15248         for_each_intel_crtc(&dev_priv->drm, crtc) {
15249                 struct intel_plane *plane =
15250                         to_intel_plane(crtc->base.primary);
15251                 struct intel_crtc *plane_crtc;
15252                 enum pipe pipe;
15253
15254                 if (!plane->get_hw_state(plane, &pipe))
15255                         continue;
15256
15257                 if (pipe == crtc->pipe)
15258                         continue;
15259
15260                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
15261                               plane->base.base.id, plane->base.name);
15262
15263                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15264                 intel_plane_disable_noatomic(plane_crtc, plane);
15265         }
15266 }
15267
15268 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15269 {
15270         struct drm_device *dev = crtc->base.dev;
15271         struct intel_encoder *encoder;
15272
15273         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15274                 return true;
15275
15276         return false;
15277 }
15278
15279 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15280 {
15281         struct drm_device *dev = encoder->base.dev;
15282         struct intel_connector *connector;
15283
15284         for_each_connector_on_encoder(dev, &encoder->base, connector)
15285                 return connector;
15286
15287         return NULL;
15288 }
15289
15290 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15291                               enum pipe pch_transcoder)
15292 {
15293         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15294                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15295 }
15296
15297 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15298                                 struct drm_modeset_acquire_ctx *ctx)
15299 {
15300         struct drm_device *dev = crtc->base.dev;
15301         struct drm_i915_private *dev_priv = to_i915(dev);
15302         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
15303         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
15304
15305         /* Clear any frame start delays used for debugging left by the BIOS */
15306         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15307                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15308
15309                 I915_WRITE(reg,
15310                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15311         }
15312
15313         if (crtc_state->base.active) {
15314                 struct intel_plane *plane;
15315
15316                 /* Disable everything but the primary plane */
15317                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15318                         const struct intel_plane_state *plane_state =
15319                                 to_intel_plane_state(plane->base.state);
15320
15321                         if (plane_state->base.visible &&
15322                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15323                                 intel_plane_disable_noatomic(crtc, plane);
15324                 }
15325         }
15326
15327         /* Adjust the state of the output pipe according to whether we
15328          * have active connectors/encoders. */
15329         if (crtc_state->base.active && !intel_crtc_has_encoders(crtc))
15330                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15331
15332         if (crtc_state->base.active || HAS_GMCH_DISPLAY(dev_priv)) {
15333                 /*
15334                  * We start out with underrun reporting disabled to avoid races.
15335                  * For correct bookkeeping mark this on active crtcs.
15336                  *
15337                  * Also on gmch platforms we dont have any hardware bits to
15338                  * disable the underrun reporting. Which means we need to start
15339                  * out with underrun reporting disabled also on inactive pipes,
15340                  * since otherwise we'll complain about the garbage we read when
15341                  * e.g. coming up after runtime pm.
15342                  *
15343                  * No protection against concurrent access is required - at
15344                  * worst a fifo underrun happens which also sets this to false.
15345                  */
15346                 crtc->cpu_fifo_underrun_disabled = true;
15347                 /*
15348                  * We track the PCH trancoder underrun reporting state
15349                  * within the crtc. With crtc for pipe A housing the underrun
15350                  * reporting state for PCH transcoder A, crtc for pipe B housing
15351                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15352                  * and marking underrun reporting as disabled for the non-existing
15353                  * PCH transcoders B and C would prevent enabling the south
15354                  * error interrupt (see cpt_can_enable_serr_int()).
15355                  */
15356                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15357                         crtc->pch_fifo_underrun_disabled = true;
15358         }
15359 }
15360
15361 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15362 {
15363         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
15364         struct intel_connector *connector;
15365
15366         /* We need to check both for a crtc link (meaning that the
15367          * encoder is active and trying to read from a pipe) and the
15368          * pipe itself being active. */
15369         bool has_active_crtc = encoder->base.crtc &&
15370                 to_intel_crtc(encoder->base.crtc)->active;
15371
15372         connector = intel_encoder_find_connector(encoder);
15373         if (connector && !has_active_crtc) {
15374                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15375                               encoder->base.base.id,
15376                               encoder->base.name);
15377
15378                 /* Connector is active, but has no active pipe. This is
15379                  * fallout from our resume register restoring. Disable
15380                  * the encoder manually again. */
15381                 if (encoder->base.crtc) {
15382                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15383
15384                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15385                                       encoder->base.base.id,
15386                                       encoder->base.name);
15387                         if (encoder->disable)
15388                                 encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15389                         if (encoder->post_disable)
15390                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15391                 }
15392                 encoder->base.crtc = NULL;
15393
15394                 /* Inconsistent output/port/pipe state happens presumably due to
15395                  * a bug in one of the get_hw_state functions. Or someplace else
15396                  * in our code, like the register restore mess on resume. Clamp
15397                  * things to off as a safer default. */
15398
15399                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15400                 connector->base.encoder = NULL;
15401         }
15402
15403         /* notify opregion of the sanitized encoder state */
15404         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15405
15406         if (INTEL_GEN(dev_priv) >= 11)
15407                 icl_sanitize_encoder_pll_mapping(encoder);
15408 }
15409
15410 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15411 {
15412         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15413
15414         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15415                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15416                 i915_disable_vga(dev_priv);
15417         }
15418 }
15419
15420 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15421 {
15422         /* This function can be called both from intel_modeset_setup_hw_state or
15423          * at a very early point in our resume sequence, where the power well
15424          * structures are not yet restored. Since this function is at a very
15425          * paranoid "someone might have enabled VGA while we were not looking"
15426          * level, just check if the power well is enabled instead of trying to
15427          * follow the "don't touch the power well if we don't need it" policy
15428          * the rest of the driver uses. */
15429         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15430                 return;
15431
15432         i915_redisable_vga_power_on(dev_priv);
15433
15434         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15435 }
15436
15437 /* FIXME read out full plane state for all planes */
15438 static void readout_plane_state(struct drm_i915_private *dev_priv)
15439 {
15440         struct intel_plane *plane;
15441         struct intel_crtc *crtc;
15442
15443         for_each_intel_plane(&dev_priv->drm, plane) {
15444                 struct intel_plane_state *plane_state =
15445                         to_intel_plane_state(plane->base.state);
15446                 struct intel_crtc_state *crtc_state;
15447                 enum pipe pipe = PIPE_A;
15448                 bool visible;
15449
15450                 visible = plane->get_hw_state(plane, &pipe);
15451
15452                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15453                 crtc_state = to_intel_crtc_state(crtc->base.state);
15454
15455                 intel_set_plane_visible(crtc_state, plane_state, visible);
15456
15457                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
15458                               plane->base.base.id, plane->base.name,
15459                               enableddisabled(visible), pipe_name(pipe));
15460         }
15461
15462         for_each_intel_crtc(&dev_priv->drm, crtc) {
15463                 struct intel_crtc_state *crtc_state =
15464                         to_intel_crtc_state(crtc->base.state);
15465
15466                 fixup_active_planes(crtc_state);
15467         }
15468 }
15469
15470 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15471 {
15472         struct drm_i915_private *dev_priv = to_i915(dev);
15473         enum pipe pipe;
15474         struct intel_crtc *crtc;
15475         struct intel_encoder *encoder;
15476         struct intel_connector *connector;
15477         struct drm_connector_list_iter conn_iter;
15478         int i;
15479
15480         dev_priv->active_crtcs = 0;
15481
15482         for_each_intel_crtc(dev, crtc) {
15483                 struct intel_crtc_state *crtc_state =
15484                         to_intel_crtc_state(crtc->base.state);
15485
15486                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15487                 memset(crtc_state, 0, sizeof(*crtc_state));
15488                 crtc_state->base.crtc = &crtc->base;
15489
15490                 crtc_state->base.active = crtc_state->base.enable =
15491                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15492
15493                 crtc->base.enabled = crtc_state->base.enable;
15494                 crtc->active = crtc_state->base.active;
15495
15496                 if (crtc_state->base.active)
15497                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15498
15499                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15500                               crtc->base.base.id, crtc->base.name,
15501                               enableddisabled(crtc_state->base.active));
15502         }
15503
15504         readout_plane_state(dev_priv);
15505
15506         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15507                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15508
15509                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15510                                                         &pll->state.hw_state);
15511                 pll->state.crtc_mask = 0;
15512                 for_each_intel_crtc(dev, crtc) {
15513                         struct intel_crtc_state *crtc_state =
15514                                 to_intel_crtc_state(crtc->base.state);
15515
15516                         if (crtc_state->base.active &&
15517                             crtc_state->shared_dpll == pll)
15518                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15519                 }
15520                 pll->active_mask = pll->state.crtc_mask;
15521
15522                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15523                               pll->info->name, pll->state.crtc_mask, pll->on);
15524         }
15525
15526         for_each_intel_encoder(dev, encoder) {
15527                 pipe = 0;
15528
15529                 if (encoder->get_hw_state(encoder, &pipe)) {
15530                         struct intel_crtc_state *crtc_state;
15531
15532                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15533                         crtc_state = to_intel_crtc_state(crtc->base.state);
15534
15535                         encoder->base.crtc = &crtc->base;
15536                         encoder->get_config(encoder, crtc_state);
15537                 } else {
15538                         encoder->base.crtc = NULL;
15539                 }
15540
15541                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15542                               encoder->base.base.id, encoder->base.name,
15543                               enableddisabled(encoder->base.crtc),
15544                               pipe_name(pipe));
15545         }
15546
15547         drm_connector_list_iter_begin(dev, &conn_iter);
15548         for_each_intel_connector_iter(connector, &conn_iter) {
15549                 if (connector->get_hw_state(connector)) {
15550                         connector->base.dpms = DRM_MODE_DPMS_ON;
15551
15552                         encoder = connector->encoder;
15553                         connector->base.encoder = &encoder->base;
15554
15555                         if (encoder->base.crtc &&
15556                             encoder->base.crtc->state->active) {
15557                                 /*
15558                                  * This has to be done during hardware readout
15559                                  * because anything calling .crtc_disable may
15560                                  * rely on the connector_mask being accurate.
15561                                  */
15562                                 encoder->base.crtc->state->connector_mask |=
15563                                         drm_connector_mask(&connector->base);
15564                                 encoder->base.crtc->state->encoder_mask |=
15565                                         drm_encoder_mask(&encoder->base);
15566                         }
15567
15568                 } else {
15569                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15570                         connector->base.encoder = NULL;
15571                 }
15572                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15573                               connector->base.base.id, connector->base.name,
15574                               enableddisabled(connector->base.encoder));
15575         }
15576         drm_connector_list_iter_end(&conn_iter);
15577
15578         for_each_intel_crtc(dev, crtc) {
15579                 struct intel_crtc_state *crtc_state =
15580                         to_intel_crtc_state(crtc->base.state);
15581                 int min_cdclk = 0;
15582
15583                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15584                 if (crtc_state->base.active) {
15585                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15586                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15587                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15588                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15589                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15590
15591                         /*
15592                          * The initial mode needs to be set in order to keep
15593                          * the atomic core happy. It wants a valid mode if the
15594                          * crtc's enabled, so we do the above call.
15595                          *
15596                          * But we don't set all the derived state fully, hence
15597                          * set a flag to indicate that a full recalculation is
15598                          * needed on the next commit.
15599                          */
15600                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15601
15602                         intel_crtc_compute_pixel_rate(crtc_state);
15603
15604                         if (dev_priv->display.modeset_calc_cdclk) {
15605                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15606                                 if (WARN_ON(min_cdclk < 0))
15607                                         min_cdclk = 0;
15608                         }
15609
15610                         drm_calc_timestamping_constants(&crtc->base,
15611                                                         &crtc_state->base.adjusted_mode);
15612                         update_scanline_offset(crtc_state);
15613                 }
15614
15615                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15616                 dev_priv->min_voltage_level[crtc->pipe] =
15617                         crtc_state->min_voltage_level;
15618
15619                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15620         }
15621 }
15622
15623 static void
15624 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15625 {
15626         struct intel_encoder *encoder;
15627
15628         for_each_intel_encoder(&dev_priv->drm, encoder) {
15629                 u64 get_domains;
15630                 enum intel_display_power_domain domain;
15631                 struct intel_crtc_state *crtc_state;
15632
15633                 if (!encoder->get_power_domains)
15634                         continue;
15635
15636                 /*
15637                  * MST-primary and inactive encoders don't have a crtc state
15638                  * and neither of these require any power domain references.
15639                  */
15640                 if (!encoder->base.crtc)
15641                         continue;
15642
15643                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15644                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15645                 for_each_power_domain(domain, get_domains)
15646                         intel_display_power_get(dev_priv, domain);
15647         }
15648 }
15649
15650 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15651 {
15652         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15653         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15654                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15655                            DARBF_GATING_DIS);
15656
15657         if (IS_HASWELL(dev_priv)) {
15658                 /*
15659                  * WaRsPkgCStateDisplayPMReq:hsw
15660                  * System hang if this isn't done before disabling all planes!
15661                  */
15662                 I915_WRITE(CHICKEN_PAR1_1,
15663                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15664         }
15665 }
15666
15667 static void ibx_sanitize_pch_hdmi_port(struct drm_i915_private *dev_priv,
15668                                        enum port port, i915_reg_t hdmi_reg)
15669 {
15670         u32 val = I915_READ(hdmi_reg);
15671
15672         if (val & SDVO_ENABLE ||
15673             (val & SDVO_PIPE_SEL_MASK) == SDVO_PIPE_SEL(PIPE_A))
15674                 return;
15675
15676         DRM_DEBUG_KMS("Sanitizing transcoder select for HDMI %c\n",
15677                       port_name(port));
15678
15679         val &= ~SDVO_PIPE_SEL_MASK;
15680         val |= SDVO_PIPE_SEL(PIPE_A);
15681
15682         I915_WRITE(hdmi_reg, val);
15683 }
15684
15685 static void ibx_sanitize_pch_dp_port(struct drm_i915_private *dev_priv,
15686                                      enum port port, i915_reg_t dp_reg)
15687 {
15688         u32 val = I915_READ(dp_reg);
15689
15690         if (val & DP_PORT_EN ||
15691             (val & DP_PIPE_SEL_MASK) == DP_PIPE_SEL(PIPE_A))
15692                 return;
15693
15694         DRM_DEBUG_KMS("Sanitizing transcoder select for DP %c\n",
15695                       port_name(port));
15696
15697         val &= ~DP_PIPE_SEL_MASK;
15698         val |= DP_PIPE_SEL(PIPE_A);
15699
15700         I915_WRITE(dp_reg, val);
15701 }
15702
15703 static void ibx_sanitize_pch_ports(struct drm_i915_private *dev_priv)
15704 {
15705         /*
15706          * The BIOS may select transcoder B on some of the PCH
15707          * ports even it doesn't enable the port. This would trip
15708          * assert_pch_dp_disabled() and assert_pch_hdmi_disabled().
15709          * Sanitize the transcoder select bits to prevent that. We
15710          * assume that the BIOS never actually enabled the port,
15711          * because if it did we'd actually have to toggle the port
15712          * on and back off to make the transcoder A select stick
15713          * (see. intel_dp_link_down(), intel_disable_hdmi(),
15714          * intel_disable_sdvo()).
15715          */
15716         ibx_sanitize_pch_dp_port(dev_priv, PORT_B, PCH_DP_B);
15717         ibx_sanitize_pch_dp_port(dev_priv, PORT_C, PCH_DP_C);
15718         ibx_sanitize_pch_dp_port(dev_priv, PORT_D, PCH_DP_D);
15719
15720         /* PCH SDVOB multiplex with HDMIB */
15721         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_B, PCH_HDMIB);
15722         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_C, PCH_HDMIC);
15723         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_D, PCH_HDMID);
15724 }
15725
15726 /* Scan out the current hw modeset state,
15727  * and sanitizes it to the current state
15728  */
15729 static void
15730 intel_modeset_setup_hw_state(struct drm_device *dev,
15731                              struct drm_modeset_acquire_ctx *ctx)
15732 {
15733         struct drm_i915_private *dev_priv = to_i915(dev);
15734         struct intel_crtc *crtc;
15735         struct intel_crtc_state *crtc_state;
15736         struct intel_encoder *encoder;
15737         int i;
15738
15739         intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15740
15741         intel_early_display_was(dev_priv);
15742         intel_modeset_readout_hw_state(dev);
15743
15744         /* HW state is read out, now we need to sanitize this mess. */
15745         get_encoder_power_domains(dev_priv);
15746
15747         if (HAS_PCH_IBX(dev_priv))
15748                 ibx_sanitize_pch_ports(dev_priv);
15749
15750         /*
15751          * intel_sanitize_plane_mapping() may need to do vblank
15752          * waits, so we need vblank interrupts restored beforehand.
15753          */
15754         for_each_intel_crtc(&dev_priv->drm, crtc) {
15755                 drm_crtc_vblank_reset(&crtc->base);
15756
15757                 if (crtc->base.state->active)
15758                         drm_crtc_vblank_on(&crtc->base);
15759         }
15760
15761         intel_sanitize_plane_mapping(dev_priv);
15762
15763         for_each_intel_encoder(dev, encoder)
15764                 intel_sanitize_encoder(encoder);
15765
15766         for_each_intel_crtc(&dev_priv->drm, crtc) {
15767                 crtc_state = to_intel_crtc_state(crtc->base.state);
15768                 intel_sanitize_crtc(crtc, ctx);
15769                 intel_dump_pipe_config(crtc, crtc_state,
15770                                        "[setup_hw_state]");
15771         }
15772
15773         intel_modeset_update_connector_atomic_state(dev);
15774
15775         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15776                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15777
15778                 if (!pll->on || pll->active_mask)
15779                         continue;
15780
15781                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15782                               pll->info->name);
15783
15784                 pll->info->funcs->disable(dev_priv, pll);
15785                 pll->on = false;
15786         }
15787
15788         if (IS_G4X(dev_priv)) {
15789                 g4x_wm_get_hw_state(dev);
15790                 g4x_wm_sanitize(dev_priv);
15791         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15792                 vlv_wm_get_hw_state(dev);
15793                 vlv_wm_sanitize(dev_priv);
15794         } else if (INTEL_GEN(dev_priv) >= 9) {
15795                 skl_wm_get_hw_state(dev);
15796         } else if (HAS_PCH_SPLIT(dev_priv)) {
15797                 ilk_wm_get_hw_state(dev);
15798         }
15799
15800         for_each_intel_crtc(dev, crtc) {
15801                 u64 put_domains;
15802
15803                 crtc_state = to_intel_crtc_state(crtc->base.state);
15804                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc_state);
15805                 if (WARN_ON(put_domains))
15806                         modeset_put_power_domains(dev_priv, put_domains);
15807         }
15808
15809         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
15810
15811         intel_fbc_init_pipe_state(dev_priv);
15812 }
15813
15814 void intel_display_resume(struct drm_device *dev)
15815 {
15816         struct drm_i915_private *dev_priv = to_i915(dev);
15817         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15818         struct drm_modeset_acquire_ctx ctx;
15819         int ret;
15820
15821         dev_priv->modeset_restore_state = NULL;
15822         if (state)
15823                 state->acquire_ctx = &ctx;
15824
15825         drm_modeset_acquire_init(&ctx, 0);
15826
15827         while (1) {
15828                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15829                 if (ret != -EDEADLK)
15830                         break;
15831
15832                 drm_modeset_backoff(&ctx);
15833         }
15834
15835         if (!ret)
15836                 ret = __intel_display_resume(dev, state, &ctx);
15837
15838         intel_enable_ipc(dev_priv);
15839         drm_modeset_drop_locks(&ctx);
15840         drm_modeset_acquire_fini(&ctx);
15841
15842         if (ret)
15843                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15844         if (state)
15845                 drm_atomic_state_put(state);
15846 }
15847
15848 static void intel_hpd_poll_fini(struct drm_device *dev)
15849 {
15850         struct intel_connector *connector;
15851         struct drm_connector_list_iter conn_iter;
15852
15853         /* Kill all the work that may have been queued by hpd. */
15854         drm_connector_list_iter_begin(dev, &conn_iter);
15855         for_each_intel_connector_iter(connector, &conn_iter) {
15856                 if (connector->modeset_retry_work.func)
15857                         cancel_work_sync(&connector->modeset_retry_work);
15858                 if (connector->hdcp.shim) {
15859                         cancel_delayed_work_sync(&connector->hdcp.check_work);
15860                         cancel_work_sync(&connector->hdcp.prop_work);
15861                 }
15862         }
15863         drm_connector_list_iter_end(&conn_iter);
15864 }
15865
15866 void intel_modeset_cleanup(struct drm_device *dev)
15867 {
15868         struct drm_i915_private *dev_priv = to_i915(dev);
15869
15870         flush_workqueue(dev_priv->modeset_wq);
15871
15872         flush_work(&dev_priv->atomic_helper.free_work);
15873         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15874
15875         /*
15876          * Interrupts and polling as the first thing to avoid creating havoc.
15877          * Too much stuff here (turning of connectors, ...) would
15878          * experience fancy races otherwise.
15879          */
15880         intel_irq_uninstall(dev_priv);
15881
15882         /*
15883          * Due to the hpd irq storm handling the hotplug work can re-arm the
15884          * poll handlers. Hence disable polling after hpd handling is shut down.
15885          */
15886         intel_hpd_poll_fini(dev);
15887
15888         /* poll work can call into fbdev, hence clean that up afterwards */
15889         intel_fbdev_fini(dev_priv);
15890
15891         intel_unregister_dsm_handler();
15892
15893         intel_fbc_global_disable(dev_priv);
15894
15895         /* flush any delayed tasks or pending work */
15896         flush_scheduled_work();
15897
15898         drm_mode_config_cleanup(dev);
15899
15900         intel_overlay_cleanup(dev_priv);
15901
15902         intel_teardown_gmbus(dev_priv);
15903
15904         destroy_workqueue(dev_priv->modeset_wq);
15905
15906         intel_fbc_cleanup_cfb(dev_priv);
15907 }
15908
15909 /*
15910  * set vga decode state - true == enable VGA decode
15911  */
15912 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15913 {
15914         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15915         u16 gmch_ctrl;
15916
15917         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15918                 DRM_ERROR("failed to read control word\n");
15919                 return -EIO;
15920         }
15921
15922         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15923                 return 0;
15924
15925         if (state)
15926                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15927         else
15928                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15929
15930         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15931                 DRM_ERROR("failed to write control word\n");
15932                 return -EIO;
15933         }
15934
15935         return 0;
15936 }
15937
15938 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15939
15940 struct intel_display_error_state {
15941
15942         u32 power_well_driver;
15943
15944         int num_transcoders;
15945
15946         struct intel_cursor_error_state {
15947                 u32 control;
15948                 u32 position;
15949                 u32 base;
15950                 u32 size;
15951         } cursor[I915_MAX_PIPES];
15952
15953         struct intel_pipe_error_state {
15954                 bool power_domain_on;
15955                 u32 source;
15956                 u32 stat;
15957         } pipe[I915_MAX_PIPES];
15958
15959         struct intel_plane_error_state {
15960                 u32 control;
15961                 u32 stride;
15962                 u32 size;
15963                 u32 pos;
15964                 u32 addr;
15965                 u32 surface;
15966                 u32 tile_offset;
15967         } plane[I915_MAX_PIPES];
15968
15969         struct intel_transcoder_error_state {
15970                 bool power_domain_on;
15971                 enum transcoder cpu_transcoder;
15972
15973                 u32 conf;
15974
15975                 u32 htotal;
15976                 u32 hblank;
15977                 u32 hsync;
15978                 u32 vtotal;
15979                 u32 vblank;
15980                 u32 vsync;
15981         } transcoder[4];
15982 };
15983
15984 struct intel_display_error_state *
15985 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15986 {
15987         struct intel_display_error_state *error;
15988         int transcoders[] = {
15989                 TRANSCODER_A,
15990                 TRANSCODER_B,
15991                 TRANSCODER_C,
15992                 TRANSCODER_EDP,
15993         };
15994         int i;
15995
15996         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15997                 return NULL;
15998
15999         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16000         if (error == NULL)
16001                 return NULL;
16002
16003         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16004                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16005
16006         for_each_pipe(dev_priv, i) {
16007                 error->pipe[i].power_domain_on =
16008                         __intel_display_power_is_enabled(dev_priv,
16009                                                          POWER_DOMAIN_PIPE(i));
16010                 if (!error->pipe[i].power_domain_on)
16011                         continue;
16012
16013                 error->cursor[i].control = I915_READ(CURCNTR(i));
16014                 error->cursor[i].position = I915_READ(CURPOS(i));
16015                 error->cursor[i].base = I915_READ(CURBASE(i));
16016
16017                 error->plane[i].control = I915_READ(DSPCNTR(i));
16018                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16019                 if (INTEL_GEN(dev_priv) <= 3) {
16020                         error->plane[i].size = I915_READ(DSPSIZE(i));
16021                         error->plane[i].pos = I915_READ(DSPPOS(i));
16022                 }
16023                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16024                         error->plane[i].addr = I915_READ(DSPADDR(i));
16025                 if (INTEL_GEN(dev_priv) >= 4) {
16026                         error->plane[i].surface = I915_READ(DSPSURF(i));
16027                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16028                 }
16029
16030                 error->pipe[i].source = I915_READ(PIPESRC(i));
16031
16032                 if (HAS_GMCH_DISPLAY(dev_priv))
16033                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16034         }
16035
16036         /* Note: this does not include DSI transcoders. */
16037         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16038         if (HAS_DDI(dev_priv))
16039                 error->num_transcoders++; /* Account for eDP. */
16040
16041         for (i = 0; i < error->num_transcoders; i++) {
16042                 enum transcoder cpu_transcoder = transcoders[i];
16043
16044                 error->transcoder[i].power_domain_on =
16045                         __intel_display_power_is_enabled(dev_priv,
16046                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16047                 if (!error->transcoder[i].power_domain_on)
16048                         continue;
16049
16050                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16051
16052                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16053                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16054                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16055                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16056                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16057                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16058                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16059         }
16060
16061         return error;
16062 }
16063
16064 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16065
16066 void
16067 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16068                                 struct intel_display_error_state *error)
16069 {
16070         struct drm_i915_private *dev_priv = m->i915;
16071         int i;
16072
16073         if (!error)
16074                 return;
16075
16076         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16077         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16078                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16079                            error->power_well_driver);
16080         for_each_pipe(dev_priv, i) {
16081                 err_printf(m, "Pipe [%d]:\n", i);
16082                 err_printf(m, "  Power: %s\n",
16083                            onoff(error->pipe[i].power_domain_on));
16084                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16085                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16086
16087                 err_printf(m, "Plane [%d]:\n", i);
16088                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16089                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16090                 if (INTEL_GEN(dev_priv) <= 3) {
16091                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16092                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16093                 }
16094                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16095                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16096                 if (INTEL_GEN(dev_priv) >= 4) {
16097                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16098                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16099                 }
16100
16101                 err_printf(m, "Cursor [%d]:\n", i);
16102                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16103                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16104                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16105         }
16106
16107         for (i = 0; i < error->num_transcoders; i++) {
16108                 err_printf(m, "CPU transcoder: %s\n",
16109                            transcoder_name(error->transcoder[i].cpu_transcoder));
16110                 err_printf(m, "  Power: %s\n",
16111                            onoff(error->transcoder[i].power_domain_on));
16112                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16113                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16114                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16115                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16116                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16117                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16118                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16119         }
16120 }
16121
16122 #endif