drm/i915: Display WA 827
[linux-2.6-microblaze.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_clflush.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 /* 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 static const uint32_t skl_primary_formats[] = {
77         DRM_FORMAT_C8,
78         DRM_FORMAT_RGB565,
79         DRM_FORMAT_XRGB8888,
80         DRM_FORMAT_XBGR8888,
81         DRM_FORMAT_ARGB8888,
82         DRM_FORMAT_ABGR8888,
83         DRM_FORMAT_XRGB2101010,
84         DRM_FORMAT_XBGR2101010,
85         DRM_FORMAT_YUYV,
86         DRM_FORMAT_YVYU,
87         DRM_FORMAT_UYVY,
88         DRM_FORMAT_VYUY,
89 };
90
91 static const uint64_t skl_format_modifiers_noccs[] = {
92         I915_FORMAT_MOD_Yf_TILED,
93         I915_FORMAT_MOD_Y_TILED,
94         I915_FORMAT_MOD_X_TILED,
95         DRM_FORMAT_MOD_LINEAR,
96         DRM_FORMAT_MOD_INVALID
97 };
98
99 static const uint64_t skl_format_modifiers_ccs[] = {
100         I915_FORMAT_MOD_Yf_TILED_CCS,
101         I915_FORMAT_MOD_Y_TILED_CCS,
102         I915_FORMAT_MOD_Yf_TILED,
103         I915_FORMAT_MOD_Y_TILED,
104         I915_FORMAT_MOD_X_TILED,
105         DRM_FORMAT_MOD_LINEAR,
106         DRM_FORMAT_MOD_INVALID
107 };
108
109 /* Cursor formats */
110 static const uint32_t intel_cursor_formats[] = {
111         DRM_FORMAT_ARGB8888,
112 };
113
114 static const uint64_t cursor_format_modifiers[] = {
115         DRM_FORMAT_MOD_LINEAR,
116         DRM_FORMAT_MOD_INVALID
117 };
118
119 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
120                                 struct intel_crtc_state *pipe_config);
121 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
122                                    struct intel_crtc_state *pipe_config);
123
124 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
125                                   struct drm_i915_gem_object *obj,
126                                   struct drm_mode_fb_cmd2 *mode_cmd);
127 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
128 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
129 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
130 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
131                                          struct intel_link_m_n *m_n,
132                                          struct intel_link_m_n *m2_n2);
133 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
134 static void haswell_set_pipeconf(struct drm_crtc *crtc);
135 static void haswell_set_pipemisc(struct drm_crtc *crtc);
136 static void vlv_prepare_pll(struct intel_crtc *crtc,
137                             const struct intel_crtc_state *pipe_config);
138 static void chv_prepare_pll(struct intel_crtc *crtc,
139                             const struct intel_crtc_state *pipe_config);
140 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
141 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
142 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
143                                     struct intel_crtc_state *crtc_state);
144 static void skylake_pfit_enable(struct intel_crtc *crtc);
145 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
146 static void ironlake_pfit_enable(struct intel_crtc *crtc);
147 static void intel_modeset_setup_hw_state(struct drm_device *dev,
148                                          struct drm_modeset_acquire_ctx *ctx);
149 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
150
151 struct intel_limit {
152         struct {
153                 int min, max;
154         } dot, vco, n, m, m1, m2, p, p1;
155
156         struct {
157                 int dot_limit;
158                 int p2_slow, p2_fast;
159         } p2;
160 };
161
162 /* returns HPLL frequency in kHz */
163 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
164 {
165         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
166
167         /* Obtain SKU information */
168         mutex_lock(&dev_priv->sb_lock);
169         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
170                 CCK_FUSE_HPLL_FREQ_MASK;
171         mutex_unlock(&dev_priv->sb_lock);
172
173         return vco_freq[hpll_freq] * 1000;
174 }
175
176 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
177                       const char *name, u32 reg, int ref_freq)
178 {
179         u32 val;
180         int divider;
181
182         mutex_lock(&dev_priv->sb_lock);
183         val = vlv_cck_read(dev_priv, reg);
184         mutex_unlock(&dev_priv->sb_lock);
185
186         divider = val & CCK_FREQUENCY_VALUES;
187
188         WARN((val & CCK_FREQUENCY_STATUS) !=
189              (divider << CCK_FREQUENCY_STATUS_SHIFT),
190              "%s change in progress\n", name);
191
192         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
193 }
194
195 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
196                            const char *name, u32 reg)
197 {
198         if (dev_priv->hpll_freq == 0)
199                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
200
201         return vlv_get_cck_clock(dev_priv, name, reg,
202                                  dev_priv->hpll_freq);
203 }
204
205 static void intel_update_czclk(struct drm_i915_private *dev_priv)
206 {
207         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
208                 return;
209
210         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
211                                                       CCK_CZ_CLOCK_CONTROL);
212
213         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
214 }
215
216 static inline u32 /* units of 100MHz */
217 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
218                     const struct intel_crtc_state *pipe_config)
219 {
220         if (HAS_DDI(dev_priv))
221                 return pipe_config->port_clock; /* SPLL */
222         else
223                 return dev_priv->fdi_pll_freq;
224 }
225
226 static const struct intel_limit intel_limits_i8xx_dac = {
227         .dot = { .min = 25000, .max = 350000 },
228         .vco = { .min = 908000, .max = 1512000 },
229         .n = { .min = 2, .max = 16 },
230         .m = { .min = 96, .max = 140 },
231         .m1 = { .min = 18, .max = 26 },
232         .m2 = { .min = 6, .max = 16 },
233         .p = { .min = 4, .max = 128 },
234         .p1 = { .min = 2, .max = 33 },
235         .p2 = { .dot_limit = 165000,
236                 .p2_slow = 4, .p2_fast = 2 },
237 };
238
239 static const struct intel_limit intel_limits_i8xx_dvo = {
240         .dot = { .min = 25000, .max = 350000 },
241         .vco = { .min = 908000, .max = 1512000 },
242         .n = { .min = 2, .max = 16 },
243         .m = { .min = 96, .max = 140 },
244         .m1 = { .min = 18, .max = 26 },
245         .m2 = { .min = 6, .max = 16 },
246         .p = { .min = 4, .max = 128 },
247         .p1 = { .min = 2, .max = 33 },
248         .p2 = { .dot_limit = 165000,
249                 .p2_slow = 4, .p2_fast = 4 },
250 };
251
252 static const struct intel_limit intel_limits_i8xx_lvds = {
253         .dot = { .min = 25000, .max = 350000 },
254         .vco = { .min = 908000, .max = 1512000 },
255         .n = { .min = 2, .max = 16 },
256         .m = { .min = 96, .max = 140 },
257         .m1 = { .min = 18, .max = 26 },
258         .m2 = { .min = 6, .max = 16 },
259         .p = { .min = 4, .max = 128 },
260         .p1 = { .min = 1, .max = 6 },
261         .p2 = { .dot_limit = 165000,
262                 .p2_slow = 14, .p2_fast = 7 },
263 };
264
265 static const struct intel_limit intel_limits_i9xx_sdvo = {
266         .dot = { .min = 20000, .max = 400000 },
267         .vco = { .min = 1400000, .max = 2800000 },
268         .n = { .min = 1, .max = 6 },
269         .m = { .min = 70, .max = 120 },
270         .m1 = { .min = 8, .max = 18 },
271         .m2 = { .min = 3, .max = 7 },
272         .p = { .min = 5, .max = 80 },
273         .p1 = { .min = 1, .max = 8 },
274         .p2 = { .dot_limit = 200000,
275                 .p2_slow = 10, .p2_fast = 5 },
276 };
277
278 static const struct intel_limit intel_limits_i9xx_lvds = {
279         .dot = { .min = 20000, .max = 400000 },
280         .vco = { .min = 1400000, .max = 2800000 },
281         .n = { .min = 1, .max = 6 },
282         .m = { .min = 70, .max = 120 },
283         .m1 = { .min = 8, .max = 18 },
284         .m2 = { .min = 3, .max = 7 },
285         .p = { .min = 7, .max = 98 },
286         .p1 = { .min = 1, .max = 8 },
287         .p2 = { .dot_limit = 112000,
288                 .p2_slow = 14, .p2_fast = 7 },
289 };
290
291
292 static const struct intel_limit intel_limits_g4x_sdvo = {
293         .dot = { .min = 25000, .max = 270000 },
294         .vco = { .min = 1750000, .max = 3500000},
295         .n = { .min = 1, .max = 4 },
296         .m = { .min = 104, .max = 138 },
297         .m1 = { .min = 17, .max = 23 },
298         .m2 = { .min = 5, .max = 11 },
299         .p = { .min = 10, .max = 30 },
300         .p1 = { .min = 1, .max = 3},
301         .p2 = { .dot_limit = 270000,
302                 .p2_slow = 10,
303                 .p2_fast = 10
304         },
305 };
306
307 static const struct intel_limit intel_limits_g4x_hdmi = {
308         .dot = { .min = 22000, .max = 400000 },
309         .vco = { .min = 1750000, .max = 3500000},
310         .n = { .min = 1, .max = 4 },
311         .m = { .min = 104, .max = 138 },
312         .m1 = { .min = 16, .max = 23 },
313         .m2 = { .min = 5, .max = 11 },
314         .p = { .min = 5, .max = 80 },
315         .p1 = { .min = 1, .max = 8},
316         .p2 = { .dot_limit = 165000,
317                 .p2_slow = 10, .p2_fast = 5 },
318 };
319
320 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
321         .dot = { .min = 20000, .max = 115000 },
322         .vco = { .min = 1750000, .max = 3500000 },
323         .n = { .min = 1, .max = 3 },
324         .m = { .min = 104, .max = 138 },
325         .m1 = { .min = 17, .max = 23 },
326         .m2 = { .min = 5, .max = 11 },
327         .p = { .min = 28, .max = 112 },
328         .p1 = { .min = 2, .max = 8 },
329         .p2 = { .dot_limit = 0,
330                 .p2_slow = 14, .p2_fast = 14
331         },
332 };
333
334 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
335         .dot = { .min = 80000, .max = 224000 },
336         .vco = { .min = 1750000, .max = 3500000 },
337         .n = { .min = 1, .max = 3 },
338         .m = { .min = 104, .max = 138 },
339         .m1 = { .min = 17, .max = 23 },
340         .m2 = { .min = 5, .max = 11 },
341         .p = { .min = 14, .max = 42 },
342         .p1 = { .min = 2, .max = 6 },
343         .p2 = { .dot_limit = 0,
344                 .p2_slow = 7, .p2_fast = 7
345         },
346 };
347
348 static const struct intel_limit intel_limits_pineview_sdvo = {
349         .dot = { .min = 20000, .max = 400000},
350         .vco = { .min = 1700000, .max = 3500000 },
351         /* Pineview's Ncounter is a ring counter */
352         .n = { .min = 3, .max = 6 },
353         .m = { .min = 2, .max = 256 },
354         /* Pineview only has one combined m divider, which we treat as m2. */
355         .m1 = { .min = 0, .max = 0 },
356         .m2 = { .min = 0, .max = 254 },
357         .p = { .min = 5, .max = 80 },
358         .p1 = { .min = 1, .max = 8 },
359         .p2 = { .dot_limit = 200000,
360                 .p2_slow = 10, .p2_fast = 5 },
361 };
362
363 static const struct intel_limit intel_limits_pineview_lvds = {
364         .dot = { .min = 20000, .max = 400000 },
365         .vco = { .min = 1700000, .max = 3500000 },
366         .n = { .min = 3, .max = 6 },
367         .m = { .min = 2, .max = 256 },
368         .m1 = { .min = 0, .max = 0 },
369         .m2 = { .min = 0, .max = 254 },
370         .p = { .min = 7, .max = 112 },
371         .p1 = { .min = 1, .max = 8 },
372         .p2 = { .dot_limit = 112000,
373                 .p2_slow = 14, .p2_fast = 14 },
374 };
375
376 /* Ironlake / Sandybridge
377  *
378  * We calculate clock using (register_value + 2) for N/M1/M2, so here
379  * the range value for them is (actual_value - 2).
380  */
381 static const struct intel_limit intel_limits_ironlake_dac = {
382         .dot = { .min = 25000, .max = 350000 },
383         .vco = { .min = 1760000, .max = 3510000 },
384         .n = { .min = 1, .max = 5 },
385         .m = { .min = 79, .max = 127 },
386         .m1 = { .min = 12, .max = 22 },
387         .m2 = { .min = 5, .max = 9 },
388         .p = { .min = 5, .max = 80 },
389         .p1 = { .min = 1, .max = 8 },
390         .p2 = { .dot_limit = 225000,
391                 .p2_slow = 10, .p2_fast = 5 },
392 };
393
394 static const struct intel_limit intel_limits_ironlake_single_lvds = {
395         .dot = { .min = 25000, .max = 350000 },
396         .vco = { .min = 1760000, .max = 3510000 },
397         .n = { .min = 1, .max = 3 },
398         .m = { .min = 79, .max = 118 },
399         .m1 = { .min = 12, .max = 22 },
400         .m2 = { .min = 5, .max = 9 },
401         .p = { .min = 28, .max = 112 },
402         .p1 = { .min = 2, .max = 8 },
403         .p2 = { .dot_limit = 225000,
404                 .p2_slow = 14, .p2_fast = 14 },
405 };
406
407 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
408         .dot = { .min = 25000, .max = 350000 },
409         .vco = { .min = 1760000, .max = 3510000 },
410         .n = { .min = 1, .max = 3 },
411         .m = { .min = 79, .max = 127 },
412         .m1 = { .min = 12, .max = 22 },
413         .m2 = { .min = 5, .max = 9 },
414         .p = { .min = 14, .max = 56 },
415         .p1 = { .min = 2, .max = 8 },
416         .p2 = { .dot_limit = 225000,
417                 .p2_slow = 7, .p2_fast = 7 },
418 };
419
420 /* LVDS 100mhz refclk limits. */
421 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
422         .dot = { .min = 25000, .max = 350000 },
423         .vco = { .min = 1760000, .max = 3510000 },
424         .n = { .min = 1, .max = 2 },
425         .m = { .min = 79, .max = 126 },
426         .m1 = { .min = 12, .max = 22 },
427         .m2 = { .min = 5, .max = 9 },
428         .p = { .min = 28, .max = 112 },
429         .p1 = { .min = 2, .max = 8 },
430         .p2 = { .dot_limit = 225000,
431                 .p2_slow = 14, .p2_fast = 14 },
432 };
433
434 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
435         .dot = { .min = 25000, .max = 350000 },
436         .vco = { .min = 1760000, .max = 3510000 },
437         .n = { .min = 1, .max = 3 },
438         .m = { .min = 79, .max = 126 },
439         .m1 = { .min = 12, .max = 22 },
440         .m2 = { .min = 5, .max = 9 },
441         .p = { .min = 14, .max = 42 },
442         .p1 = { .min = 2, .max = 6 },
443         .p2 = { .dot_limit = 225000,
444                 .p2_slow = 7, .p2_fast = 7 },
445 };
446
447 static const struct intel_limit intel_limits_vlv = {
448          /*
449           * These are the data rate limits (measured in fast clocks)
450           * since those are the strictest limits we have. The fast
451           * clock and actual rate limits are more relaxed, so checking
452           * them would make no difference.
453           */
454         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
455         .vco = { .min = 4000000, .max = 6000000 },
456         .n = { .min = 1, .max = 7 },
457         .m1 = { .min = 2, .max = 3 },
458         .m2 = { .min = 11, .max = 156 },
459         .p1 = { .min = 2, .max = 3 },
460         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
461 };
462
463 static const struct intel_limit intel_limits_chv = {
464         /*
465          * These are the data rate limits (measured in fast clocks)
466          * since those are the strictest limits we have.  The fast
467          * clock and actual rate limits are more relaxed, so checking
468          * them would make no difference.
469          */
470         .dot = { .min = 25000 * 5, .max = 540000 * 5},
471         .vco = { .min = 4800000, .max = 6480000 },
472         .n = { .min = 1, .max = 1 },
473         .m1 = { .min = 2, .max = 2 },
474         .m2 = { .min = 24 << 22, .max = 175 << 22 },
475         .p1 = { .min = 2, .max = 4 },
476         .p2 = { .p2_slow = 1, .p2_fast = 14 },
477 };
478
479 static const struct intel_limit intel_limits_bxt = {
480         /* FIXME: find real dot limits */
481         .dot = { .min = 0, .max = INT_MAX },
482         .vco = { .min = 4800000, .max = 6700000 },
483         .n = { .min = 1, .max = 1 },
484         .m1 = { .min = 2, .max = 2 },
485         /* FIXME: find real m2 limits */
486         .m2 = { .min = 2 << 22, .max = 255 << 22 },
487         .p1 = { .min = 2, .max = 4 },
488         .p2 = { .p2_slow = 1, .p2_fast = 20 },
489 };
490
491 static void
492 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
493 {
494         if (IS_SKYLAKE(dev_priv))
495                 return;
496
497         if (enable)
498                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
499                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
500         else
501                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
502                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
503                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
504 }
505
506 static bool
507 needs_modeset(const struct drm_crtc_state *state)
508 {
509         return drm_atomic_crtc_needs_modeset(state);
510 }
511
512 /*
513  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
514  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
515  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
516  * The helpers' return value is the rate of the clock that is fed to the
517  * display engine's pipe which can be the above fast dot clock rate or a
518  * divided-down version of it.
519  */
520 /* m1 is reserved as 0 in Pineview, n is a ring counter */
521 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
522 {
523         clock->m = clock->m2 + 2;
524         clock->p = clock->p1 * clock->p2;
525         if (WARN_ON(clock->n == 0 || clock->p == 0))
526                 return 0;
527         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
528         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
529
530         return clock->dot;
531 }
532
533 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
534 {
535         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
536 }
537
538 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
539 {
540         clock->m = i9xx_dpll_compute_m(clock);
541         clock->p = clock->p1 * clock->p2;
542         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
543                 return 0;
544         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
545         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
546
547         return clock->dot;
548 }
549
550 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
551 {
552         clock->m = clock->m1 * clock->m2;
553         clock->p = clock->p1 * clock->p2;
554         if (WARN_ON(clock->n == 0 || clock->p == 0))
555                 return 0;
556         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
557         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
558
559         return clock->dot / 5;
560 }
561
562 int chv_calc_dpll_params(int refclk, struct dpll *clock)
563 {
564         clock->m = clock->m1 * clock->m2;
565         clock->p = clock->p1 * clock->p2;
566         if (WARN_ON(clock->n == 0 || clock->p == 0))
567                 return 0;
568         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
569                         clock->n << 22);
570         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
571
572         return clock->dot / 5;
573 }
574
575 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
576
577 /*
578  * Returns whether the given set of divisors are valid for a given refclk with
579  * the given connectors.
580  */
581 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
582                                const struct intel_limit *limit,
583                                const struct dpll *clock)
584 {
585         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
586                 INTELPllInvalid("n out of range\n");
587         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
588                 INTELPllInvalid("p1 out of range\n");
589         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
590                 INTELPllInvalid("m2 out of range\n");
591         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
592                 INTELPllInvalid("m1 out of range\n");
593
594         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
595             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
596                 if (clock->m1 <= clock->m2)
597                         INTELPllInvalid("m1 <= m2\n");
598
599         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
600             !IS_GEN9_LP(dev_priv)) {
601                 if (clock->p < limit->p.min || limit->p.max < clock->p)
602                         INTELPllInvalid("p out of range\n");
603                 if (clock->m < limit->m.min || limit->m.max < clock->m)
604                         INTELPllInvalid("m out of range\n");
605         }
606
607         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
608                 INTELPllInvalid("vco out of range\n");
609         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
610          * connector, etc., rather than just a single range.
611          */
612         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
613                 INTELPllInvalid("dot out of range\n");
614
615         return true;
616 }
617
618 static int
619 i9xx_select_p2_div(const struct intel_limit *limit,
620                    const struct intel_crtc_state *crtc_state,
621                    int target)
622 {
623         struct drm_device *dev = crtc_state->base.crtc->dev;
624
625         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
626                 /*
627                  * For LVDS just rely on its current settings for dual-channel.
628                  * We haven't figured out how to reliably set up different
629                  * single/dual channel state, if we even can.
630                  */
631                 if (intel_is_dual_link_lvds(dev))
632                         return limit->p2.p2_fast;
633                 else
634                         return limit->p2.p2_slow;
635         } else {
636                 if (target < limit->p2.dot_limit)
637                         return limit->p2.p2_slow;
638                 else
639                         return limit->p2.p2_fast;
640         }
641 }
642
643 /*
644  * Returns a set of divisors for the desired target clock with the given
645  * refclk, or FALSE.  The returned values represent the clock equation:
646  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
647  *
648  * Target and reference clocks are specified in kHz.
649  *
650  * If match_clock is provided, then best_clock P divider must match the P
651  * divider from @match_clock used for LVDS downclocking.
652  */
653 static bool
654 i9xx_find_best_dpll(const struct intel_limit *limit,
655                     struct intel_crtc_state *crtc_state,
656                     int target, int refclk, struct dpll *match_clock,
657                     struct dpll *best_clock)
658 {
659         struct drm_device *dev = crtc_state->base.crtc->dev;
660         struct dpll clock;
661         int err = target;
662
663         memset(best_clock, 0, sizeof(*best_clock));
664
665         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
666
667         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
668              clock.m1++) {
669                 for (clock.m2 = limit->m2.min;
670                      clock.m2 <= limit->m2.max; clock.m2++) {
671                         if (clock.m2 >= clock.m1)
672                                 break;
673                         for (clock.n = limit->n.min;
674                              clock.n <= limit->n.max; clock.n++) {
675                                 for (clock.p1 = limit->p1.min;
676                                         clock.p1 <= limit->p1.max; clock.p1++) {
677                                         int this_err;
678
679                                         i9xx_calc_dpll_params(refclk, &clock);
680                                         if (!intel_PLL_is_valid(to_i915(dev),
681                                                                 limit,
682                                                                 &clock))
683                                                 continue;
684                                         if (match_clock &&
685                                             clock.p != match_clock->p)
686                                                 continue;
687
688                                         this_err = abs(clock.dot - target);
689                                         if (this_err < err) {
690                                                 *best_clock = clock;
691                                                 err = this_err;
692                                         }
693                                 }
694                         }
695                 }
696         }
697
698         return (err != target);
699 }
700
701 /*
702  * Returns a set of divisors for the desired target clock with the given
703  * refclk, or FALSE.  The returned values represent the clock equation:
704  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
705  *
706  * Target and reference clocks are specified in kHz.
707  *
708  * If match_clock is provided, then best_clock P divider must match the P
709  * divider from @match_clock used for LVDS downclocking.
710  */
711 static bool
712 pnv_find_best_dpll(const struct intel_limit *limit,
713                    struct intel_crtc_state *crtc_state,
714                    int target, int refclk, struct dpll *match_clock,
715                    struct dpll *best_clock)
716 {
717         struct drm_device *dev = crtc_state->base.crtc->dev;
718         struct dpll clock;
719         int err = target;
720
721         memset(best_clock, 0, sizeof(*best_clock));
722
723         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
724
725         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
726              clock.m1++) {
727                 for (clock.m2 = limit->m2.min;
728                      clock.m2 <= limit->m2.max; clock.m2++) {
729                         for (clock.n = limit->n.min;
730                              clock.n <= limit->n.max; clock.n++) {
731                                 for (clock.p1 = limit->p1.min;
732                                         clock.p1 <= limit->p1.max; clock.p1++) {
733                                         int this_err;
734
735                                         pnv_calc_dpll_params(refclk, &clock);
736                                         if (!intel_PLL_is_valid(to_i915(dev),
737                                                                 limit,
738                                                                 &clock))
739                                                 continue;
740                                         if (match_clock &&
741                                             clock.p != match_clock->p)
742                                                 continue;
743
744                                         this_err = abs(clock.dot - target);
745                                         if (this_err < err) {
746                                                 *best_clock = clock;
747                                                 err = this_err;
748                                         }
749                                 }
750                         }
751                 }
752         }
753
754         return (err != target);
755 }
756
757 /*
758  * Returns a set of divisors for the desired target clock with the given
759  * refclk, or FALSE.  The returned values represent the clock equation:
760  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
761  *
762  * Target and reference clocks are specified in kHz.
763  *
764  * If match_clock is provided, then best_clock P divider must match the P
765  * divider from @match_clock used for LVDS downclocking.
766  */
767 static bool
768 g4x_find_best_dpll(const struct intel_limit *limit,
769                    struct intel_crtc_state *crtc_state,
770                    int target, int refclk, struct dpll *match_clock,
771                    struct dpll *best_clock)
772 {
773         struct drm_device *dev = crtc_state->base.crtc->dev;
774         struct dpll clock;
775         int max_n;
776         bool found = false;
777         /* approximately equals target * 0.00585 */
778         int err_most = (target >> 8) + (target >> 9);
779
780         memset(best_clock, 0, sizeof(*best_clock));
781
782         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
783
784         max_n = limit->n.max;
785         /* based on hardware requirement, prefer smaller n to precision */
786         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
787                 /* based on hardware requirement, prefere larger m1,m2 */
788                 for (clock.m1 = limit->m1.max;
789                      clock.m1 >= limit->m1.min; clock.m1--) {
790                         for (clock.m2 = limit->m2.max;
791                              clock.m2 >= limit->m2.min; clock.m2--) {
792                                 for (clock.p1 = limit->p1.max;
793                                      clock.p1 >= limit->p1.min; clock.p1--) {
794                                         int this_err;
795
796                                         i9xx_calc_dpll_params(refclk, &clock);
797                                         if (!intel_PLL_is_valid(to_i915(dev),
798                                                                 limit,
799                                                                 &clock))
800                                                 continue;
801
802                                         this_err = abs(clock.dot - target);
803                                         if (this_err < err_most) {
804                                                 *best_clock = clock;
805                                                 err_most = this_err;
806                                                 max_n = clock.n;
807                                                 found = true;
808                                         }
809                                 }
810                         }
811                 }
812         }
813         return found;
814 }
815
816 /*
817  * Check if the calculated PLL configuration is more optimal compared to the
818  * best configuration and error found so far. Return the calculated error.
819  */
820 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
821                                const struct dpll *calculated_clock,
822                                const struct dpll *best_clock,
823                                unsigned int best_error_ppm,
824                                unsigned int *error_ppm)
825 {
826         /*
827          * For CHV ignore the error and consider only the P value.
828          * Prefer a bigger P value based on HW requirements.
829          */
830         if (IS_CHERRYVIEW(to_i915(dev))) {
831                 *error_ppm = 0;
832
833                 return calculated_clock->p > best_clock->p;
834         }
835
836         if (WARN_ON_ONCE(!target_freq))
837                 return false;
838
839         *error_ppm = div_u64(1000000ULL *
840                                 abs(target_freq - calculated_clock->dot),
841                              target_freq);
842         /*
843          * Prefer a better P value over a better (smaller) error if the error
844          * is small. Ensure this preference for future configurations too by
845          * setting the error to 0.
846          */
847         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
848                 *error_ppm = 0;
849
850                 return true;
851         }
852
853         return *error_ppm + 10 < best_error_ppm;
854 }
855
856 /*
857  * Returns a set of divisors for the desired target clock with the given
858  * refclk, or FALSE.  The returned values represent the clock equation:
859  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
860  */
861 static bool
862 vlv_find_best_dpll(const struct intel_limit *limit,
863                    struct intel_crtc_state *crtc_state,
864                    int target, int refclk, struct dpll *match_clock,
865                    struct dpll *best_clock)
866 {
867         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
868         struct drm_device *dev = crtc->base.dev;
869         struct dpll clock;
870         unsigned int bestppm = 1000000;
871         /* min update 19.2 MHz */
872         int max_n = min(limit->n.max, refclk / 19200);
873         bool found = false;
874
875         target *= 5; /* fast clock */
876
877         memset(best_clock, 0, sizeof(*best_clock));
878
879         /* based on hardware requirement, prefer smaller n to precision */
880         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
881                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
882                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
883                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
884                                 clock.p = clock.p1 * clock.p2;
885                                 /* based on hardware requirement, prefer bigger m1,m2 values */
886                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
887                                         unsigned int ppm;
888
889                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
890                                                                      refclk * clock.m1);
891
892                                         vlv_calc_dpll_params(refclk, &clock);
893
894                                         if (!intel_PLL_is_valid(to_i915(dev),
895                                                                 limit,
896                                                                 &clock))
897                                                 continue;
898
899                                         if (!vlv_PLL_is_optimal(dev, target,
900                                                                 &clock,
901                                                                 best_clock,
902                                                                 bestppm, &ppm))
903                                                 continue;
904
905                                         *best_clock = clock;
906                                         bestppm = ppm;
907                                         found = true;
908                                 }
909                         }
910                 }
911         }
912
913         return found;
914 }
915
916 /*
917  * Returns a set of divisors for the desired target clock with the given
918  * refclk, or FALSE.  The returned values represent the clock equation:
919  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
920  */
921 static bool
922 chv_find_best_dpll(const struct intel_limit *limit,
923                    struct intel_crtc_state *crtc_state,
924                    int target, int refclk, struct dpll *match_clock,
925                    struct dpll *best_clock)
926 {
927         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
928         struct drm_device *dev = crtc->base.dev;
929         unsigned int best_error_ppm;
930         struct dpll clock;
931         uint64_t m2;
932         int found = false;
933
934         memset(best_clock, 0, sizeof(*best_clock));
935         best_error_ppm = 1000000;
936
937         /*
938          * Based on hardware doc, the n always set to 1, and m1 always
939          * set to 2.  If requires to support 200Mhz refclk, we need to
940          * revisit this because n may not 1 anymore.
941          */
942         clock.n = 1, clock.m1 = 2;
943         target *= 5;    /* fast clock */
944
945         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
946                 for (clock.p2 = limit->p2.p2_fast;
947                                 clock.p2 >= limit->p2.p2_slow;
948                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
949                         unsigned int error_ppm;
950
951                         clock.p = clock.p1 * clock.p2;
952
953                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
954                                         clock.n) << 22, refclk * clock.m1);
955
956                         if (m2 > INT_MAX/clock.m1)
957                                 continue;
958
959                         clock.m2 = m2;
960
961                         chv_calc_dpll_params(refclk, &clock);
962
963                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
964                                 continue;
965
966                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
967                                                 best_error_ppm, &error_ppm))
968                                 continue;
969
970                         *best_clock = clock;
971                         best_error_ppm = error_ppm;
972                         found = true;
973                 }
974         }
975
976         return found;
977 }
978
979 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
980                         struct dpll *best_clock)
981 {
982         int refclk = 100000;
983         const struct intel_limit *limit = &intel_limits_bxt;
984
985         return chv_find_best_dpll(limit, crtc_state,
986                                   target_clock, refclk, NULL, best_clock);
987 }
988
989 bool intel_crtc_active(struct intel_crtc *crtc)
990 {
991         /* Be paranoid as we can arrive here with only partial
992          * state retrieved from the hardware during setup.
993          *
994          * We can ditch the adjusted_mode.crtc_clock check as soon
995          * as Haswell has gained clock readout/fastboot support.
996          *
997          * We can ditch the crtc->primary->fb check as soon as we can
998          * properly reconstruct framebuffers.
999          *
1000          * FIXME: The intel_crtc->active here should be switched to
1001          * crtc->state->active once we have proper CRTC states wired up
1002          * for atomic.
1003          */
1004         return crtc->active && crtc->base.primary->state->fb &&
1005                 crtc->config->base.adjusted_mode.crtc_clock;
1006 }
1007
1008 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1009                                              enum pipe pipe)
1010 {
1011         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1012
1013         return crtc->config->cpu_transcoder;
1014 }
1015
1016 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1017                                     enum pipe pipe)
1018 {
1019         i915_reg_t reg = PIPEDSL(pipe);
1020         u32 line1, line2;
1021         u32 line_mask;
1022
1023         if (IS_GEN2(dev_priv))
1024                 line_mask = DSL_LINEMASK_GEN2;
1025         else
1026                 line_mask = DSL_LINEMASK_GEN3;
1027
1028         line1 = I915_READ(reg) & line_mask;
1029         msleep(5);
1030         line2 = I915_READ(reg) & line_mask;
1031
1032         return line1 != line2;
1033 }
1034
1035 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1036 {
1037         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1038         enum pipe pipe = crtc->pipe;
1039
1040         /* Wait for the display line to settle/start moving */
1041         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1042                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1043                           pipe_name(pipe), onoff(state));
1044 }
1045
1046 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1047 {
1048         wait_for_pipe_scanline_moving(crtc, false);
1049 }
1050
1051 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1052 {
1053         wait_for_pipe_scanline_moving(crtc, true);
1054 }
1055
1056 static void
1057 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1058 {
1059         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1060         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1061
1062         if (INTEL_GEN(dev_priv) >= 4) {
1063                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1064                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1065
1066                 /* Wait for the Pipe State to go off */
1067                 if (intel_wait_for_register(dev_priv,
1068                                             reg, I965_PIPECONF_ACTIVE, 0,
1069                                             100))
1070                         WARN(1, "pipe_off wait timed out\n");
1071         } else {
1072                 intel_wait_for_pipe_scanline_stopped(crtc);
1073         }
1074 }
1075
1076 /* Only for pre-ILK configs */
1077 void assert_pll(struct drm_i915_private *dev_priv,
1078                 enum pipe pipe, bool state)
1079 {
1080         u32 val;
1081         bool cur_state;
1082
1083         val = I915_READ(DPLL(pipe));
1084         cur_state = !!(val & DPLL_VCO_ENABLE);
1085         I915_STATE_WARN(cur_state != state,
1086              "PLL state assertion failure (expected %s, current %s)\n",
1087                         onoff(state), onoff(cur_state));
1088 }
1089
1090 /* XXX: the dsi pll is shared between MIPI DSI ports */
1091 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1092 {
1093         u32 val;
1094         bool cur_state;
1095
1096         mutex_lock(&dev_priv->sb_lock);
1097         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1098         mutex_unlock(&dev_priv->sb_lock);
1099
1100         cur_state = val & DSI_PLL_VCO_EN;
1101         I915_STATE_WARN(cur_state != state,
1102              "DSI PLL state assertion failure (expected %s, current %s)\n",
1103                         onoff(state), onoff(cur_state));
1104 }
1105
1106 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1107                           enum pipe pipe, bool state)
1108 {
1109         bool cur_state;
1110         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1111                                                                       pipe);
1112
1113         if (HAS_DDI(dev_priv)) {
1114                 /* DDI does not have a specific FDI_TX register */
1115                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1116                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1117         } else {
1118                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1119                 cur_state = !!(val & FDI_TX_ENABLE);
1120         }
1121         I915_STATE_WARN(cur_state != state,
1122              "FDI TX state assertion failure (expected %s, current %s)\n",
1123                         onoff(state), onoff(cur_state));
1124 }
1125 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1126 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1127
1128 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1129                           enum pipe pipe, bool state)
1130 {
1131         u32 val;
1132         bool cur_state;
1133
1134         val = I915_READ(FDI_RX_CTL(pipe));
1135         cur_state = !!(val & FDI_RX_ENABLE);
1136         I915_STATE_WARN(cur_state != state,
1137              "FDI RX state assertion failure (expected %s, current %s)\n",
1138                         onoff(state), onoff(cur_state));
1139 }
1140 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1141 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1142
1143 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1144                                       enum pipe pipe)
1145 {
1146         u32 val;
1147
1148         /* ILK FDI PLL is always enabled */
1149         if (IS_GEN5(dev_priv))
1150                 return;
1151
1152         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1153         if (HAS_DDI(dev_priv))
1154                 return;
1155
1156         val = I915_READ(FDI_TX_CTL(pipe));
1157         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1158 }
1159
1160 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1161                        enum pipe pipe, bool state)
1162 {
1163         u32 val;
1164         bool cur_state;
1165
1166         val = I915_READ(FDI_RX_CTL(pipe));
1167         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1168         I915_STATE_WARN(cur_state != state,
1169              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1170                         onoff(state), onoff(cur_state));
1171 }
1172
1173 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1174 {
1175         i915_reg_t pp_reg;
1176         u32 val;
1177         enum pipe panel_pipe = PIPE_A;
1178         bool locked = true;
1179
1180         if (WARN_ON(HAS_DDI(dev_priv)))
1181                 return;
1182
1183         if (HAS_PCH_SPLIT(dev_priv)) {
1184                 u32 port_sel;
1185
1186                 pp_reg = PP_CONTROL(0);
1187                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1188
1189                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1190                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1191                         panel_pipe = PIPE_B;
1192                 /* XXX: else fix for eDP */
1193         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1194                 /* presumably write lock depends on pipe, not port select */
1195                 pp_reg = PP_CONTROL(pipe);
1196                 panel_pipe = pipe;
1197         } else {
1198                 pp_reg = PP_CONTROL(0);
1199                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1200                         panel_pipe = PIPE_B;
1201         }
1202
1203         val = I915_READ(pp_reg);
1204         if (!(val & PANEL_POWER_ON) ||
1205             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1206                 locked = false;
1207
1208         I915_STATE_WARN(panel_pipe == pipe && locked,
1209              "panel assertion failure, pipe %c regs locked\n",
1210              pipe_name(pipe));
1211 }
1212
1213 void assert_pipe(struct drm_i915_private *dev_priv,
1214                  enum pipe pipe, bool state)
1215 {
1216         bool cur_state;
1217         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1218                                                                       pipe);
1219         enum intel_display_power_domain power_domain;
1220
1221         /* we keep both pipes enabled on 830 */
1222         if (IS_I830(dev_priv))
1223                 state = true;
1224
1225         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1226         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1227                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1228                 cur_state = !!(val & PIPECONF_ENABLE);
1229
1230                 intel_display_power_put(dev_priv, power_domain);
1231         } else {
1232                 cur_state = false;
1233         }
1234
1235         I915_STATE_WARN(cur_state != state,
1236              "pipe %c assertion failure (expected %s, current %s)\n",
1237                         pipe_name(pipe), onoff(state), onoff(cur_state));
1238 }
1239
1240 static void assert_plane(struct intel_plane *plane, bool state)
1241 {
1242         bool cur_state = plane->get_hw_state(plane);
1243
1244         I915_STATE_WARN(cur_state != state,
1245                         "%s assertion failure (expected %s, current %s)\n",
1246                         plane->base.name, onoff(state), onoff(cur_state));
1247 }
1248
1249 #define assert_plane_enabled(p) assert_plane(p, true)
1250 #define assert_plane_disabled(p) assert_plane(p, false)
1251
1252 static void assert_planes_disabled(struct intel_crtc *crtc)
1253 {
1254         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1255         struct intel_plane *plane;
1256
1257         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1258                 assert_plane_disabled(plane);
1259 }
1260
1261 static void assert_vblank_disabled(struct drm_crtc *crtc)
1262 {
1263         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1264                 drm_crtc_vblank_put(crtc);
1265 }
1266
1267 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1268                                     enum pipe pipe)
1269 {
1270         u32 val;
1271         bool enabled;
1272
1273         val = I915_READ(PCH_TRANSCONF(pipe));
1274         enabled = !!(val & TRANS_ENABLE);
1275         I915_STATE_WARN(enabled,
1276              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1277              pipe_name(pipe));
1278 }
1279
1280 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1281                             enum pipe pipe, u32 port_sel, u32 val)
1282 {
1283         if ((val & DP_PORT_EN) == 0)
1284                 return false;
1285
1286         if (HAS_PCH_CPT(dev_priv)) {
1287                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1288                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1289                         return false;
1290         } else if (IS_CHERRYVIEW(dev_priv)) {
1291                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1292                         return false;
1293         } else {
1294                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1295                         return false;
1296         }
1297         return true;
1298 }
1299
1300 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1301                               enum pipe pipe, u32 val)
1302 {
1303         if ((val & SDVO_ENABLE) == 0)
1304                 return false;
1305
1306         if (HAS_PCH_CPT(dev_priv)) {
1307                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1308                         return false;
1309         } else if (IS_CHERRYVIEW(dev_priv)) {
1310                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1311                         return false;
1312         } else {
1313                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1314                         return false;
1315         }
1316         return true;
1317 }
1318
1319 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1320                               enum pipe pipe, u32 val)
1321 {
1322         if ((val & LVDS_PORT_EN) == 0)
1323                 return false;
1324
1325         if (HAS_PCH_CPT(dev_priv)) {
1326                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1327                         return false;
1328         } else {
1329                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1330                         return false;
1331         }
1332         return true;
1333 }
1334
1335 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1336                               enum pipe pipe, u32 val)
1337 {
1338         if ((val & ADPA_DAC_ENABLE) == 0)
1339                 return false;
1340         if (HAS_PCH_CPT(dev_priv)) {
1341                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1342                         return false;
1343         } else {
1344                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1345                         return false;
1346         }
1347         return true;
1348 }
1349
1350 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1351                                    enum pipe pipe, i915_reg_t reg,
1352                                    u32 port_sel)
1353 {
1354         u32 val = I915_READ(reg);
1355         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1356              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1357              i915_mmio_reg_offset(reg), pipe_name(pipe));
1358
1359         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1360              && (val & DP_PIPEB_SELECT),
1361              "IBX PCH dp port still using transcoder B\n");
1362 }
1363
1364 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1365                                      enum pipe pipe, i915_reg_t reg)
1366 {
1367         u32 val = I915_READ(reg);
1368         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1369              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1370              i915_mmio_reg_offset(reg), pipe_name(pipe));
1371
1372         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1373              && (val & SDVO_PIPE_B_SELECT),
1374              "IBX PCH hdmi port still using transcoder B\n");
1375 }
1376
1377 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1378                                       enum pipe pipe)
1379 {
1380         u32 val;
1381
1382         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1383         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1384         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1385
1386         val = I915_READ(PCH_ADPA);
1387         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1388              "PCH VGA enabled on transcoder %c, should be disabled\n",
1389              pipe_name(pipe));
1390
1391         val = I915_READ(PCH_LVDS);
1392         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1393              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1394              pipe_name(pipe));
1395
1396         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1397         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1398         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1399 }
1400
1401 static void _vlv_enable_pll(struct intel_crtc *crtc,
1402                             const struct intel_crtc_state *pipe_config)
1403 {
1404         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1405         enum pipe pipe = crtc->pipe;
1406
1407         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1408         POSTING_READ(DPLL(pipe));
1409         udelay(150);
1410
1411         if (intel_wait_for_register(dev_priv,
1412                                     DPLL(pipe),
1413                                     DPLL_LOCK_VLV,
1414                                     DPLL_LOCK_VLV,
1415                                     1))
1416                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1417 }
1418
1419 static void vlv_enable_pll(struct intel_crtc *crtc,
1420                            const struct intel_crtc_state *pipe_config)
1421 {
1422         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1423         enum pipe pipe = crtc->pipe;
1424
1425         assert_pipe_disabled(dev_priv, pipe);
1426
1427         /* PLL is protected by panel, make sure we can write it */
1428         assert_panel_unlocked(dev_priv, pipe);
1429
1430         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1431                 _vlv_enable_pll(crtc, pipe_config);
1432
1433         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1434         POSTING_READ(DPLL_MD(pipe));
1435 }
1436
1437
1438 static void _chv_enable_pll(struct intel_crtc *crtc,
1439                             const struct intel_crtc_state *pipe_config)
1440 {
1441         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1442         enum pipe pipe = crtc->pipe;
1443         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1444         u32 tmp;
1445
1446         mutex_lock(&dev_priv->sb_lock);
1447
1448         /* Enable back the 10bit clock to display controller */
1449         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1450         tmp |= DPIO_DCLKP_EN;
1451         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1452
1453         mutex_unlock(&dev_priv->sb_lock);
1454
1455         /*
1456          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1457          */
1458         udelay(1);
1459
1460         /* Enable PLL */
1461         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1462
1463         /* Check PLL is locked */
1464         if (intel_wait_for_register(dev_priv,
1465                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1466                                     1))
1467                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1468 }
1469
1470 static void chv_enable_pll(struct intel_crtc *crtc,
1471                            const struct intel_crtc_state *pipe_config)
1472 {
1473         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1474         enum pipe pipe = crtc->pipe;
1475
1476         assert_pipe_disabled(dev_priv, pipe);
1477
1478         /* PLL is protected by panel, make sure we can write it */
1479         assert_panel_unlocked(dev_priv, pipe);
1480
1481         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1482                 _chv_enable_pll(crtc, pipe_config);
1483
1484         if (pipe != PIPE_A) {
1485                 /*
1486                  * WaPixelRepeatModeFixForC0:chv
1487                  *
1488                  * DPLLCMD is AWOL. Use chicken bits to propagate
1489                  * the value from DPLLBMD to either pipe B or C.
1490                  */
1491                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1492                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1493                 I915_WRITE(CBR4_VLV, 0);
1494                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1495
1496                 /*
1497                  * DPLLB VGA mode also seems to cause problems.
1498                  * We should always have it disabled.
1499                  */
1500                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1501         } else {
1502                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1503                 POSTING_READ(DPLL_MD(pipe));
1504         }
1505 }
1506
1507 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1508 {
1509         struct intel_crtc *crtc;
1510         int count = 0;
1511
1512         for_each_intel_crtc(&dev_priv->drm, crtc) {
1513                 count += crtc->base.state->active &&
1514                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1515         }
1516
1517         return count;
1518 }
1519
1520 static void i9xx_enable_pll(struct intel_crtc *crtc,
1521                             const struct intel_crtc_state *crtc_state)
1522 {
1523         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1524         i915_reg_t reg = DPLL(crtc->pipe);
1525         u32 dpll = crtc_state->dpll_hw_state.dpll;
1526         int i;
1527
1528         assert_pipe_disabled(dev_priv, crtc->pipe);
1529
1530         /* PLL is protected by panel, make sure we can write it */
1531         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1532                 assert_panel_unlocked(dev_priv, crtc->pipe);
1533
1534         /* Enable DVO 2x clock on both PLLs if necessary */
1535         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1536                 /*
1537                  * It appears to be important that we don't enable this
1538                  * for the current pipe before otherwise configuring the
1539                  * PLL. No idea how this should be handled if multiple
1540                  * DVO outputs are enabled simultaneosly.
1541                  */
1542                 dpll |= DPLL_DVO_2X_MODE;
1543                 I915_WRITE(DPLL(!crtc->pipe),
1544                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1545         }
1546
1547         /*
1548          * Apparently we need to have VGA mode enabled prior to changing
1549          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1550          * dividers, even though the register value does change.
1551          */
1552         I915_WRITE(reg, 0);
1553
1554         I915_WRITE(reg, dpll);
1555
1556         /* Wait for the clocks to stabilize. */
1557         POSTING_READ(reg);
1558         udelay(150);
1559
1560         if (INTEL_GEN(dev_priv) >= 4) {
1561                 I915_WRITE(DPLL_MD(crtc->pipe),
1562                            crtc_state->dpll_hw_state.dpll_md);
1563         } else {
1564                 /* The pixel multiplier can only be updated once the
1565                  * DPLL is enabled and the clocks are stable.
1566                  *
1567                  * So write it again.
1568                  */
1569                 I915_WRITE(reg, dpll);
1570         }
1571
1572         /* We do this three times for luck */
1573         for (i = 0; i < 3; i++) {
1574                 I915_WRITE(reg, dpll);
1575                 POSTING_READ(reg);
1576                 udelay(150); /* wait for warmup */
1577         }
1578 }
1579
1580 static void i9xx_disable_pll(struct intel_crtc *crtc)
1581 {
1582         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1583         enum pipe pipe = crtc->pipe;
1584
1585         /* Disable DVO 2x clock on both PLLs if necessary */
1586         if (IS_I830(dev_priv) &&
1587             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1588             !intel_num_dvo_pipes(dev_priv)) {
1589                 I915_WRITE(DPLL(PIPE_B),
1590                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1591                 I915_WRITE(DPLL(PIPE_A),
1592                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1593         }
1594
1595         /* Don't disable pipe or pipe PLLs if needed */
1596         if (IS_I830(dev_priv))
1597                 return;
1598
1599         /* Make sure the pipe isn't still relying on us */
1600         assert_pipe_disabled(dev_priv, pipe);
1601
1602         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1603         POSTING_READ(DPLL(pipe));
1604 }
1605
1606 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1607 {
1608         u32 val;
1609
1610         /* Make sure the pipe isn't still relying on us */
1611         assert_pipe_disabled(dev_priv, pipe);
1612
1613         val = DPLL_INTEGRATED_REF_CLK_VLV |
1614                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1615         if (pipe != PIPE_A)
1616                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1617
1618         I915_WRITE(DPLL(pipe), val);
1619         POSTING_READ(DPLL(pipe));
1620 }
1621
1622 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1623 {
1624         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1625         u32 val;
1626
1627         /* Make sure the pipe isn't still relying on us */
1628         assert_pipe_disabled(dev_priv, pipe);
1629
1630         val = DPLL_SSC_REF_CLK_CHV |
1631                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1632         if (pipe != PIPE_A)
1633                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1634
1635         I915_WRITE(DPLL(pipe), val);
1636         POSTING_READ(DPLL(pipe));
1637
1638         mutex_lock(&dev_priv->sb_lock);
1639
1640         /* Disable 10bit clock to display controller */
1641         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1642         val &= ~DPIO_DCLKP_EN;
1643         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1644
1645         mutex_unlock(&dev_priv->sb_lock);
1646 }
1647
1648 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1649                          struct intel_digital_port *dport,
1650                          unsigned int expected_mask)
1651 {
1652         u32 port_mask;
1653         i915_reg_t dpll_reg;
1654
1655         switch (dport->base.port) {
1656         case PORT_B:
1657                 port_mask = DPLL_PORTB_READY_MASK;
1658                 dpll_reg = DPLL(0);
1659                 break;
1660         case PORT_C:
1661                 port_mask = DPLL_PORTC_READY_MASK;
1662                 dpll_reg = DPLL(0);
1663                 expected_mask <<= 4;
1664                 break;
1665         case PORT_D:
1666                 port_mask = DPLL_PORTD_READY_MASK;
1667                 dpll_reg = DPIO_PHY_STATUS;
1668                 break;
1669         default:
1670                 BUG();
1671         }
1672
1673         if (intel_wait_for_register(dev_priv,
1674                                     dpll_reg, port_mask, expected_mask,
1675                                     1000))
1676                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1677                      port_name(dport->base.port),
1678                      I915_READ(dpll_reg) & port_mask, expected_mask);
1679 }
1680
1681 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1682                                            enum pipe pipe)
1683 {
1684         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1685                                                                 pipe);
1686         i915_reg_t reg;
1687         uint32_t val, pipeconf_val;
1688
1689         /* Make sure PCH DPLL is enabled */
1690         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1691
1692         /* FDI must be feeding us bits for PCH ports */
1693         assert_fdi_tx_enabled(dev_priv, pipe);
1694         assert_fdi_rx_enabled(dev_priv, pipe);
1695
1696         if (HAS_PCH_CPT(dev_priv)) {
1697                 /* Workaround: Set the timing override bit before enabling the
1698                  * pch transcoder. */
1699                 reg = TRANS_CHICKEN2(pipe);
1700                 val = I915_READ(reg);
1701                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1702                 I915_WRITE(reg, val);
1703         }
1704
1705         reg = PCH_TRANSCONF(pipe);
1706         val = I915_READ(reg);
1707         pipeconf_val = I915_READ(PIPECONF(pipe));
1708
1709         if (HAS_PCH_IBX(dev_priv)) {
1710                 /*
1711                  * Make the BPC in transcoder be consistent with
1712                  * that in pipeconf reg. For HDMI we must use 8bpc
1713                  * here for both 8bpc and 12bpc.
1714                  */
1715                 val &= ~PIPECONF_BPC_MASK;
1716                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1717                         val |= PIPECONF_8BPC;
1718                 else
1719                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1720         }
1721
1722         val &= ~TRANS_INTERLACE_MASK;
1723         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1724                 if (HAS_PCH_IBX(dev_priv) &&
1725                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1726                         val |= TRANS_LEGACY_INTERLACED_ILK;
1727                 else
1728                         val |= TRANS_INTERLACED;
1729         else
1730                 val |= TRANS_PROGRESSIVE;
1731
1732         I915_WRITE(reg, val | TRANS_ENABLE);
1733         if (intel_wait_for_register(dev_priv,
1734                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1735                                     100))
1736                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1737 }
1738
1739 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1740                                       enum transcoder cpu_transcoder)
1741 {
1742         u32 val, pipeconf_val;
1743
1744         /* FDI must be feeding us bits for PCH ports */
1745         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1746         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1747
1748         /* Workaround: set timing override bit. */
1749         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1750         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1751         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1752
1753         val = TRANS_ENABLE;
1754         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1755
1756         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1757             PIPECONF_INTERLACED_ILK)
1758                 val |= TRANS_INTERLACED;
1759         else
1760                 val |= TRANS_PROGRESSIVE;
1761
1762         I915_WRITE(LPT_TRANSCONF, val);
1763         if (intel_wait_for_register(dev_priv,
1764                                     LPT_TRANSCONF,
1765                                     TRANS_STATE_ENABLE,
1766                                     TRANS_STATE_ENABLE,
1767                                     100))
1768                 DRM_ERROR("Failed to enable PCH transcoder\n");
1769 }
1770
1771 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1772                                             enum pipe pipe)
1773 {
1774         i915_reg_t reg;
1775         uint32_t val;
1776
1777         /* FDI relies on the transcoder */
1778         assert_fdi_tx_disabled(dev_priv, pipe);
1779         assert_fdi_rx_disabled(dev_priv, pipe);
1780
1781         /* Ports must be off as well */
1782         assert_pch_ports_disabled(dev_priv, pipe);
1783
1784         reg = PCH_TRANSCONF(pipe);
1785         val = I915_READ(reg);
1786         val &= ~TRANS_ENABLE;
1787         I915_WRITE(reg, val);
1788         /* wait for PCH transcoder off, transcoder state */
1789         if (intel_wait_for_register(dev_priv,
1790                                     reg, TRANS_STATE_ENABLE, 0,
1791                                     50))
1792                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1793
1794         if (HAS_PCH_CPT(dev_priv)) {
1795                 /* Workaround: Clear the timing override chicken bit again. */
1796                 reg = TRANS_CHICKEN2(pipe);
1797                 val = I915_READ(reg);
1798                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1799                 I915_WRITE(reg, val);
1800         }
1801 }
1802
1803 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1804 {
1805         u32 val;
1806
1807         val = I915_READ(LPT_TRANSCONF);
1808         val &= ~TRANS_ENABLE;
1809         I915_WRITE(LPT_TRANSCONF, val);
1810         /* wait for PCH transcoder off, transcoder state */
1811         if (intel_wait_for_register(dev_priv,
1812                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1813                                     50))
1814                 DRM_ERROR("Failed to disable PCH transcoder\n");
1815
1816         /* Workaround: clear timing override bit. */
1817         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1818         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1819         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1820 }
1821
1822 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1823 {
1824         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1825
1826         if (HAS_PCH_LPT(dev_priv))
1827                 return PIPE_A;
1828         else
1829                 return crtc->pipe;
1830 }
1831
1832 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1833 {
1834         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1835         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1836         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1837         enum pipe pipe = crtc->pipe;
1838         i915_reg_t reg;
1839         u32 val;
1840
1841         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1842
1843         assert_planes_disabled(crtc);
1844
1845         /*
1846          * A pipe without a PLL won't actually be able to drive bits from
1847          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1848          * need the check.
1849          */
1850         if (HAS_GMCH_DISPLAY(dev_priv)) {
1851                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1852                         assert_dsi_pll_enabled(dev_priv);
1853                 else
1854                         assert_pll_enabled(dev_priv, pipe);
1855         } else {
1856                 if (new_crtc_state->has_pch_encoder) {
1857                         /* if driving the PCH, we need FDI enabled */
1858                         assert_fdi_rx_pll_enabled(dev_priv,
1859                                                   intel_crtc_pch_transcoder(crtc));
1860                         assert_fdi_tx_pll_enabled(dev_priv,
1861                                                   (enum pipe) cpu_transcoder);
1862                 }
1863                 /* FIXME: assert CPU port conditions for SNB+ */
1864         }
1865
1866         reg = PIPECONF(cpu_transcoder);
1867         val = I915_READ(reg);
1868         if (val & PIPECONF_ENABLE) {
1869                 /* we keep both pipes enabled on 830 */
1870                 WARN_ON(!IS_I830(dev_priv));
1871                 return;
1872         }
1873
1874         I915_WRITE(reg, val | PIPECONF_ENABLE);
1875         POSTING_READ(reg);
1876
1877         /*
1878          * Until the pipe starts PIPEDSL reads will return a stale value,
1879          * which causes an apparent vblank timestamp jump when PIPEDSL
1880          * resets to its proper value. That also messes up the frame count
1881          * when it's derived from the timestamps. So let's wait for the
1882          * pipe to start properly before we call drm_crtc_vblank_on()
1883          */
1884         if (dev_priv->drm.max_vblank_count == 0)
1885                 intel_wait_for_pipe_scanline_moving(crtc);
1886 }
1887
1888 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1889 {
1890         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1891         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1892         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1893         enum pipe pipe = crtc->pipe;
1894         i915_reg_t reg;
1895         u32 val;
1896
1897         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1898
1899         /*
1900          * Make sure planes won't keep trying to pump pixels to us,
1901          * or we might hang the display.
1902          */
1903         assert_planes_disabled(crtc);
1904
1905         reg = PIPECONF(cpu_transcoder);
1906         val = I915_READ(reg);
1907         if ((val & PIPECONF_ENABLE) == 0)
1908                 return;
1909
1910         /*
1911          * Double wide has implications for planes
1912          * so best keep it disabled when not needed.
1913          */
1914         if (old_crtc_state->double_wide)
1915                 val &= ~PIPECONF_DOUBLE_WIDE;
1916
1917         /* Don't disable pipe or pipe PLLs if needed */
1918         if (!IS_I830(dev_priv))
1919                 val &= ~PIPECONF_ENABLE;
1920
1921         I915_WRITE(reg, val);
1922         if ((val & PIPECONF_ENABLE) == 0)
1923                 intel_wait_for_pipe_off(old_crtc_state);
1924 }
1925
1926 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1927 {
1928         return IS_GEN2(dev_priv) ? 2048 : 4096;
1929 }
1930
1931 static unsigned int
1932 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1933 {
1934         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1935         unsigned int cpp = fb->format->cpp[plane];
1936
1937         switch (fb->modifier) {
1938         case DRM_FORMAT_MOD_LINEAR:
1939                 return cpp;
1940         case I915_FORMAT_MOD_X_TILED:
1941                 if (IS_GEN2(dev_priv))
1942                         return 128;
1943                 else
1944                         return 512;
1945         case I915_FORMAT_MOD_Y_TILED_CCS:
1946                 if (plane == 1)
1947                         return 128;
1948                 /* fall through */
1949         case I915_FORMAT_MOD_Y_TILED:
1950                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1951                         return 128;
1952                 else
1953                         return 512;
1954         case I915_FORMAT_MOD_Yf_TILED_CCS:
1955                 if (plane == 1)
1956                         return 128;
1957                 /* fall through */
1958         case I915_FORMAT_MOD_Yf_TILED:
1959                 switch (cpp) {
1960                 case 1:
1961                         return 64;
1962                 case 2:
1963                 case 4:
1964                         return 128;
1965                 case 8:
1966                 case 16:
1967                         return 256;
1968                 default:
1969                         MISSING_CASE(cpp);
1970                         return cpp;
1971                 }
1972                 break;
1973         default:
1974                 MISSING_CASE(fb->modifier);
1975                 return cpp;
1976         }
1977 }
1978
1979 static unsigned int
1980 intel_tile_height(const struct drm_framebuffer *fb, int plane)
1981 {
1982         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1983                 return 1;
1984         else
1985                 return intel_tile_size(to_i915(fb->dev)) /
1986                         intel_tile_width_bytes(fb, plane);
1987 }
1988
1989 /* Return the tile dimensions in pixel units */
1990 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
1991                             unsigned int *tile_width,
1992                             unsigned int *tile_height)
1993 {
1994         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
1995         unsigned int cpp = fb->format->cpp[plane];
1996
1997         *tile_width = tile_width_bytes / cpp;
1998         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1999 }
2000
2001 unsigned int
2002 intel_fb_align_height(const struct drm_framebuffer *fb,
2003                       int plane, unsigned int height)
2004 {
2005         unsigned int tile_height = intel_tile_height(fb, plane);
2006
2007         return ALIGN(height, tile_height);
2008 }
2009
2010 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2011 {
2012         unsigned int size = 0;
2013         int i;
2014
2015         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2016                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2017
2018         return size;
2019 }
2020
2021 static void
2022 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2023                         const struct drm_framebuffer *fb,
2024                         unsigned int rotation)
2025 {
2026         view->type = I915_GGTT_VIEW_NORMAL;
2027         if (drm_rotation_90_or_270(rotation)) {
2028                 view->type = I915_GGTT_VIEW_ROTATED;
2029                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2030         }
2031 }
2032
2033 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2034 {
2035         if (IS_I830(dev_priv))
2036                 return 16 * 1024;
2037         else if (IS_I85X(dev_priv))
2038                 return 256;
2039         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2040                 return 32;
2041         else
2042                 return 4 * 1024;
2043 }
2044
2045 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2046 {
2047         if (INTEL_GEN(dev_priv) >= 9)
2048                 return 256 * 1024;
2049         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2050                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2051                 return 128 * 1024;
2052         else if (INTEL_GEN(dev_priv) >= 4)
2053                 return 4 * 1024;
2054         else
2055                 return 0;
2056 }
2057
2058 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2059                                          int plane)
2060 {
2061         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2062
2063         /* AUX_DIST needs only 4K alignment */
2064         if (plane == 1)
2065                 return 4096;
2066
2067         switch (fb->modifier) {
2068         case DRM_FORMAT_MOD_LINEAR:
2069                 return intel_linear_alignment(dev_priv);
2070         case I915_FORMAT_MOD_X_TILED:
2071                 if (INTEL_GEN(dev_priv) >= 9)
2072                         return 256 * 1024;
2073                 return 0;
2074         case I915_FORMAT_MOD_Y_TILED_CCS:
2075         case I915_FORMAT_MOD_Yf_TILED_CCS:
2076         case I915_FORMAT_MOD_Y_TILED:
2077         case I915_FORMAT_MOD_Yf_TILED:
2078                 return 1 * 1024 * 1024;
2079         default:
2080                 MISSING_CASE(fb->modifier);
2081                 return 0;
2082         }
2083 }
2084
2085 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2086 {
2087         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2088         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2089
2090         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2091 }
2092
2093 struct i915_vma *
2094 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2095                            unsigned int rotation,
2096                            bool uses_fence,
2097                            unsigned long *out_flags)
2098 {
2099         struct drm_device *dev = fb->dev;
2100         struct drm_i915_private *dev_priv = to_i915(dev);
2101         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2102         struct i915_ggtt_view view;
2103         struct i915_vma *vma;
2104         unsigned int pinctl;
2105         u32 alignment;
2106
2107         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2108
2109         alignment = intel_surf_alignment(fb, 0);
2110
2111         intel_fill_fb_ggtt_view(&view, fb, rotation);
2112
2113         /* Note that the w/a also requires 64 PTE of padding following the
2114          * bo. We currently fill all unused PTE with the shadow page and so
2115          * we should always have valid PTE following the scanout preventing
2116          * the VT-d warning.
2117          */
2118         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2119                 alignment = 256 * 1024;
2120
2121         /*
2122          * Global gtt pte registers are special registers which actually forward
2123          * writes to a chunk of system memory. Which means that there is no risk
2124          * that the register values disappear as soon as we call
2125          * intel_runtime_pm_put(), so it is correct to wrap only the
2126          * pin/unpin/fence and not more.
2127          */
2128         intel_runtime_pm_get(dev_priv);
2129
2130         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2131
2132         pinctl = 0;
2133
2134         /* Valleyview is definitely limited to scanning out the first
2135          * 512MiB. Lets presume this behaviour was inherited from the
2136          * g4x display engine and that all earlier gen are similarly
2137          * limited. Testing suggests that it is a little more
2138          * complicated than this. For example, Cherryview appears quite
2139          * happy to scanout from anywhere within its global aperture.
2140          */
2141         if (HAS_GMCH_DISPLAY(dev_priv))
2142                 pinctl |= PIN_MAPPABLE;
2143
2144         vma = i915_gem_object_pin_to_display_plane(obj,
2145                                                    alignment, &view, pinctl);
2146         if (IS_ERR(vma))
2147                 goto err;
2148
2149         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2150                 int ret;
2151
2152                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2153                  * fence, whereas 965+ only requires a fence if using
2154                  * framebuffer compression.  For simplicity, we always, when
2155                  * possible, install a fence as the cost is not that onerous.
2156                  *
2157                  * If we fail to fence the tiled scanout, then either the
2158                  * modeset will reject the change (which is highly unlikely as
2159                  * the affected systems, all but one, do not have unmappable
2160                  * space) or we will not be able to enable full powersaving
2161                  * techniques (also likely not to apply due to various limits
2162                  * FBC and the like impose on the size of the buffer, which
2163                  * presumably we violated anyway with this unmappable buffer).
2164                  * Anyway, it is presumably better to stumble onwards with
2165                  * something and try to run the system in a "less than optimal"
2166                  * mode that matches the user configuration.
2167                  */
2168                 ret = i915_vma_pin_fence(vma);
2169                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2170                         i915_gem_object_unpin_from_display_plane(vma);
2171                         vma = ERR_PTR(ret);
2172                         goto err;
2173                 }
2174
2175                 if (ret == 0 && vma->fence)
2176                         *out_flags |= PLANE_HAS_FENCE;
2177         }
2178
2179         i915_vma_get(vma);
2180 err:
2181         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2182
2183         intel_runtime_pm_put(dev_priv);
2184         return vma;
2185 }
2186
2187 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2188 {
2189         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2190
2191         if (flags & PLANE_HAS_FENCE)
2192                 i915_vma_unpin_fence(vma);
2193         i915_gem_object_unpin_from_display_plane(vma);
2194         i915_vma_put(vma);
2195 }
2196
2197 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2198                           unsigned int rotation)
2199 {
2200         if (drm_rotation_90_or_270(rotation))
2201                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2202         else
2203                 return fb->pitches[plane];
2204 }
2205
2206 /*
2207  * Convert the x/y offsets into a linear offset.
2208  * Only valid with 0/180 degree rotation, which is fine since linear
2209  * offset is only used with linear buffers on pre-hsw and tiled buffers
2210  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2211  */
2212 u32 intel_fb_xy_to_linear(int x, int y,
2213                           const struct intel_plane_state *state,
2214                           int plane)
2215 {
2216         const struct drm_framebuffer *fb = state->base.fb;
2217         unsigned int cpp = fb->format->cpp[plane];
2218         unsigned int pitch = fb->pitches[plane];
2219
2220         return y * pitch + x * cpp;
2221 }
2222
2223 /*
2224  * Add the x/y offsets derived from fb->offsets[] to the user
2225  * specified plane src x/y offsets. The resulting x/y offsets
2226  * specify the start of scanout from the beginning of the gtt mapping.
2227  */
2228 void intel_add_fb_offsets(int *x, int *y,
2229                           const struct intel_plane_state *state,
2230                           int plane)
2231
2232 {
2233         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2234         unsigned int rotation = state->base.rotation;
2235
2236         if (drm_rotation_90_or_270(rotation)) {
2237                 *x += intel_fb->rotated[plane].x;
2238                 *y += intel_fb->rotated[plane].y;
2239         } else {
2240                 *x += intel_fb->normal[plane].x;
2241                 *y += intel_fb->normal[plane].y;
2242         }
2243 }
2244
2245 static u32 __intel_adjust_tile_offset(int *x, int *y,
2246                                       unsigned int tile_width,
2247                                       unsigned int tile_height,
2248                                       unsigned int tile_size,
2249                                       unsigned int pitch_tiles,
2250                                       u32 old_offset,
2251                                       u32 new_offset)
2252 {
2253         unsigned int pitch_pixels = pitch_tiles * tile_width;
2254         unsigned int tiles;
2255
2256         WARN_ON(old_offset & (tile_size - 1));
2257         WARN_ON(new_offset & (tile_size - 1));
2258         WARN_ON(new_offset > old_offset);
2259
2260         tiles = (old_offset - new_offset) / tile_size;
2261
2262         *y += tiles / pitch_tiles * tile_height;
2263         *x += tiles % pitch_tiles * tile_width;
2264
2265         /* minimize x in case it got needlessly big */
2266         *y += *x / pitch_pixels * tile_height;
2267         *x %= pitch_pixels;
2268
2269         return new_offset;
2270 }
2271
2272 static u32 _intel_adjust_tile_offset(int *x, int *y,
2273                                      const struct drm_framebuffer *fb, int plane,
2274                                      unsigned int rotation,
2275                                      u32 old_offset, u32 new_offset)
2276 {
2277         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2278         unsigned int cpp = fb->format->cpp[plane];
2279         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2280
2281         WARN_ON(new_offset > old_offset);
2282
2283         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2284                 unsigned int tile_size, tile_width, tile_height;
2285                 unsigned int pitch_tiles;
2286
2287                 tile_size = intel_tile_size(dev_priv);
2288                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2289
2290                 if (drm_rotation_90_or_270(rotation)) {
2291                         pitch_tiles = pitch / tile_height;
2292                         swap(tile_width, tile_height);
2293                 } else {
2294                         pitch_tiles = pitch / (tile_width * cpp);
2295                 }
2296
2297                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2298                                            tile_size, pitch_tiles,
2299                                            old_offset, new_offset);
2300         } else {
2301                 old_offset += *y * pitch + *x * cpp;
2302
2303                 *y = (old_offset - new_offset) / pitch;
2304                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2305         }
2306
2307         return new_offset;
2308 }
2309
2310 /*
2311  * Adjust the tile offset by moving the difference into
2312  * the x/y offsets.
2313  */
2314 static u32 intel_adjust_tile_offset(int *x, int *y,
2315                                     const struct intel_plane_state *state, int plane,
2316                                     u32 old_offset, u32 new_offset)
2317 {
2318         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2319                                          state->base.rotation,
2320                                          old_offset, new_offset);
2321 }
2322
2323 /*
2324  * Computes the linear offset to the base tile and adjusts
2325  * x, y. bytes per pixel is assumed to be a power-of-two.
2326  *
2327  * In the 90/270 rotated case, x and y are assumed
2328  * to be already rotated to match the rotated GTT view, and
2329  * pitch is the tile_height aligned framebuffer height.
2330  *
2331  * This function is used when computing the derived information
2332  * under intel_framebuffer, so using any of that information
2333  * here is not allowed. Anything under drm_framebuffer can be
2334  * used. This is why the user has to pass in the pitch since it
2335  * is specified in the rotated orientation.
2336  */
2337 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2338                                       int *x, int *y,
2339                                       const struct drm_framebuffer *fb, int plane,
2340                                       unsigned int pitch,
2341                                       unsigned int rotation,
2342                                       u32 alignment)
2343 {
2344         uint64_t fb_modifier = fb->modifier;
2345         unsigned int cpp = fb->format->cpp[plane];
2346         u32 offset, offset_aligned;
2347
2348         if (alignment)
2349                 alignment--;
2350
2351         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2352                 unsigned int tile_size, tile_width, tile_height;
2353                 unsigned int tile_rows, tiles, pitch_tiles;
2354
2355                 tile_size = intel_tile_size(dev_priv);
2356                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2357
2358                 if (drm_rotation_90_or_270(rotation)) {
2359                         pitch_tiles = pitch / tile_height;
2360                         swap(tile_width, tile_height);
2361                 } else {
2362                         pitch_tiles = pitch / (tile_width * cpp);
2363                 }
2364
2365                 tile_rows = *y / tile_height;
2366                 *y %= tile_height;
2367
2368                 tiles = *x / tile_width;
2369                 *x %= tile_width;
2370
2371                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2372                 offset_aligned = offset & ~alignment;
2373
2374                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2375                                            tile_size, pitch_tiles,
2376                                            offset, offset_aligned);
2377         } else {
2378                 offset = *y * pitch + *x * cpp;
2379                 offset_aligned = offset & ~alignment;
2380
2381                 *y = (offset & alignment) / pitch;
2382                 *x = ((offset & alignment) - *y * pitch) / cpp;
2383         }
2384
2385         return offset_aligned;
2386 }
2387
2388 u32 intel_compute_tile_offset(int *x, int *y,
2389                               const struct intel_plane_state *state,
2390                               int plane)
2391 {
2392         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2393         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2394         const struct drm_framebuffer *fb = state->base.fb;
2395         unsigned int rotation = state->base.rotation;
2396         int pitch = intel_fb_pitch(fb, plane, rotation);
2397         u32 alignment;
2398
2399         if (intel_plane->id == PLANE_CURSOR)
2400                 alignment = intel_cursor_alignment(dev_priv);
2401         else
2402                 alignment = intel_surf_alignment(fb, plane);
2403
2404         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2405                                           rotation, alignment);
2406 }
2407
2408 /* Convert the fb->offset[] into x/y offsets */
2409 static int intel_fb_offset_to_xy(int *x, int *y,
2410                                  const struct drm_framebuffer *fb, int plane)
2411 {
2412         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2413
2414         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2415             fb->offsets[plane] % intel_tile_size(dev_priv))
2416                 return -EINVAL;
2417
2418         *x = 0;
2419         *y = 0;
2420
2421         _intel_adjust_tile_offset(x, y,
2422                                   fb, plane, DRM_MODE_ROTATE_0,
2423                                   fb->offsets[plane], 0);
2424
2425         return 0;
2426 }
2427
2428 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2429 {
2430         switch (fb_modifier) {
2431         case I915_FORMAT_MOD_X_TILED:
2432                 return I915_TILING_X;
2433         case I915_FORMAT_MOD_Y_TILED:
2434         case I915_FORMAT_MOD_Y_TILED_CCS:
2435                 return I915_TILING_Y;
2436         default:
2437                 return I915_TILING_NONE;
2438         }
2439 }
2440
2441 /*
2442  * From the Sky Lake PRM:
2443  * "The Color Control Surface (CCS) contains the compression status of
2444  *  the cache-line pairs. The compression state of the cache-line pair
2445  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2446  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2447  *  cache-line-pairs. CCS is always Y tiled."
2448  *
2449  * Since cache line pairs refers to horizontally adjacent cache lines,
2450  * each cache line in the CCS corresponds to an area of 32x16 cache
2451  * lines on the main surface. Since each pixel is 4 bytes, this gives
2452  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2453  * main surface.
2454  */
2455 static const struct drm_format_info ccs_formats[] = {
2456         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2457         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2458         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2459         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2460 };
2461
2462 static const struct drm_format_info *
2463 lookup_format_info(const struct drm_format_info formats[],
2464                    int num_formats, u32 format)
2465 {
2466         int i;
2467
2468         for (i = 0; i < num_formats; i++) {
2469                 if (formats[i].format == format)
2470                         return &formats[i];
2471         }
2472
2473         return NULL;
2474 }
2475
2476 static const struct drm_format_info *
2477 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2478 {
2479         switch (cmd->modifier[0]) {
2480         case I915_FORMAT_MOD_Y_TILED_CCS:
2481         case I915_FORMAT_MOD_Yf_TILED_CCS:
2482                 return lookup_format_info(ccs_formats,
2483                                           ARRAY_SIZE(ccs_formats),
2484                                           cmd->pixel_format);
2485         default:
2486                 return NULL;
2487         }
2488 }
2489
2490 static int
2491 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2492                    struct drm_framebuffer *fb)
2493 {
2494         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2495         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2496         u32 gtt_offset_rotated = 0;
2497         unsigned int max_size = 0;
2498         int i, num_planes = fb->format->num_planes;
2499         unsigned int tile_size = intel_tile_size(dev_priv);
2500
2501         for (i = 0; i < num_planes; i++) {
2502                 unsigned int width, height;
2503                 unsigned int cpp, size;
2504                 u32 offset;
2505                 int x, y;
2506                 int ret;
2507
2508                 cpp = fb->format->cpp[i];
2509                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2510                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2511
2512                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2513                 if (ret) {
2514                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2515                                       i, fb->offsets[i]);
2516                         return ret;
2517                 }
2518
2519                 if ((fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2520                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) && i == 1) {
2521                         int hsub = fb->format->hsub;
2522                         int vsub = fb->format->vsub;
2523                         int tile_width, tile_height;
2524                         int main_x, main_y;
2525                         int ccs_x, ccs_y;
2526
2527                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2528                         tile_width *= hsub;
2529                         tile_height *= vsub;
2530
2531                         ccs_x = (x * hsub) % tile_width;
2532                         ccs_y = (y * vsub) % tile_height;
2533                         main_x = intel_fb->normal[0].x % tile_width;
2534                         main_y = intel_fb->normal[0].y % tile_height;
2535
2536                         /*
2537                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2538                          * x/y offsets must match between CCS and the main surface.
2539                          */
2540                         if (main_x != ccs_x || main_y != ccs_y) {
2541                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2542                                               main_x, main_y,
2543                                               ccs_x, ccs_y,
2544                                               intel_fb->normal[0].x,
2545                                               intel_fb->normal[0].y,
2546                                               x, y);
2547                                 return -EINVAL;
2548                         }
2549                 }
2550
2551                 /*
2552                  * The fence (if used) is aligned to the start of the object
2553                  * so having the framebuffer wrap around across the edge of the
2554                  * fenced region doesn't really work. We have no API to configure
2555                  * the fence start offset within the object (nor could we probably
2556                  * on gen2/3). So it's just easier if we just require that the
2557                  * fb layout agrees with the fence layout. We already check that the
2558                  * fb stride matches the fence stride elsewhere.
2559                  */
2560                 if (i == 0 && i915_gem_object_is_tiled(intel_fb->obj) &&
2561                     (x + width) * cpp > fb->pitches[i]) {
2562                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2563                                       i, fb->offsets[i]);
2564                         return -EINVAL;
2565                 }
2566
2567                 /*
2568                  * First pixel of the framebuffer from
2569                  * the start of the normal gtt mapping.
2570                  */
2571                 intel_fb->normal[i].x = x;
2572                 intel_fb->normal[i].y = y;
2573
2574                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2575                                                     fb, i, fb->pitches[i],
2576                                                     DRM_MODE_ROTATE_0, tile_size);
2577                 offset /= tile_size;
2578
2579                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2580                         unsigned int tile_width, tile_height;
2581                         unsigned int pitch_tiles;
2582                         struct drm_rect r;
2583
2584                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2585
2586                         rot_info->plane[i].offset = offset;
2587                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2588                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2589                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2590
2591                         intel_fb->rotated[i].pitch =
2592                                 rot_info->plane[i].height * tile_height;
2593
2594                         /* how many tiles does this plane need */
2595                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2596                         /*
2597                          * If the plane isn't horizontally tile aligned,
2598                          * we need one more tile.
2599                          */
2600                         if (x != 0)
2601                                 size++;
2602
2603                         /* rotate the x/y offsets to match the GTT view */
2604                         r.x1 = x;
2605                         r.y1 = y;
2606                         r.x2 = x + width;
2607                         r.y2 = y + height;
2608                         drm_rect_rotate(&r,
2609                                         rot_info->plane[i].width * tile_width,
2610                                         rot_info->plane[i].height * tile_height,
2611                                         DRM_MODE_ROTATE_270);
2612                         x = r.x1;
2613                         y = r.y1;
2614
2615                         /* rotate the tile dimensions to match the GTT view */
2616                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2617                         swap(tile_width, tile_height);
2618
2619                         /*
2620                          * We only keep the x/y offsets, so push all of the
2621                          * gtt offset into the x/y offsets.
2622                          */
2623                         __intel_adjust_tile_offset(&x, &y,
2624                                                    tile_width, tile_height,
2625                                                    tile_size, pitch_tiles,
2626                                                    gtt_offset_rotated * tile_size, 0);
2627
2628                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2629
2630                         /*
2631                          * First pixel of the framebuffer from
2632                          * the start of the rotated gtt mapping.
2633                          */
2634                         intel_fb->rotated[i].x = x;
2635                         intel_fb->rotated[i].y = y;
2636                 } else {
2637                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2638                                             x * cpp, tile_size);
2639                 }
2640
2641                 /* how many tiles in total needed in the bo */
2642                 max_size = max(max_size, offset + size);
2643         }
2644
2645         if (max_size * tile_size > intel_fb->obj->base.size) {
2646                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2647                               max_size * tile_size, intel_fb->obj->base.size);
2648                 return -EINVAL;
2649         }
2650
2651         return 0;
2652 }
2653
2654 static int i9xx_format_to_fourcc(int format)
2655 {
2656         switch (format) {
2657         case DISPPLANE_8BPP:
2658                 return DRM_FORMAT_C8;
2659         case DISPPLANE_BGRX555:
2660                 return DRM_FORMAT_XRGB1555;
2661         case DISPPLANE_BGRX565:
2662                 return DRM_FORMAT_RGB565;
2663         default:
2664         case DISPPLANE_BGRX888:
2665                 return DRM_FORMAT_XRGB8888;
2666         case DISPPLANE_RGBX888:
2667                 return DRM_FORMAT_XBGR8888;
2668         case DISPPLANE_BGRX101010:
2669                 return DRM_FORMAT_XRGB2101010;
2670         case DISPPLANE_RGBX101010:
2671                 return DRM_FORMAT_XBGR2101010;
2672         }
2673 }
2674
2675 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2676 {
2677         switch (format) {
2678         case PLANE_CTL_FORMAT_RGB_565:
2679                 return DRM_FORMAT_RGB565;
2680         case PLANE_CTL_FORMAT_NV12:
2681                 return DRM_FORMAT_NV12;
2682         default:
2683         case PLANE_CTL_FORMAT_XRGB_8888:
2684                 if (rgb_order) {
2685                         if (alpha)
2686                                 return DRM_FORMAT_ABGR8888;
2687                         else
2688                                 return DRM_FORMAT_XBGR8888;
2689                 } else {
2690                         if (alpha)
2691                                 return DRM_FORMAT_ARGB8888;
2692                         else
2693                                 return DRM_FORMAT_XRGB8888;
2694                 }
2695         case PLANE_CTL_FORMAT_XRGB_2101010:
2696                 if (rgb_order)
2697                         return DRM_FORMAT_XBGR2101010;
2698                 else
2699                         return DRM_FORMAT_XRGB2101010;
2700         }
2701 }
2702
2703 static bool
2704 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2705                               struct intel_initial_plane_config *plane_config)
2706 {
2707         struct drm_device *dev = crtc->base.dev;
2708         struct drm_i915_private *dev_priv = to_i915(dev);
2709         struct drm_i915_gem_object *obj = NULL;
2710         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2711         struct drm_framebuffer *fb = &plane_config->fb->base;
2712         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2713         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2714                                     PAGE_SIZE);
2715
2716         size_aligned -= base_aligned;
2717
2718         if (plane_config->size == 0)
2719                 return false;
2720
2721         /* If the FB is too big, just don't use it since fbdev is not very
2722          * important and we should probably use that space with FBC or other
2723          * features. */
2724         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2725                 return false;
2726
2727         mutex_lock(&dev->struct_mutex);
2728         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2729                                                              base_aligned,
2730                                                              base_aligned,
2731                                                              size_aligned);
2732         mutex_unlock(&dev->struct_mutex);
2733         if (!obj)
2734                 return false;
2735
2736         if (plane_config->tiling == I915_TILING_X)
2737                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2738
2739         mode_cmd.pixel_format = fb->format->format;
2740         mode_cmd.width = fb->width;
2741         mode_cmd.height = fb->height;
2742         mode_cmd.pitches[0] = fb->pitches[0];
2743         mode_cmd.modifier[0] = fb->modifier;
2744         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2745
2746         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2747                 DRM_DEBUG_KMS("intel fb init failed\n");
2748                 goto out_unref_obj;
2749         }
2750
2751
2752         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2753         return true;
2754
2755 out_unref_obj:
2756         i915_gem_object_put(obj);
2757         return false;
2758 }
2759
2760 static void
2761 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2762                         struct intel_plane_state *plane_state,
2763                         bool visible)
2764 {
2765         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2766
2767         plane_state->base.visible = visible;
2768
2769         /* FIXME pre-g4x don't work like this */
2770         if (visible) {
2771                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2772                 crtc_state->active_planes |= BIT(plane->id);
2773         } else {
2774                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2775                 crtc_state->active_planes &= ~BIT(plane->id);
2776         }
2777
2778         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2779                       crtc_state->base.crtc->name,
2780                       crtc_state->active_planes);
2781 }
2782
2783 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2784                                          struct intel_plane *plane)
2785 {
2786         struct intel_crtc_state *crtc_state =
2787                 to_intel_crtc_state(crtc->base.state);
2788         struct intel_plane_state *plane_state =
2789                 to_intel_plane_state(plane->base.state);
2790
2791         intel_set_plane_visible(crtc_state, plane_state, false);
2792
2793         if (plane->id == PLANE_PRIMARY)
2794                 intel_pre_disable_primary_noatomic(&crtc->base);
2795
2796         trace_intel_disable_plane(&plane->base, crtc);
2797         plane->disable_plane(plane, crtc);
2798 }
2799
2800 static void
2801 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2802                              struct intel_initial_plane_config *plane_config)
2803 {
2804         struct drm_device *dev = intel_crtc->base.dev;
2805         struct drm_i915_private *dev_priv = to_i915(dev);
2806         struct drm_crtc *c;
2807         struct drm_i915_gem_object *obj;
2808         struct drm_plane *primary = intel_crtc->base.primary;
2809         struct drm_plane_state *plane_state = primary->state;
2810         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2811         struct intel_plane *intel_plane = to_intel_plane(primary);
2812         struct intel_plane_state *intel_state =
2813                 to_intel_plane_state(plane_state);
2814         struct drm_framebuffer *fb;
2815
2816         if (!plane_config->fb)
2817                 return;
2818
2819         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2820                 fb = &plane_config->fb->base;
2821                 goto valid_fb;
2822         }
2823
2824         kfree(plane_config->fb);
2825
2826         /*
2827          * Failed to alloc the obj, check to see if we should share
2828          * an fb with another CRTC instead
2829          */
2830         for_each_crtc(dev, c) {
2831                 struct intel_plane_state *state;
2832
2833                 if (c == &intel_crtc->base)
2834                         continue;
2835
2836                 if (!to_intel_crtc(c)->active)
2837                         continue;
2838
2839                 state = to_intel_plane_state(c->primary->state);
2840                 if (!state->vma)
2841                         continue;
2842
2843                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2844                         fb = c->primary->fb;
2845                         drm_framebuffer_get(fb);
2846                         goto valid_fb;
2847                 }
2848         }
2849
2850         /*
2851          * We've failed to reconstruct the BIOS FB.  Current display state
2852          * indicates that the primary plane is visible, but has a NULL FB,
2853          * which will lead to problems later if we don't fix it up.  The
2854          * simplest solution is to just disable the primary plane now and
2855          * pretend the BIOS never had it enabled.
2856          */
2857         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2858
2859         return;
2860
2861 valid_fb:
2862         mutex_lock(&dev->struct_mutex);
2863         intel_state->vma =
2864                 intel_pin_and_fence_fb_obj(fb,
2865                                            primary->state->rotation,
2866                                            intel_plane_uses_fence(intel_state),
2867                                            &intel_state->flags);
2868         mutex_unlock(&dev->struct_mutex);
2869         if (IS_ERR(intel_state->vma)) {
2870                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2871                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2872
2873                 intel_state->vma = NULL;
2874                 drm_framebuffer_put(fb);
2875                 return;
2876         }
2877
2878         obj = intel_fb_obj(fb);
2879         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2880
2881         plane_state->src_x = 0;
2882         plane_state->src_y = 0;
2883         plane_state->src_w = fb->width << 16;
2884         plane_state->src_h = fb->height << 16;
2885
2886         plane_state->crtc_x = 0;
2887         plane_state->crtc_y = 0;
2888         plane_state->crtc_w = fb->width;
2889         plane_state->crtc_h = fb->height;
2890
2891         intel_state->base.src = drm_plane_state_src(plane_state);
2892         intel_state->base.dst = drm_plane_state_dest(plane_state);
2893
2894         if (i915_gem_object_is_tiled(obj))
2895                 dev_priv->preserve_bios_swizzle = true;
2896
2897         drm_framebuffer_get(fb);
2898         primary->fb = primary->state->fb = fb;
2899         primary->crtc = primary->state->crtc = &intel_crtc->base;
2900
2901         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2902                                 to_intel_plane_state(plane_state),
2903                                 true);
2904
2905         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2906                   &obj->frontbuffer_bits);
2907 }
2908
2909 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2910                                unsigned int rotation)
2911 {
2912         int cpp = fb->format->cpp[plane];
2913
2914         switch (fb->modifier) {
2915         case DRM_FORMAT_MOD_LINEAR:
2916         case I915_FORMAT_MOD_X_TILED:
2917                 switch (cpp) {
2918                 case 8:
2919                         return 4096;
2920                 case 4:
2921                 case 2:
2922                 case 1:
2923                         return 8192;
2924                 default:
2925                         MISSING_CASE(cpp);
2926                         break;
2927                 }
2928                 break;
2929         case I915_FORMAT_MOD_Y_TILED_CCS:
2930         case I915_FORMAT_MOD_Yf_TILED_CCS:
2931                 /* FIXME AUX plane? */
2932         case I915_FORMAT_MOD_Y_TILED:
2933         case I915_FORMAT_MOD_Yf_TILED:
2934                 switch (cpp) {
2935                 case 8:
2936                         return 2048;
2937                 case 4:
2938                         return 4096;
2939                 case 2:
2940                 case 1:
2941                         return 8192;
2942                 default:
2943                         MISSING_CASE(cpp);
2944                         break;
2945                 }
2946                 break;
2947         default:
2948                 MISSING_CASE(fb->modifier);
2949         }
2950
2951         return 2048;
2952 }
2953
2954 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2955                                            int main_x, int main_y, u32 main_offset)
2956 {
2957         const struct drm_framebuffer *fb = plane_state->base.fb;
2958         int hsub = fb->format->hsub;
2959         int vsub = fb->format->vsub;
2960         int aux_x = plane_state->aux.x;
2961         int aux_y = plane_state->aux.y;
2962         u32 aux_offset = plane_state->aux.offset;
2963         u32 alignment = intel_surf_alignment(fb, 1);
2964
2965         while (aux_offset >= main_offset && aux_y <= main_y) {
2966                 int x, y;
2967
2968                 if (aux_x == main_x && aux_y == main_y)
2969                         break;
2970
2971                 if (aux_offset == 0)
2972                         break;
2973
2974                 x = aux_x / hsub;
2975                 y = aux_y / vsub;
2976                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
2977                                                       aux_offset, aux_offset - alignment);
2978                 aux_x = x * hsub + aux_x % hsub;
2979                 aux_y = y * vsub + aux_y % vsub;
2980         }
2981
2982         if (aux_x != main_x || aux_y != main_y)
2983                 return false;
2984
2985         plane_state->aux.offset = aux_offset;
2986         plane_state->aux.x = aux_x;
2987         plane_state->aux.y = aux_y;
2988
2989         return true;
2990 }
2991
2992 static int skl_check_main_surface(const struct intel_crtc_state *crtc_state,
2993                                   struct intel_plane_state *plane_state)
2994 {
2995         struct drm_i915_private *dev_priv =
2996                 to_i915(plane_state->base.plane->dev);
2997         const struct drm_framebuffer *fb = plane_state->base.fb;
2998         unsigned int rotation = plane_state->base.rotation;
2999         int x = plane_state->base.src.x1 >> 16;
3000         int y = plane_state->base.src.y1 >> 16;
3001         int w = drm_rect_width(&plane_state->base.src) >> 16;
3002         int h = drm_rect_height(&plane_state->base.src) >> 16;
3003         int dst_x = plane_state->base.dst.x1;
3004         int pipe_src_w = crtc_state->pipe_src_w;
3005         int max_width = skl_max_plane_width(fb, 0, rotation);
3006         int max_height = 4096;
3007         u32 alignment, offset, aux_offset = plane_state->aux.offset;
3008
3009         if (w > max_width || h > max_height) {
3010                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3011                               w, h, max_width, max_height);
3012                 return -EINVAL;
3013         }
3014
3015         /*
3016          * Display WA #1175: cnl,glk
3017          * Planes other than the cursor may cause FIFO underflow and display
3018          * corruption if starting less than 4 pixels from the right edge of
3019          * the screen.
3020          * Besides the above WA fix the similar problem, where planes other
3021          * than the cursor ending less than 4 pixels from the left edge of the
3022          * screen may cause FIFO underflow and display corruption.
3023          */
3024         if ((IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
3025             (dst_x + w < 4 || dst_x > pipe_src_w - 4)) {
3026                 DRM_DEBUG_KMS("requested plane X %s position %d invalid (valid range %d-%d)\n",
3027                               dst_x + w < 4 ? "end" : "start",
3028                               dst_x + w < 4 ? dst_x + w : dst_x,
3029                               4, pipe_src_w - 4);
3030                 return -ERANGE;
3031         }
3032
3033         intel_add_fb_offsets(&x, &y, plane_state, 0);
3034         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
3035         alignment = intel_surf_alignment(fb, 0);
3036
3037         /*
3038          * AUX surface offset is specified as the distance from the
3039          * main surface offset, and it must be non-negative. Make
3040          * sure that is what we will get.
3041          */
3042         if (offset > aux_offset)
3043                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3044                                                   offset, aux_offset & ~(alignment - 1));
3045
3046         /*
3047          * When using an X-tiled surface, the plane blows up
3048          * if the x offset + width exceed the stride.
3049          *
3050          * TODO: linear and Y-tiled seem fine, Yf untested,
3051          */
3052         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3053                 int cpp = fb->format->cpp[0];
3054
3055                 while ((x + w) * cpp > fb->pitches[0]) {
3056                         if (offset == 0) {
3057                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3058                                 return -EINVAL;
3059                         }
3060
3061                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3062                                                           offset, offset - alignment);
3063                 }
3064         }
3065
3066         /*
3067          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3068          * they match with the main surface x/y offsets.
3069          */
3070         if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3071             fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3072                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3073                         if (offset == 0)
3074                                 break;
3075
3076                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3077                                                           offset, offset - alignment);
3078                 }
3079
3080                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
3081                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3082                         return -EINVAL;
3083                 }
3084         }
3085
3086         plane_state->main.offset = offset;
3087         plane_state->main.x = x;
3088         plane_state->main.y = y;
3089
3090         return 0;
3091 }
3092
3093 static int skl_check_nv12_aux_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 max_width = skl_max_plane_width(fb, 1, rotation);
3098         int max_height = 4096;
3099         int x = plane_state->base.src.x1 >> 17;
3100         int y = plane_state->base.src.y1 >> 17;
3101         int w = drm_rect_width(&plane_state->base.src) >> 17;
3102         int h = drm_rect_height(&plane_state->base.src) >> 17;
3103         u32 offset;
3104
3105         intel_add_fb_offsets(&x, &y, plane_state, 1);
3106         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3107
3108         /* FIXME not quite sure how/if these apply to the chroma plane */
3109         if (w > max_width || h > max_height) {
3110                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3111                               w, h, max_width, max_height);
3112                 return -EINVAL;
3113         }
3114
3115         plane_state->aux.offset = offset;
3116         plane_state->aux.x = x;
3117         plane_state->aux.y = y;
3118
3119         return 0;
3120 }
3121
3122 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3123 {
3124         const struct drm_framebuffer *fb = plane_state->base.fb;
3125         int src_x = plane_state->base.src.x1 >> 16;
3126         int src_y = plane_state->base.src.y1 >> 16;
3127         int hsub = fb->format->hsub;
3128         int vsub = fb->format->vsub;
3129         int x = src_x / hsub;
3130         int y = src_y / vsub;
3131         u32 offset;
3132
3133         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3134                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3135                               plane_state->base.rotation);
3136                 return -EINVAL;
3137         }
3138
3139         intel_add_fb_offsets(&x, &y, plane_state, 1);
3140         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3141
3142         plane_state->aux.offset = offset;
3143         plane_state->aux.x = x * hsub + src_x % hsub;
3144         plane_state->aux.y = y * vsub + src_y % vsub;
3145
3146         return 0;
3147 }
3148
3149 int skl_check_plane_surface(const struct intel_crtc_state *crtc_state,
3150                             struct intel_plane_state *plane_state)
3151 {
3152         const struct drm_framebuffer *fb = plane_state->base.fb;
3153         unsigned int rotation = plane_state->base.rotation;
3154         int ret;
3155
3156         if (rotation & DRM_MODE_REFLECT_X &&
3157             fb->modifier == DRM_FORMAT_MOD_LINEAR) {
3158                 DRM_DEBUG_KMS("horizontal flip is not supported with linear surface formats\n");
3159                 return -EINVAL;
3160         }
3161
3162         if (!plane_state->base.visible)
3163                 return 0;
3164
3165         /* Rotate src coordinates to match rotated GTT view */
3166         if (drm_rotation_90_or_270(rotation))
3167                 drm_rect_rotate(&plane_state->base.src,
3168                                 fb->width << 16, fb->height << 16,
3169                                 DRM_MODE_ROTATE_270);
3170
3171         /*
3172          * Handle the AUX surface first since
3173          * the main surface setup depends on it.
3174          */
3175         if (fb->format->format == DRM_FORMAT_NV12) {
3176                 ret = skl_check_nv12_aux_surface(plane_state);
3177                 if (ret)
3178                         return ret;
3179         } else if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3180                    fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3181                 ret = skl_check_ccs_aux_surface(plane_state);
3182                 if (ret)
3183                         return ret;
3184         } else {
3185                 plane_state->aux.offset = ~0xfff;
3186                 plane_state->aux.x = 0;
3187                 plane_state->aux.y = 0;
3188         }
3189
3190         ret = skl_check_main_surface(crtc_state, plane_state);
3191         if (ret)
3192                 return ret;
3193
3194         return 0;
3195 }
3196
3197 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3198                           const struct intel_plane_state *plane_state)
3199 {
3200         struct drm_i915_private *dev_priv =
3201                 to_i915(plane_state->base.plane->dev);
3202         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3203         const struct drm_framebuffer *fb = plane_state->base.fb;
3204         unsigned int rotation = plane_state->base.rotation;
3205         u32 dspcntr;
3206
3207         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3208
3209         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3210             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3211                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3212
3213         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3214                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3215
3216         if (INTEL_GEN(dev_priv) < 5)
3217                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3218
3219         switch (fb->format->format) {
3220         case DRM_FORMAT_C8:
3221                 dspcntr |= DISPPLANE_8BPP;
3222                 break;
3223         case DRM_FORMAT_XRGB1555:
3224                 dspcntr |= DISPPLANE_BGRX555;
3225                 break;
3226         case DRM_FORMAT_RGB565:
3227                 dspcntr |= DISPPLANE_BGRX565;
3228                 break;
3229         case DRM_FORMAT_XRGB8888:
3230                 dspcntr |= DISPPLANE_BGRX888;
3231                 break;
3232         case DRM_FORMAT_XBGR8888:
3233                 dspcntr |= DISPPLANE_RGBX888;
3234                 break;
3235         case DRM_FORMAT_XRGB2101010:
3236                 dspcntr |= DISPPLANE_BGRX101010;
3237                 break;
3238         case DRM_FORMAT_XBGR2101010:
3239                 dspcntr |= DISPPLANE_RGBX101010;
3240                 break;
3241         default:
3242                 MISSING_CASE(fb->format->format);
3243                 return 0;
3244         }
3245
3246         if (INTEL_GEN(dev_priv) >= 4 &&
3247             fb->modifier == I915_FORMAT_MOD_X_TILED)
3248                 dspcntr |= DISPPLANE_TILED;
3249
3250         if (rotation & DRM_MODE_ROTATE_180)
3251                 dspcntr |= DISPPLANE_ROTATE_180;
3252
3253         if (rotation & DRM_MODE_REFLECT_X)
3254                 dspcntr |= DISPPLANE_MIRROR;
3255
3256         return dspcntr;
3257 }
3258
3259 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3260 {
3261         struct drm_i915_private *dev_priv =
3262                 to_i915(plane_state->base.plane->dev);
3263         int src_x = plane_state->base.src.x1 >> 16;
3264         int src_y = plane_state->base.src.y1 >> 16;
3265         u32 offset;
3266
3267         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3268
3269         if (INTEL_GEN(dev_priv) >= 4)
3270                 offset = intel_compute_tile_offset(&src_x, &src_y,
3271                                                    plane_state, 0);
3272         else
3273                 offset = 0;
3274
3275         /* HSW/BDW do this automagically in hardware */
3276         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3277                 unsigned int rotation = plane_state->base.rotation;
3278                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3279                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3280
3281                 if (rotation & DRM_MODE_ROTATE_180) {
3282                         src_x += src_w - 1;
3283                         src_y += src_h - 1;
3284                 } else if (rotation & DRM_MODE_REFLECT_X) {
3285                         src_x += src_w - 1;
3286                 }
3287         }
3288
3289         plane_state->main.offset = offset;
3290         plane_state->main.x = src_x;
3291         plane_state->main.y = src_y;
3292
3293         return 0;
3294 }
3295
3296 static void i9xx_update_plane(struct intel_plane *plane,
3297                               const struct intel_crtc_state *crtc_state,
3298                               const struct intel_plane_state *plane_state)
3299 {
3300         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3301         const struct drm_framebuffer *fb = plane_state->base.fb;
3302         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3303         u32 linear_offset;
3304         u32 dspcntr = plane_state->ctl;
3305         i915_reg_t reg = DSPCNTR(i9xx_plane);
3306         int x = plane_state->main.x;
3307         int y = plane_state->main.y;
3308         unsigned long irqflags;
3309         u32 dspaddr_offset;
3310
3311         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3312
3313         if (INTEL_GEN(dev_priv) >= 4)
3314                 dspaddr_offset = plane_state->main.offset;
3315         else
3316                 dspaddr_offset = linear_offset;
3317
3318         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3319
3320         if (INTEL_GEN(dev_priv) < 4) {
3321                 /* pipesrc and dspsize control the size that is scaled from,
3322                  * which should always be the user's requested size.
3323                  */
3324                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3325                               ((crtc_state->pipe_src_h - 1) << 16) |
3326                               (crtc_state->pipe_src_w - 1));
3327                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3328         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3329                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3330                               ((crtc_state->pipe_src_h - 1) << 16) |
3331                               (crtc_state->pipe_src_w - 1));
3332                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3333                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3334         }
3335
3336         I915_WRITE_FW(reg, dspcntr);
3337
3338         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), fb->pitches[0]);
3339         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3340                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3341                               intel_plane_ggtt_offset(plane_state) +
3342                               dspaddr_offset);
3343                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3344         } else if (INTEL_GEN(dev_priv) >= 4) {
3345                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3346                               intel_plane_ggtt_offset(plane_state) +
3347                               dspaddr_offset);
3348                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3349                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3350         } else {
3351                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3352                               intel_plane_ggtt_offset(plane_state) +
3353                               dspaddr_offset);
3354         }
3355         POSTING_READ_FW(reg);
3356
3357         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3358 }
3359
3360 static void i9xx_disable_plane(struct intel_plane *plane,
3361                                struct intel_crtc *crtc)
3362 {
3363         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3364         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3365         unsigned long irqflags;
3366
3367         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3368
3369         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3370         if (INTEL_GEN(dev_priv) >= 4)
3371                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3372         else
3373                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3374         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3375
3376         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3377 }
3378
3379 static bool i9xx_plane_get_hw_state(struct intel_plane *plane)
3380 {
3381         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3382         enum intel_display_power_domain power_domain;
3383         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3384         enum pipe pipe = plane->pipe;
3385         bool ret;
3386
3387         /*
3388          * Not 100% correct for planes that can move between pipes,
3389          * but that's only the case for gen2-4 which don't have any
3390          * display power wells.
3391          */
3392         power_domain = POWER_DOMAIN_PIPE(pipe);
3393         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3394                 return false;
3395
3396         ret = I915_READ(DSPCNTR(i9xx_plane)) & DISPLAY_PLANE_ENABLE;
3397
3398         intel_display_power_put(dev_priv, power_domain);
3399
3400         return ret;
3401 }
3402
3403 static u32
3404 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3405 {
3406         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3407                 return 64;
3408         else
3409                 return intel_tile_width_bytes(fb, plane);
3410 }
3411
3412 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3413 {
3414         struct drm_device *dev = intel_crtc->base.dev;
3415         struct drm_i915_private *dev_priv = to_i915(dev);
3416
3417         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3418         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3419         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3420 }
3421
3422 /*
3423  * This function detaches (aka. unbinds) unused scalers in hardware
3424  */
3425 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3426 {
3427         struct intel_crtc_scaler_state *scaler_state;
3428         int i;
3429
3430         scaler_state = &intel_crtc->config->scaler_state;
3431
3432         /* loop through and disable scalers that aren't in use */
3433         for (i = 0; i < intel_crtc->num_scalers; i++) {
3434                 if (!scaler_state->scalers[i].in_use)
3435                         skl_detach_scaler(intel_crtc, i);
3436         }
3437 }
3438
3439 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3440                      unsigned int rotation)
3441 {
3442         u32 stride;
3443
3444         if (plane >= fb->format->num_planes)
3445                 return 0;
3446
3447         stride = intel_fb_pitch(fb, plane, rotation);
3448
3449         /*
3450          * The stride is either expressed as a multiple of 64 bytes chunks for
3451          * linear buffers or in number of tiles for tiled buffers.
3452          */
3453         if (drm_rotation_90_or_270(rotation))
3454                 stride /= intel_tile_height(fb, plane);
3455         else
3456                 stride /= intel_fb_stride_alignment(fb, plane);
3457
3458         return stride;
3459 }
3460
3461 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3462 {
3463         switch (pixel_format) {
3464         case DRM_FORMAT_C8:
3465                 return PLANE_CTL_FORMAT_INDEXED;
3466         case DRM_FORMAT_RGB565:
3467                 return PLANE_CTL_FORMAT_RGB_565;
3468         case DRM_FORMAT_XBGR8888:
3469         case DRM_FORMAT_ABGR8888:
3470                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3471         case DRM_FORMAT_XRGB8888:
3472         case DRM_FORMAT_ARGB8888:
3473                 return PLANE_CTL_FORMAT_XRGB_8888;
3474         case DRM_FORMAT_XRGB2101010:
3475                 return PLANE_CTL_FORMAT_XRGB_2101010;
3476         case DRM_FORMAT_XBGR2101010:
3477                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3478         case DRM_FORMAT_YUYV:
3479                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3480         case DRM_FORMAT_YVYU:
3481                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3482         case DRM_FORMAT_UYVY:
3483                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3484         case DRM_FORMAT_VYUY:
3485                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3486         default:
3487                 MISSING_CASE(pixel_format);
3488         }
3489
3490         return 0;
3491 }
3492
3493 /*
3494  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3495  * to be already pre-multiplied. We need to add a knob (or a different
3496  * DRM_FORMAT) for user-space to configure that.
3497  */
3498 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3499 {
3500         switch (pixel_format) {
3501         case DRM_FORMAT_ABGR8888:
3502         case DRM_FORMAT_ARGB8888:
3503                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3504         default:
3505                 return PLANE_CTL_ALPHA_DISABLE;
3506         }
3507 }
3508
3509 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3510 {
3511         switch (pixel_format) {
3512         case DRM_FORMAT_ABGR8888:
3513         case DRM_FORMAT_ARGB8888:
3514                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3515         default:
3516                 return PLANE_COLOR_ALPHA_DISABLE;
3517         }
3518 }
3519
3520 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3521 {
3522         switch (fb_modifier) {
3523         case DRM_FORMAT_MOD_LINEAR:
3524                 break;
3525         case I915_FORMAT_MOD_X_TILED:
3526                 return PLANE_CTL_TILED_X;
3527         case I915_FORMAT_MOD_Y_TILED:
3528                 return PLANE_CTL_TILED_Y;
3529         case I915_FORMAT_MOD_Y_TILED_CCS:
3530                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3531         case I915_FORMAT_MOD_Yf_TILED:
3532                 return PLANE_CTL_TILED_YF;
3533         case I915_FORMAT_MOD_Yf_TILED_CCS:
3534                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3535         default:
3536                 MISSING_CASE(fb_modifier);
3537         }
3538
3539         return 0;
3540 }
3541
3542 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3543 {
3544         switch (rotate) {
3545         case DRM_MODE_ROTATE_0:
3546                 break;
3547         /*
3548          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3549          * while i915 HW rotation is clockwise, thats why this swapping.
3550          */
3551         case DRM_MODE_ROTATE_90:
3552                 return PLANE_CTL_ROTATE_270;
3553         case DRM_MODE_ROTATE_180:
3554                 return PLANE_CTL_ROTATE_180;
3555         case DRM_MODE_ROTATE_270:
3556                 return PLANE_CTL_ROTATE_90;
3557         default:
3558                 MISSING_CASE(rotate);
3559         }
3560
3561         return 0;
3562 }
3563
3564 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3565 {
3566         switch (reflect) {
3567         case 0:
3568                 break;
3569         case DRM_MODE_REFLECT_X:
3570                 return PLANE_CTL_FLIP_HORIZONTAL;
3571         case DRM_MODE_REFLECT_Y:
3572         default:
3573                 MISSING_CASE(reflect);
3574         }
3575
3576         return 0;
3577 }
3578
3579 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3580                   const struct intel_plane_state *plane_state)
3581 {
3582         struct drm_i915_private *dev_priv =
3583                 to_i915(plane_state->base.plane->dev);
3584         const struct drm_framebuffer *fb = plane_state->base.fb;
3585         unsigned int rotation = plane_state->base.rotation;
3586         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3587         u32 plane_ctl;
3588
3589         plane_ctl = PLANE_CTL_ENABLE;
3590
3591         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3592                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3593                 plane_ctl |=
3594                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3595                         PLANE_CTL_PIPE_CSC_ENABLE |
3596                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3597
3598                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3599                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3600
3601                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3602                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3603         }
3604
3605         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3606         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3607         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3608
3609         if (INTEL_GEN(dev_priv) >= 10)
3610                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3611                                                 DRM_MODE_REFLECT_MASK);
3612
3613         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3614                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3615         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3616                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3617
3618         return plane_ctl;
3619 }
3620
3621 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3622                         const struct intel_plane_state *plane_state)
3623 {
3624         const struct drm_framebuffer *fb = plane_state->base.fb;
3625         u32 plane_color_ctl = 0;
3626
3627         plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3628         plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3629         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3630         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3631
3632         if (intel_format_is_yuv(fb->format->format)) {
3633                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3634                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3635                 else
3636                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3637
3638                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3639                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3640         }
3641
3642         return plane_color_ctl;
3643 }
3644
3645 static int
3646 __intel_display_resume(struct drm_device *dev,
3647                        struct drm_atomic_state *state,
3648                        struct drm_modeset_acquire_ctx *ctx)
3649 {
3650         struct drm_crtc_state *crtc_state;
3651         struct drm_crtc *crtc;
3652         int i, ret;
3653
3654         intel_modeset_setup_hw_state(dev, ctx);
3655         i915_redisable_vga(to_i915(dev));
3656
3657         if (!state)
3658                 return 0;
3659
3660         /*
3661          * We've duplicated the state, pointers to the old state are invalid.
3662          *
3663          * Don't attempt to use the old state until we commit the duplicated state.
3664          */
3665         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3666                 /*
3667                  * Force recalculation even if we restore
3668                  * current state. With fast modeset this may not result
3669                  * in a modeset when the state is compatible.
3670                  */
3671                 crtc_state->mode_changed = true;
3672         }
3673
3674         /* ignore any reset values/BIOS leftovers in the WM registers */
3675         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3676                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3677
3678         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3679
3680         WARN_ON(ret == -EDEADLK);
3681         return ret;
3682 }
3683
3684 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3685 {
3686         return intel_has_gpu_reset(dev_priv) &&
3687                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3688 }
3689
3690 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3691 {
3692         struct drm_device *dev = &dev_priv->drm;
3693         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3694         struct drm_atomic_state *state;
3695         int ret;
3696
3697         /* reset doesn't touch the display */
3698         if (!i915_modparams.force_reset_modeset_test &&
3699             !gpu_reset_clobbers_display(dev_priv))
3700                 return;
3701
3702         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3703         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3704         wake_up_all(&dev_priv->gpu_error.wait_queue);
3705
3706         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3707                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3708                 i915_gem_set_wedged(dev_priv);
3709         }
3710
3711         /*
3712          * Need mode_config.mutex so that we don't
3713          * trample ongoing ->detect() and whatnot.
3714          */
3715         mutex_lock(&dev->mode_config.mutex);
3716         drm_modeset_acquire_init(ctx, 0);
3717         while (1) {
3718                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3719                 if (ret != -EDEADLK)
3720                         break;
3721
3722                 drm_modeset_backoff(ctx);
3723         }
3724         /*
3725          * Disabling the crtcs gracefully seems nicer. Also the
3726          * g33 docs say we should at least disable all the planes.
3727          */
3728         state = drm_atomic_helper_duplicate_state(dev, ctx);
3729         if (IS_ERR(state)) {
3730                 ret = PTR_ERR(state);
3731                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3732                 return;
3733         }
3734
3735         ret = drm_atomic_helper_disable_all(dev, ctx);
3736         if (ret) {
3737                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3738                 drm_atomic_state_put(state);
3739                 return;
3740         }
3741
3742         dev_priv->modeset_restore_state = state;
3743         state->acquire_ctx = ctx;
3744 }
3745
3746 void intel_finish_reset(struct drm_i915_private *dev_priv)
3747 {
3748         struct drm_device *dev = &dev_priv->drm;
3749         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3750         struct drm_atomic_state *state;
3751         int ret;
3752
3753         /* reset doesn't touch the display */
3754         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3755                 return;
3756
3757         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3758         if (!state)
3759                 goto unlock;
3760
3761         /* reset doesn't touch the display */
3762         if (!gpu_reset_clobbers_display(dev_priv)) {
3763                 /* for testing only restore the display */
3764                 ret = __intel_display_resume(dev, state, ctx);
3765                 if (ret)
3766                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3767         } else {
3768                 /*
3769                  * The display has been reset as well,
3770                  * so need a full re-initialization.
3771                  */
3772                 intel_runtime_pm_disable_interrupts(dev_priv);
3773                 intel_runtime_pm_enable_interrupts(dev_priv);
3774
3775                 intel_pps_unlock_regs_wa(dev_priv);
3776                 intel_modeset_init_hw(dev);
3777                 intel_init_clock_gating(dev_priv);
3778
3779                 spin_lock_irq(&dev_priv->irq_lock);
3780                 if (dev_priv->display.hpd_irq_setup)
3781                         dev_priv->display.hpd_irq_setup(dev_priv);
3782                 spin_unlock_irq(&dev_priv->irq_lock);
3783
3784                 ret = __intel_display_resume(dev, state, ctx);
3785                 if (ret)
3786                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3787
3788                 intel_hpd_init(dev_priv);
3789         }
3790
3791         drm_atomic_state_put(state);
3792 unlock:
3793         drm_modeset_drop_locks(ctx);
3794         drm_modeset_acquire_fini(ctx);
3795         mutex_unlock(&dev->mode_config.mutex);
3796
3797         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3798 }
3799
3800 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3801                                      const struct intel_crtc_state *new_crtc_state)
3802 {
3803         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3804         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3805
3806         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3807         crtc->base.mode = new_crtc_state->base.mode;
3808
3809         /*
3810          * Update pipe size and adjust fitter if needed: the reason for this is
3811          * that in compute_mode_changes we check the native mode (not the pfit
3812          * mode) to see if we can flip rather than do a full mode set. In the
3813          * fastboot case, we'll flip, but if we don't update the pipesrc and
3814          * pfit state, we'll end up with a big fb scanned out into the wrong
3815          * sized surface.
3816          */
3817
3818         I915_WRITE(PIPESRC(crtc->pipe),
3819                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3820                    (new_crtc_state->pipe_src_h - 1));
3821
3822         /* on skylake this is done by detaching scalers */
3823         if (INTEL_GEN(dev_priv) >= 9) {
3824                 skl_detach_scalers(crtc);
3825
3826                 if (new_crtc_state->pch_pfit.enabled)
3827                         skylake_pfit_enable(crtc);
3828         } else if (HAS_PCH_SPLIT(dev_priv)) {
3829                 if (new_crtc_state->pch_pfit.enabled)
3830                         ironlake_pfit_enable(crtc);
3831                 else if (old_crtc_state->pch_pfit.enabled)
3832                         ironlake_pfit_disable(crtc, true);
3833         }
3834 }
3835
3836 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3837 {
3838         struct drm_device *dev = crtc->base.dev;
3839         struct drm_i915_private *dev_priv = to_i915(dev);
3840         int pipe = crtc->pipe;
3841         i915_reg_t reg;
3842         u32 temp;
3843
3844         /* enable normal train */
3845         reg = FDI_TX_CTL(pipe);
3846         temp = I915_READ(reg);
3847         if (IS_IVYBRIDGE(dev_priv)) {
3848                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3849                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3850         } else {
3851                 temp &= ~FDI_LINK_TRAIN_NONE;
3852                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3853         }
3854         I915_WRITE(reg, temp);
3855
3856         reg = FDI_RX_CTL(pipe);
3857         temp = I915_READ(reg);
3858         if (HAS_PCH_CPT(dev_priv)) {
3859                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3860                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3861         } else {
3862                 temp &= ~FDI_LINK_TRAIN_NONE;
3863                 temp |= FDI_LINK_TRAIN_NONE;
3864         }
3865         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3866
3867         /* wait one idle pattern time */
3868         POSTING_READ(reg);
3869         udelay(1000);
3870
3871         /* IVB wants error correction enabled */
3872         if (IS_IVYBRIDGE(dev_priv))
3873                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3874                            FDI_FE_ERRC_ENABLE);
3875 }
3876
3877 /* The FDI link training functions for ILK/Ibexpeak. */
3878 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3879                                     const struct intel_crtc_state *crtc_state)
3880 {
3881         struct drm_device *dev = crtc->base.dev;
3882         struct drm_i915_private *dev_priv = to_i915(dev);
3883         int pipe = crtc->pipe;
3884         i915_reg_t reg;
3885         u32 temp, tries;
3886
3887         /* FDI needs bits from pipe first */
3888         assert_pipe_enabled(dev_priv, pipe);
3889
3890         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3891            for train result */
3892         reg = FDI_RX_IMR(pipe);
3893         temp = I915_READ(reg);
3894         temp &= ~FDI_RX_SYMBOL_LOCK;
3895         temp &= ~FDI_RX_BIT_LOCK;
3896         I915_WRITE(reg, temp);
3897         I915_READ(reg);
3898         udelay(150);
3899
3900         /* enable CPU FDI TX and PCH FDI RX */
3901         reg = FDI_TX_CTL(pipe);
3902         temp = I915_READ(reg);
3903         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3904         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3905         temp &= ~FDI_LINK_TRAIN_NONE;
3906         temp |= FDI_LINK_TRAIN_PATTERN_1;
3907         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3908
3909         reg = FDI_RX_CTL(pipe);
3910         temp = I915_READ(reg);
3911         temp &= ~FDI_LINK_TRAIN_NONE;
3912         temp |= FDI_LINK_TRAIN_PATTERN_1;
3913         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3914
3915         POSTING_READ(reg);
3916         udelay(150);
3917
3918         /* Ironlake workaround, enable clock pointer after FDI enable*/
3919         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3920         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3921                    FDI_RX_PHASE_SYNC_POINTER_EN);
3922
3923         reg = FDI_RX_IIR(pipe);
3924         for (tries = 0; tries < 5; tries++) {
3925                 temp = I915_READ(reg);
3926                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3927
3928                 if ((temp & FDI_RX_BIT_LOCK)) {
3929                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3930                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3931                         break;
3932                 }
3933         }
3934         if (tries == 5)
3935                 DRM_ERROR("FDI train 1 fail!\n");
3936
3937         /* Train 2 */
3938         reg = FDI_TX_CTL(pipe);
3939         temp = I915_READ(reg);
3940         temp &= ~FDI_LINK_TRAIN_NONE;
3941         temp |= FDI_LINK_TRAIN_PATTERN_2;
3942         I915_WRITE(reg, temp);
3943
3944         reg = FDI_RX_CTL(pipe);
3945         temp = I915_READ(reg);
3946         temp &= ~FDI_LINK_TRAIN_NONE;
3947         temp |= FDI_LINK_TRAIN_PATTERN_2;
3948         I915_WRITE(reg, temp);
3949
3950         POSTING_READ(reg);
3951         udelay(150);
3952
3953         reg = FDI_RX_IIR(pipe);
3954         for (tries = 0; tries < 5; tries++) {
3955                 temp = I915_READ(reg);
3956                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3957
3958                 if (temp & FDI_RX_SYMBOL_LOCK) {
3959                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3960                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3961                         break;
3962                 }
3963         }
3964         if (tries == 5)
3965                 DRM_ERROR("FDI train 2 fail!\n");
3966
3967         DRM_DEBUG_KMS("FDI train done\n");
3968
3969 }
3970
3971 static const int snb_b_fdi_train_param[] = {
3972         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3973         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3974         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3975         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3976 };
3977
3978 /* The FDI link training functions for SNB/Cougarpoint. */
3979 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3980                                 const struct intel_crtc_state *crtc_state)
3981 {
3982         struct drm_device *dev = crtc->base.dev;
3983         struct drm_i915_private *dev_priv = to_i915(dev);
3984         int pipe = crtc->pipe;
3985         i915_reg_t reg;
3986         u32 temp, i, retry;
3987
3988         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3989            for train result */
3990         reg = FDI_RX_IMR(pipe);
3991         temp = I915_READ(reg);
3992         temp &= ~FDI_RX_SYMBOL_LOCK;
3993         temp &= ~FDI_RX_BIT_LOCK;
3994         I915_WRITE(reg, temp);
3995
3996         POSTING_READ(reg);
3997         udelay(150);
3998
3999         /* enable CPU FDI TX and PCH FDI RX */
4000         reg = FDI_TX_CTL(pipe);
4001         temp = I915_READ(reg);
4002         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4003         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4004         temp &= ~FDI_LINK_TRAIN_NONE;
4005         temp |= FDI_LINK_TRAIN_PATTERN_1;
4006         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4007         /* SNB-B */
4008         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4009         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4010
4011         I915_WRITE(FDI_RX_MISC(pipe),
4012                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4013
4014         reg = FDI_RX_CTL(pipe);
4015         temp = I915_READ(reg);
4016         if (HAS_PCH_CPT(dev_priv)) {
4017                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4018                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4019         } else {
4020                 temp &= ~FDI_LINK_TRAIN_NONE;
4021                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4022         }
4023         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4024
4025         POSTING_READ(reg);
4026         udelay(150);
4027
4028         for (i = 0; i < 4; i++) {
4029                 reg = FDI_TX_CTL(pipe);
4030                 temp = I915_READ(reg);
4031                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4032                 temp |= snb_b_fdi_train_param[i];
4033                 I915_WRITE(reg, temp);
4034
4035                 POSTING_READ(reg);
4036                 udelay(500);
4037
4038                 for (retry = 0; retry < 5; retry++) {
4039                         reg = FDI_RX_IIR(pipe);
4040                         temp = I915_READ(reg);
4041                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4042                         if (temp & FDI_RX_BIT_LOCK) {
4043                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4044                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4045                                 break;
4046                         }
4047                         udelay(50);
4048                 }
4049                 if (retry < 5)
4050                         break;
4051         }
4052         if (i == 4)
4053                 DRM_ERROR("FDI train 1 fail!\n");
4054
4055         /* Train 2 */
4056         reg = FDI_TX_CTL(pipe);
4057         temp = I915_READ(reg);
4058         temp &= ~FDI_LINK_TRAIN_NONE;
4059         temp |= FDI_LINK_TRAIN_PATTERN_2;
4060         if (IS_GEN6(dev_priv)) {
4061                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4062                 /* SNB-B */
4063                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4064         }
4065         I915_WRITE(reg, temp);
4066
4067         reg = FDI_RX_CTL(pipe);
4068         temp = I915_READ(reg);
4069         if (HAS_PCH_CPT(dev_priv)) {
4070                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4071                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4072         } else {
4073                 temp &= ~FDI_LINK_TRAIN_NONE;
4074                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4075         }
4076         I915_WRITE(reg, temp);
4077
4078         POSTING_READ(reg);
4079         udelay(150);
4080
4081         for (i = 0; i < 4; i++) {
4082                 reg = FDI_TX_CTL(pipe);
4083                 temp = I915_READ(reg);
4084                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4085                 temp |= snb_b_fdi_train_param[i];
4086                 I915_WRITE(reg, temp);
4087
4088                 POSTING_READ(reg);
4089                 udelay(500);
4090
4091                 for (retry = 0; retry < 5; retry++) {
4092                         reg = FDI_RX_IIR(pipe);
4093                         temp = I915_READ(reg);
4094                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4095                         if (temp & FDI_RX_SYMBOL_LOCK) {
4096                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4097                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4098                                 break;
4099                         }
4100                         udelay(50);
4101                 }
4102                 if (retry < 5)
4103                         break;
4104         }
4105         if (i == 4)
4106                 DRM_ERROR("FDI train 2 fail!\n");
4107
4108         DRM_DEBUG_KMS("FDI train done.\n");
4109 }
4110
4111 /* Manual link training for Ivy Bridge A0 parts */
4112 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4113                                       const struct intel_crtc_state *crtc_state)
4114 {
4115         struct drm_device *dev = crtc->base.dev;
4116         struct drm_i915_private *dev_priv = to_i915(dev);
4117         int pipe = crtc->pipe;
4118         i915_reg_t reg;
4119         u32 temp, i, j;
4120
4121         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4122            for train result */
4123         reg = FDI_RX_IMR(pipe);
4124         temp = I915_READ(reg);
4125         temp &= ~FDI_RX_SYMBOL_LOCK;
4126         temp &= ~FDI_RX_BIT_LOCK;
4127         I915_WRITE(reg, temp);
4128
4129         POSTING_READ(reg);
4130         udelay(150);
4131
4132         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4133                       I915_READ(FDI_RX_IIR(pipe)));
4134
4135         /* Try each vswing and preemphasis setting twice before moving on */
4136         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4137                 /* disable first in case we need to retry */
4138                 reg = FDI_TX_CTL(pipe);
4139                 temp = I915_READ(reg);
4140                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4141                 temp &= ~FDI_TX_ENABLE;
4142                 I915_WRITE(reg, temp);
4143
4144                 reg = FDI_RX_CTL(pipe);
4145                 temp = I915_READ(reg);
4146                 temp &= ~FDI_LINK_TRAIN_AUTO;
4147                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4148                 temp &= ~FDI_RX_ENABLE;
4149                 I915_WRITE(reg, temp);
4150
4151                 /* enable CPU FDI TX and PCH FDI RX */
4152                 reg = FDI_TX_CTL(pipe);
4153                 temp = I915_READ(reg);
4154                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4155                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4156                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4157                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4158                 temp |= snb_b_fdi_train_param[j/2];
4159                 temp |= FDI_COMPOSITE_SYNC;
4160                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4161
4162                 I915_WRITE(FDI_RX_MISC(pipe),
4163                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4164
4165                 reg = FDI_RX_CTL(pipe);
4166                 temp = I915_READ(reg);
4167                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4168                 temp |= FDI_COMPOSITE_SYNC;
4169                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4170
4171                 POSTING_READ(reg);
4172                 udelay(1); /* should be 0.5us */
4173
4174                 for (i = 0; i < 4; i++) {
4175                         reg = FDI_RX_IIR(pipe);
4176                         temp = I915_READ(reg);
4177                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4178
4179                         if (temp & FDI_RX_BIT_LOCK ||
4180                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4181                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4182                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4183                                               i);
4184                                 break;
4185                         }
4186                         udelay(1); /* should be 0.5us */
4187                 }
4188                 if (i == 4) {
4189                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4190                         continue;
4191                 }
4192
4193                 /* Train 2 */
4194                 reg = FDI_TX_CTL(pipe);
4195                 temp = I915_READ(reg);
4196                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4197                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4198                 I915_WRITE(reg, temp);
4199
4200                 reg = FDI_RX_CTL(pipe);
4201                 temp = I915_READ(reg);
4202                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4203                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4204                 I915_WRITE(reg, temp);
4205
4206                 POSTING_READ(reg);
4207                 udelay(2); /* should be 1.5us */
4208
4209                 for (i = 0; i < 4; i++) {
4210                         reg = FDI_RX_IIR(pipe);
4211                         temp = I915_READ(reg);
4212                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4213
4214                         if (temp & FDI_RX_SYMBOL_LOCK ||
4215                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4216                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4217                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4218                                               i);
4219                                 goto train_done;
4220                         }
4221                         udelay(2); /* should be 1.5us */
4222                 }
4223                 if (i == 4)
4224                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4225         }
4226
4227 train_done:
4228         DRM_DEBUG_KMS("FDI train done.\n");
4229 }
4230
4231 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4232 {
4233         struct drm_device *dev = intel_crtc->base.dev;
4234         struct drm_i915_private *dev_priv = to_i915(dev);
4235         int pipe = intel_crtc->pipe;
4236         i915_reg_t reg;
4237         u32 temp;
4238
4239         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4240         reg = FDI_RX_CTL(pipe);
4241         temp = I915_READ(reg);
4242         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4243         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4244         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4245         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4246
4247         POSTING_READ(reg);
4248         udelay(200);
4249
4250         /* Switch from Rawclk to PCDclk */
4251         temp = I915_READ(reg);
4252         I915_WRITE(reg, temp | FDI_PCDCLK);
4253
4254         POSTING_READ(reg);
4255         udelay(200);
4256
4257         /* Enable CPU FDI TX PLL, always on for Ironlake */
4258         reg = FDI_TX_CTL(pipe);
4259         temp = I915_READ(reg);
4260         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4261                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4262
4263                 POSTING_READ(reg);
4264                 udelay(100);
4265         }
4266 }
4267
4268 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4269 {
4270         struct drm_device *dev = intel_crtc->base.dev;
4271         struct drm_i915_private *dev_priv = to_i915(dev);
4272         int pipe = intel_crtc->pipe;
4273         i915_reg_t reg;
4274         u32 temp;
4275
4276         /* Switch from PCDclk to Rawclk */
4277         reg = FDI_RX_CTL(pipe);
4278         temp = I915_READ(reg);
4279         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4280
4281         /* Disable CPU FDI TX PLL */
4282         reg = FDI_TX_CTL(pipe);
4283         temp = I915_READ(reg);
4284         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4285
4286         POSTING_READ(reg);
4287         udelay(100);
4288
4289         reg = FDI_RX_CTL(pipe);
4290         temp = I915_READ(reg);
4291         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4292
4293         /* Wait for the clocks to turn off. */
4294         POSTING_READ(reg);
4295         udelay(100);
4296 }
4297
4298 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4299 {
4300         struct drm_device *dev = crtc->dev;
4301         struct drm_i915_private *dev_priv = to_i915(dev);
4302         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4303         int pipe = intel_crtc->pipe;
4304         i915_reg_t reg;
4305         u32 temp;
4306
4307         /* disable CPU FDI tx and PCH FDI rx */
4308         reg = FDI_TX_CTL(pipe);
4309         temp = I915_READ(reg);
4310         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4311         POSTING_READ(reg);
4312
4313         reg = FDI_RX_CTL(pipe);
4314         temp = I915_READ(reg);
4315         temp &= ~(0x7 << 16);
4316         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4317         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4318
4319         POSTING_READ(reg);
4320         udelay(100);
4321
4322         /* Ironlake workaround, disable clock pointer after downing FDI */
4323         if (HAS_PCH_IBX(dev_priv))
4324                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4325
4326         /* still set train pattern 1 */
4327         reg = FDI_TX_CTL(pipe);
4328         temp = I915_READ(reg);
4329         temp &= ~FDI_LINK_TRAIN_NONE;
4330         temp |= FDI_LINK_TRAIN_PATTERN_1;
4331         I915_WRITE(reg, temp);
4332
4333         reg = FDI_RX_CTL(pipe);
4334         temp = I915_READ(reg);
4335         if (HAS_PCH_CPT(dev_priv)) {
4336                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4337                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4338         } else {
4339                 temp &= ~FDI_LINK_TRAIN_NONE;
4340                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4341         }
4342         /* BPC in FDI rx is consistent with that in PIPECONF */
4343         temp &= ~(0x07 << 16);
4344         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4345         I915_WRITE(reg, temp);
4346
4347         POSTING_READ(reg);
4348         udelay(100);
4349 }
4350
4351 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4352 {
4353         struct drm_crtc *crtc;
4354         bool cleanup_done;
4355
4356         drm_for_each_crtc(crtc, &dev_priv->drm) {
4357                 struct drm_crtc_commit *commit;
4358                 spin_lock(&crtc->commit_lock);
4359                 commit = list_first_entry_or_null(&crtc->commit_list,
4360                                                   struct drm_crtc_commit, commit_entry);
4361                 cleanup_done = commit ?
4362                         try_wait_for_completion(&commit->cleanup_done) : true;
4363                 spin_unlock(&crtc->commit_lock);
4364
4365                 if (cleanup_done)
4366                         continue;
4367
4368                 drm_crtc_wait_one_vblank(crtc);
4369
4370                 return true;
4371         }
4372
4373         return false;
4374 }
4375
4376 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4377 {
4378         u32 temp;
4379
4380         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4381
4382         mutex_lock(&dev_priv->sb_lock);
4383
4384         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4385         temp |= SBI_SSCCTL_DISABLE;
4386         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4387
4388         mutex_unlock(&dev_priv->sb_lock);
4389 }
4390
4391 /* Program iCLKIP clock to the desired frequency */
4392 static void lpt_program_iclkip(struct intel_crtc *crtc)
4393 {
4394         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4395         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4396         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4397         u32 temp;
4398
4399         lpt_disable_iclkip(dev_priv);
4400
4401         /* The iCLK virtual clock root frequency is in MHz,
4402          * but the adjusted_mode->crtc_clock in in KHz. To get the
4403          * divisors, it is necessary to divide one by another, so we
4404          * convert the virtual clock precision to KHz here for higher
4405          * precision.
4406          */
4407         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4408                 u32 iclk_virtual_root_freq = 172800 * 1000;
4409                 u32 iclk_pi_range = 64;
4410                 u32 desired_divisor;
4411
4412                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4413                                                     clock << auxdiv);
4414                 divsel = (desired_divisor / iclk_pi_range) - 2;
4415                 phaseinc = desired_divisor % iclk_pi_range;
4416
4417                 /*
4418                  * Near 20MHz is a corner case which is
4419                  * out of range for the 7-bit divisor
4420                  */
4421                 if (divsel <= 0x7f)
4422                         break;
4423         }
4424
4425         /* This should not happen with any sane values */
4426         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4427                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4428         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4429                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4430
4431         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4432                         clock,
4433                         auxdiv,
4434                         divsel,
4435                         phasedir,
4436                         phaseinc);
4437
4438         mutex_lock(&dev_priv->sb_lock);
4439
4440         /* Program SSCDIVINTPHASE6 */
4441         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4442         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4443         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4444         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4445         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4446         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4447         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4448         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4449
4450         /* Program SSCAUXDIV */
4451         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4452         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4453         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4454         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4455
4456         /* Enable modulator and associated divider */
4457         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4458         temp &= ~SBI_SSCCTL_DISABLE;
4459         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4460
4461         mutex_unlock(&dev_priv->sb_lock);
4462
4463         /* Wait for initialization time */
4464         udelay(24);
4465
4466         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4467 }
4468
4469 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4470 {
4471         u32 divsel, phaseinc, auxdiv;
4472         u32 iclk_virtual_root_freq = 172800 * 1000;
4473         u32 iclk_pi_range = 64;
4474         u32 desired_divisor;
4475         u32 temp;
4476
4477         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4478                 return 0;
4479
4480         mutex_lock(&dev_priv->sb_lock);
4481
4482         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4483         if (temp & SBI_SSCCTL_DISABLE) {
4484                 mutex_unlock(&dev_priv->sb_lock);
4485                 return 0;
4486         }
4487
4488         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4489         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4490                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4491         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4492                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4493
4494         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4495         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4496                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4497
4498         mutex_unlock(&dev_priv->sb_lock);
4499
4500         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4501
4502         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4503                                  desired_divisor << auxdiv);
4504 }
4505
4506 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4507                                                 enum pipe pch_transcoder)
4508 {
4509         struct drm_device *dev = crtc->base.dev;
4510         struct drm_i915_private *dev_priv = to_i915(dev);
4511         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4512
4513         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4514                    I915_READ(HTOTAL(cpu_transcoder)));
4515         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4516                    I915_READ(HBLANK(cpu_transcoder)));
4517         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4518                    I915_READ(HSYNC(cpu_transcoder)));
4519
4520         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4521                    I915_READ(VTOTAL(cpu_transcoder)));
4522         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4523                    I915_READ(VBLANK(cpu_transcoder)));
4524         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4525                    I915_READ(VSYNC(cpu_transcoder)));
4526         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4527                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4528 }
4529
4530 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4531 {
4532         struct drm_i915_private *dev_priv = to_i915(dev);
4533         uint32_t temp;
4534
4535         temp = I915_READ(SOUTH_CHICKEN1);
4536         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4537                 return;
4538
4539         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4540         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4541
4542         temp &= ~FDI_BC_BIFURCATION_SELECT;
4543         if (enable)
4544                 temp |= FDI_BC_BIFURCATION_SELECT;
4545
4546         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4547         I915_WRITE(SOUTH_CHICKEN1, temp);
4548         POSTING_READ(SOUTH_CHICKEN1);
4549 }
4550
4551 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4552 {
4553         struct drm_device *dev = intel_crtc->base.dev;
4554
4555         switch (intel_crtc->pipe) {
4556         case PIPE_A:
4557                 break;
4558         case PIPE_B:
4559                 if (intel_crtc->config->fdi_lanes > 2)
4560                         cpt_set_fdi_bc_bifurcation(dev, false);
4561                 else
4562                         cpt_set_fdi_bc_bifurcation(dev, true);
4563
4564                 break;
4565         case PIPE_C:
4566                 cpt_set_fdi_bc_bifurcation(dev, true);
4567
4568                 break;
4569         default:
4570                 BUG();
4571         }
4572 }
4573
4574 /* Return which DP Port should be selected for Transcoder DP control */
4575 static enum port
4576 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4577 {
4578         struct drm_device *dev = crtc->base.dev;
4579         struct intel_encoder *encoder;
4580
4581         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4582                 if (encoder->type == INTEL_OUTPUT_DP ||
4583                     encoder->type == INTEL_OUTPUT_EDP)
4584                         return encoder->port;
4585         }
4586
4587         return -1;
4588 }
4589
4590 /*
4591  * Enable PCH resources required for PCH ports:
4592  *   - PCH PLLs
4593  *   - FDI training & RX/TX
4594  *   - update transcoder timings
4595  *   - DP transcoding bits
4596  *   - transcoder
4597  */
4598 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4599 {
4600         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4601         struct drm_device *dev = crtc->base.dev;
4602         struct drm_i915_private *dev_priv = to_i915(dev);
4603         int pipe = crtc->pipe;
4604         u32 temp;
4605
4606         assert_pch_transcoder_disabled(dev_priv, pipe);
4607
4608         if (IS_IVYBRIDGE(dev_priv))
4609                 ivybridge_update_fdi_bc_bifurcation(crtc);
4610
4611         /* Write the TU size bits before fdi link training, so that error
4612          * detection works. */
4613         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4614                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4615
4616         /* For PCH output, training FDI link */
4617         dev_priv->display.fdi_link_train(crtc, crtc_state);
4618
4619         /* We need to program the right clock selection before writing the pixel
4620          * mutliplier into the DPLL. */
4621         if (HAS_PCH_CPT(dev_priv)) {
4622                 u32 sel;
4623
4624                 temp = I915_READ(PCH_DPLL_SEL);
4625                 temp |= TRANS_DPLL_ENABLE(pipe);
4626                 sel = TRANS_DPLLB_SEL(pipe);
4627                 if (crtc_state->shared_dpll ==
4628                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4629                         temp |= sel;
4630                 else
4631                         temp &= ~sel;
4632                 I915_WRITE(PCH_DPLL_SEL, temp);
4633         }
4634
4635         /* XXX: pch pll's can be enabled any time before we enable the PCH
4636          * transcoder, and we actually should do this to not upset any PCH
4637          * transcoder that already use the clock when we share it.
4638          *
4639          * Note that enable_shared_dpll tries to do the right thing, but
4640          * get_shared_dpll unconditionally resets the pll - we need that to have
4641          * the right LVDS enable sequence. */
4642         intel_enable_shared_dpll(crtc);
4643
4644         /* set transcoder timing, panel must allow it */
4645         assert_panel_unlocked(dev_priv, pipe);
4646         ironlake_pch_transcoder_set_timings(crtc, pipe);
4647
4648         intel_fdi_normal_train(crtc);
4649
4650         /* For PCH DP, enable TRANS_DP_CTL */
4651         if (HAS_PCH_CPT(dev_priv) &&
4652             intel_crtc_has_dp_encoder(crtc_state)) {
4653                 const struct drm_display_mode *adjusted_mode =
4654                         &crtc_state->base.adjusted_mode;
4655                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4656                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4657                 temp = I915_READ(reg);
4658                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4659                           TRANS_DP_SYNC_MASK |
4660                           TRANS_DP_BPC_MASK);
4661                 temp |= TRANS_DP_OUTPUT_ENABLE;
4662                 temp |= bpc << 9; /* same format but at 11:9 */
4663
4664                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4665                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4666                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4667                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4668
4669                 switch (intel_trans_dp_port_sel(crtc)) {
4670                 case PORT_B:
4671                         temp |= TRANS_DP_PORT_SEL_B;
4672                         break;
4673                 case PORT_C:
4674                         temp |= TRANS_DP_PORT_SEL_C;
4675                         break;
4676                 case PORT_D:
4677                         temp |= TRANS_DP_PORT_SEL_D;
4678                         break;
4679                 default:
4680                         BUG();
4681                 }
4682
4683                 I915_WRITE(reg, temp);
4684         }
4685
4686         ironlake_enable_pch_transcoder(dev_priv, pipe);
4687 }
4688
4689 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4690 {
4691         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4692         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4693         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4694
4695         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4696
4697         lpt_program_iclkip(crtc);
4698
4699         /* Set transcoder timing. */
4700         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4701
4702         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4703 }
4704
4705 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4706 {
4707         struct drm_i915_private *dev_priv = to_i915(dev);
4708         i915_reg_t dslreg = PIPEDSL(pipe);
4709         u32 temp;
4710
4711         temp = I915_READ(dslreg);
4712         udelay(500);
4713         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4714                 if (wait_for(I915_READ(dslreg) != temp, 5))
4715                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4716         }
4717 }
4718
4719 static int
4720 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4721                   unsigned int scaler_user, int *scaler_id,
4722                   int src_w, int src_h, int dst_w, int dst_h)
4723 {
4724         struct intel_crtc_scaler_state *scaler_state =
4725                 &crtc_state->scaler_state;
4726         struct intel_crtc *intel_crtc =
4727                 to_intel_crtc(crtc_state->base.crtc);
4728         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4729         const struct drm_display_mode *adjusted_mode =
4730                 &crtc_state->base.adjusted_mode;
4731         int need_scaling;
4732
4733         /*
4734          * Src coordinates are already rotated by 270 degrees for
4735          * the 90/270 degree plane rotation cases (to match the
4736          * GTT mapping), hence no need to account for rotation here.
4737          */
4738         need_scaling = src_w != dst_w || src_h != dst_h;
4739
4740         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4741                 need_scaling = true;
4742
4743         /*
4744          * Scaling/fitting not supported in IF-ID mode in GEN9+
4745          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4746          * Once NV12 is enabled, handle it here while allocating scaler
4747          * for NV12.
4748          */
4749         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4750             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4751                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4752                 return -EINVAL;
4753         }
4754
4755         /*
4756          * if plane is being disabled or scaler is no more required or force detach
4757          *  - free scaler binded to this plane/crtc
4758          *  - in order to do this, update crtc->scaler_usage
4759          *
4760          * Here scaler state in crtc_state is set free so that
4761          * scaler can be assigned to other user. Actual register
4762          * update to free the scaler is done in plane/panel-fit programming.
4763          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4764          */
4765         if (force_detach || !need_scaling) {
4766                 if (*scaler_id >= 0) {
4767                         scaler_state->scaler_users &= ~(1 << scaler_user);
4768                         scaler_state->scalers[*scaler_id].in_use = 0;
4769
4770                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4771                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4772                                 intel_crtc->pipe, scaler_user, *scaler_id,
4773                                 scaler_state->scaler_users);
4774                         *scaler_id = -1;
4775                 }
4776                 return 0;
4777         }
4778
4779         /* range checks */
4780         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4781             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4782             (IS_GEN11(dev_priv) &&
4783              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4784               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4785             (!IS_GEN11(dev_priv) &&
4786              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4787               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4788                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4789                         "size is out of scaler range\n",
4790                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4791                 return -EINVAL;
4792         }
4793
4794         /* mark this plane as a scaler user in crtc_state */
4795         scaler_state->scaler_users |= (1 << scaler_user);
4796         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4797                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4798                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4799                 scaler_state->scaler_users);
4800
4801         return 0;
4802 }
4803
4804 /**
4805  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4806  *
4807  * @state: crtc's scaler state
4808  *
4809  * Return
4810  *     0 - scaler_usage updated successfully
4811  *    error - requested scaling cannot be supported or other error condition
4812  */
4813 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4814 {
4815         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4816
4817         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4818                 &state->scaler_state.scaler_id,
4819                 state->pipe_src_w, state->pipe_src_h,
4820                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4821 }
4822
4823 /**
4824  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4825  * @crtc_state: crtc's scaler state
4826  * @plane_state: atomic plane state to update
4827  *
4828  * Return
4829  *     0 - scaler_usage updated successfully
4830  *    error - requested scaling cannot be supported or other error condition
4831  */
4832 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4833                                    struct intel_plane_state *plane_state)
4834 {
4835
4836         struct intel_plane *intel_plane =
4837                 to_intel_plane(plane_state->base.plane);
4838         struct drm_framebuffer *fb = plane_state->base.fb;
4839         int ret;
4840
4841         bool force_detach = !fb || !plane_state->base.visible;
4842
4843         ret = skl_update_scaler(crtc_state, force_detach,
4844                                 drm_plane_index(&intel_plane->base),
4845                                 &plane_state->scaler_id,
4846                                 drm_rect_width(&plane_state->base.src) >> 16,
4847                                 drm_rect_height(&plane_state->base.src) >> 16,
4848                                 drm_rect_width(&plane_state->base.dst),
4849                                 drm_rect_height(&plane_state->base.dst));
4850
4851         if (ret || plane_state->scaler_id < 0)
4852                 return ret;
4853
4854         /* check colorkey */
4855         if (plane_state->ckey.flags) {
4856                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4857                               intel_plane->base.base.id,
4858                               intel_plane->base.name);
4859                 return -EINVAL;
4860         }
4861
4862         /* Check src format */
4863         switch (fb->format->format) {
4864         case DRM_FORMAT_RGB565:
4865         case DRM_FORMAT_XBGR8888:
4866         case DRM_FORMAT_XRGB8888:
4867         case DRM_FORMAT_ABGR8888:
4868         case DRM_FORMAT_ARGB8888:
4869         case DRM_FORMAT_XRGB2101010:
4870         case DRM_FORMAT_XBGR2101010:
4871         case DRM_FORMAT_YUYV:
4872         case DRM_FORMAT_YVYU:
4873         case DRM_FORMAT_UYVY:
4874         case DRM_FORMAT_VYUY:
4875                 break;
4876         default:
4877                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4878                               intel_plane->base.base.id, intel_plane->base.name,
4879                               fb->base.id, fb->format->format);
4880                 return -EINVAL;
4881         }
4882
4883         return 0;
4884 }
4885
4886 static void skylake_scaler_disable(struct intel_crtc *crtc)
4887 {
4888         int i;
4889
4890         for (i = 0; i < crtc->num_scalers; i++)
4891                 skl_detach_scaler(crtc, i);
4892 }
4893
4894 static void skylake_pfit_enable(struct intel_crtc *crtc)
4895 {
4896         struct drm_device *dev = crtc->base.dev;
4897         struct drm_i915_private *dev_priv = to_i915(dev);
4898         int pipe = crtc->pipe;
4899         struct intel_crtc_scaler_state *scaler_state =
4900                 &crtc->config->scaler_state;
4901
4902         if (crtc->config->pch_pfit.enabled) {
4903                 int id;
4904
4905                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4906                         return;
4907
4908                 id = scaler_state->scaler_id;
4909                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4910                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4911                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4912                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4913         }
4914 }
4915
4916 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4917 {
4918         struct drm_device *dev = crtc->base.dev;
4919         struct drm_i915_private *dev_priv = to_i915(dev);
4920         int pipe = crtc->pipe;
4921
4922         if (crtc->config->pch_pfit.enabled) {
4923                 /* Force use of hard-coded filter coefficients
4924                  * as some pre-programmed values are broken,
4925                  * e.g. x201.
4926                  */
4927                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4928                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4929                                                  PF_PIPE_SEL_IVB(pipe));
4930                 else
4931                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4932                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4933                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4934         }
4935 }
4936
4937 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
4938 {
4939         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4940         struct drm_device *dev = crtc->base.dev;
4941         struct drm_i915_private *dev_priv = to_i915(dev);
4942
4943         if (!crtc_state->ips_enabled)
4944                 return;
4945
4946         /*
4947          * We can only enable IPS after we enable a plane and wait for a vblank
4948          * This function is called from post_plane_update, which is run after
4949          * a vblank wait.
4950          */
4951         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
4952
4953         if (IS_BROADWELL(dev_priv)) {
4954                 mutex_lock(&dev_priv->pcu_lock);
4955                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
4956                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
4957                 mutex_unlock(&dev_priv->pcu_lock);
4958                 /* Quoting Art Runyan: "its not safe to expect any particular
4959                  * value in IPS_CTL bit 31 after enabling IPS through the
4960                  * mailbox." Moreover, the mailbox may return a bogus state,
4961                  * so we need to just enable it and continue on.
4962                  */
4963         } else {
4964                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4965                 /* The bit only becomes 1 in the next vblank, so this wait here
4966                  * is essentially intel_wait_for_vblank. If we don't have this
4967                  * and don't wait for vblanks until the end of crtc_enable, then
4968                  * the HW state readout code will complain that the expected
4969                  * IPS_CTL value is not the one we read. */
4970                 if (intel_wait_for_register(dev_priv,
4971                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4972                                             50))
4973                         DRM_ERROR("Timed out waiting for IPS enable\n");
4974         }
4975 }
4976
4977 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
4978 {
4979         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4980         struct drm_device *dev = crtc->base.dev;
4981         struct drm_i915_private *dev_priv = to_i915(dev);
4982
4983         if (!crtc_state->ips_enabled)
4984                 return;
4985
4986         if (IS_BROADWELL(dev_priv)) {
4987                 mutex_lock(&dev_priv->pcu_lock);
4988                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4989                 mutex_unlock(&dev_priv->pcu_lock);
4990                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4991                 if (intel_wait_for_register(dev_priv,
4992                                             IPS_CTL, IPS_ENABLE, 0,
4993                                             42))
4994                         DRM_ERROR("Timed out waiting for IPS disable\n");
4995         } else {
4996                 I915_WRITE(IPS_CTL, 0);
4997                 POSTING_READ(IPS_CTL);
4998         }
4999
5000         /* We need to wait for a vblank before we can disable the plane. */
5001         intel_wait_for_vblank(dev_priv, crtc->pipe);
5002 }
5003
5004 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5005 {
5006         if (intel_crtc->overlay) {
5007                 struct drm_device *dev = intel_crtc->base.dev;
5008
5009                 mutex_lock(&dev->struct_mutex);
5010                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5011                 mutex_unlock(&dev->struct_mutex);
5012         }
5013
5014         /* Let userspace switch the overlay on again. In most cases userspace
5015          * has to recompute where to put it anyway.
5016          */
5017 }
5018
5019 /**
5020  * intel_post_enable_primary - Perform operations after enabling primary plane
5021  * @crtc: the CRTC whose primary plane was just enabled
5022  * @new_crtc_state: the enabling state
5023  *
5024  * Performs potentially sleeping operations that must be done after the primary
5025  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5026  * called due to an explicit primary plane update, or due to an implicit
5027  * re-enable that is caused when a sprite plane is updated to no longer
5028  * completely hide the primary plane.
5029  */
5030 static void
5031 intel_post_enable_primary(struct drm_crtc *crtc,
5032                           const struct intel_crtc_state *new_crtc_state)
5033 {
5034         struct drm_device *dev = crtc->dev;
5035         struct drm_i915_private *dev_priv = to_i915(dev);
5036         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5037         int pipe = intel_crtc->pipe;
5038
5039         /*
5040          * Gen2 reports pipe underruns whenever all planes are disabled.
5041          * So don't enable underrun reporting before at least some planes
5042          * are enabled.
5043          * FIXME: Need to fix the logic to work when we turn off all planes
5044          * but leave the pipe running.
5045          */
5046         if (IS_GEN2(dev_priv))
5047                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5048
5049         /* Underruns don't always raise interrupts, so check manually. */
5050         intel_check_cpu_fifo_underruns(dev_priv);
5051         intel_check_pch_fifo_underruns(dev_priv);
5052 }
5053
5054 /* FIXME get rid of this and use pre_plane_update */
5055 static void
5056 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5057 {
5058         struct drm_device *dev = crtc->dev;
5059         struct drm_i915_private *dev_priv = to_i915(dev);
5060         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5061         int pipe = intel_crtc->pipe;
5062
5063         /*
5064          * Gen2 reports pipe underruns whenever all planes are disabled.
5065          * So disable underrun reporting before all the planes get disabled.
5066          */
5067         if (IS_GEN2(dev_priv))
5068                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5069
5070         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5071
5072         /*
5073          * Vblank time updates from the shadow to live plane control register
5074          * are blocked if the memory self-refresh mode is active at that
5075          * moment. So to make sure the plane gets truly disabled, disable
5076          * first the self-refresh mode. The self-refresh enable bit in turn
5077          * will be checked/applied by the HW only at the next frame start
5078          * event which is after the vblank start event, so we need to have a
5079          * wait-for-vblank between disabling the plane and the pipe.
5080          */
5081         if (HAS_GMCH_DISPLAY(dev_priv) &&
5082             intel_set_memory_cxsr(dev_priv, false))
5083                 intel_wait_for_vblank(dev_priv, pipe);
5084 }
5085
5086 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5087                                        const struct intel_crtc_state *new_crtc_state)
5088 {
5089         if (!old_crtc_state->ips_enabled)
5090                 return false;
5091
5092         if (needs_modeset(&new_crtc_state->base))
5093                 return true;
5094
5095         return !new_crtc_state->ips_enabled;
5096 }
5097
5098 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5099                                        const struct intel_crtc_state *new_crtc_state)
5100 {
5101         if (!new_crtc_state->ips_enabled)
5102                 return false;
5103
5104         if (needs_modeset(&new_crtc_state->base))
5105                 return true;
5106
5107         /*
5108          * We can't read out IPS on broadwell, assume the worst and
5109          * forcibly enable IPS on the first fastset.
5110          */
5111         if (new_crtc_state->update_pipe &&
5112             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5113                 return true;
5114
5115         return !old_crtc_state->ips_enabled;
5116 }
5117
5118 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5119 {
5120         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5121         struct drm_device *dev = crtc->base.dev;
5122         struct drm_i915_private *dev_priv = to_i915(dev);
5123         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5124         struct intel_crtc_state *pipe_config =
5125                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5126                                                 crtc);
5127         struct drm_plane *primary = crtc->base.primary;
5128         struct drm_plane_state *old_pri_state =
5129                 drm_atomic_get_existing_plane_state(old_state, primary);
5130
5131         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5132
5133         if (pipe_config->update_wm_post && pipe_config->base.active)
5134                 intel_update_watermarks(crtc);
5135
5136         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5137                 hsw_enable_ips(pipe_config);
5138
5139         if (old_pri_state) {
5140                 struct intel_plane_state *primary_state =
5141                         intel_atomic_get_new_plane_state(to_intel_atomic_state(old_state),
5142                                                          to_intel_plane(primary));
5143                 struct intel_plane_state *old_primary_state =
5144                         to_intel_plane_state(old_pri_state);
5145                 struct drm_framebuffer *fb = primary_state->base.fb;
5146
5147                 intel_fbc_post_update(crtc);
5148
5149                 if (primary_state->base.visible &&
5150                     (needs_modeset(&pipe_config->base) ||
5151                      !old_primary_state->base.visible))
5152                         intel_post_enable_primary(&crtc->base, pipe_config);
5153
5154                 /* Display WA 827 */
5155                 if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5156                     IS_CANNONLAKE(dev_priv)) {
5157                         if (fb && fb->format->format == DRM_FORMAT_NV12)
5158                                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5159                 }
5160
5161         }
5162 }
5163
5164 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5165                                    struct intel_crtc_state *pipe_config)
5166 {
5167         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5168         struct drm_device *dev = crtc->base.dev;
5169         struct drm_i915_private *dev_priv = to_i915(dev);
5170         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5171         struct drm_plane *primary = crtc->base.primary;
5172         struct drm_plane_state *old_pri_state =
5173                 drm_atomic_get_existing_plane_state(old_state, primary);
5174         bool modeset = needs_modeset(&pipe_config->base);
5175         struct intel_atomic_state *old_intel_state =
5176                 to_intel_atomic_state(old_state);
5177
5178         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5179                 hsw_disable_ips(old_crtc_state);
5180
5181         if (old_pri_state) {
5182                 struct intel_plane_state *primary_state =
5183                         intel_atomic_get_new_plane_state(old_intel_state,
5184                                                          to_intel_plane(primary));
5185                 struct intel_plane_state *old_primary_state =
5186                         to_intel_plane_state(old_pri_state);
5187                 struct drm_framebuffer *fb = primary_state->base.fb;
5188
5189                 /* Display WA 827 */
5190                 if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5191                     IS_CANNONLAKE(dev_priv)) {
5192                         if (fb && fb->format->format == DRM_FORMAT_NV12)
5193                                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5194                 }
5195
5196                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5197                 /*
5198                  * Gen2 reports pipe underruns whenever all planes are disabled.
5199                  * So disable underrun reporting before all the planes get disabled.
5200                  */
5201                 if (IS_GEN2(dev_priv) && old_primary_state->base.visible &&
5202                     (modeset || !primary_state->base.visible))
5203                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5204         }
5205
5206         /*
5207          * Vblank time updates from the shadow to live plane control register
5208          * are blocked if the memory self-refresh mode is active at that
5209          * moment. So to make sure the plane gets truly disabled, disable
5210          * first the self-refresh mode. The self-refresh enable bit in turn
5211          * will be checked/applied by the HW only at the next frame start
5212          * event which is after the vblank start event, so we need to have a
5213          * wait-for-vblank between disabling the plane and the pipe.
5214          */
5215         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5216             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5217                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5218
5219         /*
5220          * IVB workaround: must disable low power watermarks for at least
5221          * one frame before enabling scaling.  LP watermarks can be re-enabled
5222          * when scaling is disabled.
5223          *
5224          * WaCxSRDisabledForSpriteScaling:ivb
5225          */
5226         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5227                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5228
5229         /*
5230          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5231          * watermark programming here.
5232          */
5233         if (needs_modeset(&pipe_config->base))
5234                 return;
5235
5236         /*
5237          * For platforms that support atomic watermarks, program the
5238          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5239          * will be the intermediate values that are safe for both pre- and
5240          * post- vblank; when vblank happens, the 'active' values will be set
5241          * to the final 'target' values and we'll do this again to get the
5242          * optimal watermarks.  For gen9+ platforms, the values we program here
5243          * will be the final target values which will get automatically latched
5244          * at vblank time; no further programming will be necessary.
5245          *
5246          * If a platform hasn't been transitioned to atomic watermarks yet,
5247          * we'll continue to update watermarks the old way, if flags tell
5248          * us to.
5249          */
5250         if (dev_priv->display.initial_watermarks != NULL)
5251                 dev_priv->display.initial_watermarks(old_intel_state,
5252                                                      pipe_config);
5253         else if (pipe_config->update_wm_pre)
5254                 intel_update_watermarks(crtc);
5255 }
5256
5257 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5258 {
5259         struct drm_device *dev = crtc->dev;
5260         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5261         struct drm_plane *p;
5262         int pipe = intel_crtc->pipe;
5263
5264         intel_crtc_dpms_overlay_disable(intel_crtc);
5265
5266         drm_for_each_plane_mask(p, dev, plane_mask)
5267                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5268
5269         /*
5270          * FIXME: Once we grow proper nuclear flip support out of this we need
5271          * to compute the mask of flip planes precisely. For the time being
5272          * consider this a flip to a NULL plane.
5273          */
5274         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5275 }
5276
5277 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5278                                           struct intel_crtc_state *crtc_state,
5279                                           struct drm_atomic_state *old_state)
5280 {
5281         struct drm_connector_state *conn_state;
5282         struct drm_connector *conn;
5283         int i;
5284
5285         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5286                 struct intel_encoder *encoder =
5287                         to_intel_encoder(conn_state->best_encoder);
5288
5289                 if (conn_state->crtc != crtc)
5290                         continue;
5291
5292                 if (encoder->pre_pll_enable)
5293                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5294         }
5295 }
5296
5297 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5298                                       struct intel_crtc_state *crtc_state,
5299                                       struct drm_atomic_state *old_state)
5300 {
5301         struct drm_connector_state *conn_state;
5302         struct drm_connector *conn;
5303         int i;
5304
5305         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5306                 struct intel_encoder *encoder =
5307                         to_intel_encoder(conn_state->best_encoder);
5308
5309                 if (conn_state->crtc != crtc)
5310                         continue;
5311
5312                 if (encoder->pre_enable)
5313                         encoder->pre_enable(encoder, crtc_state, conn_state);
5314         }
5315 }
5316
5317 static void intel_encoders_enable(struct drm_crtc *crtc,
5318                                   struct intel_crtc_state *crtc_state,
5319                                   struct drm_atomic_state *old_state)
5320 {
5321         struct drm_connector_state *conn_state;
5322         struct drm_connector *conn;
5323         int i;
5324
5325         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5326                 struct intel_encoder *encoder =
5327                         to_intel_encoder(conn_state->best_encoder);
5328
5329                 if (conn_state->crtc != crtc)
5330                         continue;
5331
5332                 encoder->enable(encoder, crtc_state, conn_state);
5333                 intel_opregion_notify_encoder(encoder, true);
5334         }
5335 }
5336
5337 static void intel_encoders_disable(struct drm_crtc *crtc,
5338                                    struct intel_crtc_state *old_crtc_state,
5339                                    struct drm_atomic_state *old_state)
5340 {
5341         struct drm_connector_state *old_conn_state;
5342         struct drm_connector *conn;
5343         int i;
5344
5345         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5346                 struct intel_encoder *encoder =
5347                         to_intel_encoder(old_conn_state->best_encoder);
5348
5349                 if (old_conn_state->crtc != crtc)
5350                         continue;
5351
5352                 intel_opregion_notify_encoder(encoder, false);
5353                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5354         }
5355 }
5356
5357 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5358                                         struct intel_crtc_state *old_crtc_state,
5359                                         struct drm_atomic_state *old_state)
5360 {
5361         struct drm_connector_state *old_conn_state;
5362         struct drm_connector *conn;
5363         int i;
5364
5365         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5366                 struct intel_encoder *encoder =
5367                         to_intel_encoder(old_conn_state->best_encoder);
5368
5369                 if (old_conn_state->crtc != crtc)
5370                         continue;
5371
5372                 if (encoder->post_disable)
5373                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5374         }
5375 }
5376
5377 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5378                                             struct intel_crtc_state *old_crtc_state,
5379                                             struct drm_atomic_state *old_state)
5380 {
5381         struct drm_connector_state *old_conn_state;
5382         struct drm_connector *conn;
5383         int i;
5384
5385         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5386                 struct intel_encoder *encoder =
5387                         to_intel_encoder(old_conn_state->best_encoder);
5388
5389                 if (old_conn_state->crtc != crtc)
5390                         continue;
5391
5392                 if (encoder->post_pll_disable)
5393                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5394         }
5395 }
5396
5397 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5398                                  struct drm_atomic_state *old_state)
5399 {
5400         struct drm_crtc *crtc = pipe_config->base.crtc;
5401         struct drm_device *dev = crtc->dev;
5402         struct drm_i915_private *dev_priv = to_i915(dev);
5403         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5404         int pipe = intel_crtc->pipe;
5405         struct intel_atomic_state *old_intel_state =
5406                 to_intel_atomic_state(old_state);
5407
5408         if (WARN_ON(intel_crtc->active))
5409                 return;
5410
5411         /*
5412          * Sometimes spurious CPU pipe underruns happen during FDI
5413          * training, at least with VGA+HDMI cloning. Suppress them.
5414          *
5415          * On ILK we get an occasional spurious CPU pipe underruns
5416          * between eDP port A enable and vdd enable. Also PCH port
5417          * enable seems to result in the occasional CPU pipe underrun.
5418          *
5419          * Spurious PCH underruns also occur during PCH enabling.
5420          */
5421         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5422                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5423         if (intel_crtc->config->has_pch_encoder)
5424                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5425
5426         if (intel_crtc->config->has_pch_encoder)
5427                 intel_prepare_shared_dpll(intel_crtc);
5428
5429         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5430                 intel_dp_set_m_n(intel_crtc, M1_N1);
5431
5432         intel_set_pipe_timings(intel_crtc);
5433         intel_set_pipe_src_size(intel_crtc);
5434
5435         if (intel_crtc->config->has_pch_encoder) {
5436                 intel_cpu_transcoder_set_m_n(intel_crtc,
5437                                      &intel_crtc->config->fdi_m_n, NULL);
5438         }
5439
5440         ironlake_set_pipeconf(crtc);
5441
5442         intel_crtc->active = true;
5443
5444         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5445
5446         if (intel_crtc->config->has_pch_encoder) {
5447                 /* Note: FDI PLL enabling _must_ be done before we enable the
5448                  * cpu pipes, hence this is separate from all the other fdi/pch
5449                  * enabling. */
5450                 ironlake_fdi_pll_enable(intel_crtc);
5451         } else {
5452                 assert_fdi_tx_disabled(dev_priv, pipe);
5453                 assert_fdi_rx_disabled(dev_priv, pipe);
5454         }
5455
5456         ironlake_pfit_enable(intel_crtc);
5457
5458         /*
5459          * On ILK+ LUT must be loaded before the pipe is running but with
5460          * clocks enabled
5461          */
5462         intel_color_load_luts(&pipe_config->base);
5463
5464         if (dev_priv->display.initial_watermarks != NULL)
5465                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5466         intel_enable_pipe(pipe_config);
5467
5468         if (intel_crtc->config->has_pch_encoder)
5469                 ironlake_pch_enable(pipe_config);
5470
5471         assert_vblank_disabled(crtc);
5472         drm_crtc_vblank_on(crtc);
5473
5474         intel_encoders_enable(crtc, pipe_config, old_state);
5475
5476         if (HAS_PCH_CPT(dev_priv))
5477                 cpt_verify_modeset(dev, intel_crtc->pipe);
5478
5479         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5480         if (intel_crtc->config->has_pch_encoder)
5481                 intel_wait_for_vblank(dev_priv, pipe);
5482         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5483         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5484 }
5485
5486 /* IPS only exists on ULT machines and is tied to pipe A. */
5487 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5488 {
5489         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5490 }
5491
5492 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5493                                             enum pipe pipe, bool apply)
5494 {
5495         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5496         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5497
5498         if (apply)
5499                 val |= mask;
5500         else
5501                 val &= ~mask;
5502
5503         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5504 }
5505
5506 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5507 {
5508         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5509         enum pipe pipe = crtc->pipe;
5510         uint32_t val;
5511
5512         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5513
5514         /* Program B credit equally to all pipes */
5515         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5516
5517         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5518 }
5519
5520 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5521                                 struct drm_atomic_state *old_state)
5522 {
5523         struct drm_crtc *crtc = pipe_config->base.crtc;
5524         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5525         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5526         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5527         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5528         struct intel_atomic_state *old_intel_state =
5529                 to_intel_atomic_state(old_state);
5530         bool psl_clkgate_wa;
5531
5532         if (WARN_ON(intel_crtc->active))
5533                 return;
5534
5535         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5536
5537         if (intel_crtc->config->shared_dpll)
5538                 intel_enable_shared_dpll(intel_crtc);
5539
5540         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5541                 intel_dp_set_m_n(intel_crtc, M1_N1);
5542
5543         if (!transcoder_is_dsi(cpu_transcoder))
5544                 intel_set_pipe_timings(intel_crtc);
5545
5546         intel_set_pipe_src_size(intel_crtc);
5547
5548         if (cpu_transcoder != TRANSCODER_EDP &&
5549             !transcoder_is_dsi(cpu_transcoder)) {
5550                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5551                            intel_crtc->config->pixel_multiplier - 1);
5552         }
5553
5554         if (intel_crtc->config->has_pch_encoder) {
5555                 intel_cpu_transcoder_set_m_n(intel_crtc,
5556                                      &intel_crtc->config->fdi_m_n, NULL);
5557         }
5558
5559         if (!transcoder_is_dsi(cpu_transcoder))
5560                 haswell_set_pipeconf(crtc);
5561
5562         haswell_set_pipemisc(crtc);
5563
5564         intel_color_set_csc(&pipe_config->base);
5565
5566         intel_crtc->active = true;
5567
5568         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5569
5570         if (!transcoder_is_dsi(cpu_transcoder))
5571                 intel_ddi_enable_pipe_clock(pipe_config);
5572
5573         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5574         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5575                          intel_crtc->config->pch_pfit.enabled;
5576         if (psl_clkgate_wa)
5577                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5578
5579         if (INTEL_GEN(dev_priv) >= 9)
5580                 skylake_pfit_enable(intel_crtc);
5581         else
5582                 ironlake_pfit_enable(intel_crtc);
5583
5584         /*
5585          * On ILK+ LUT must be loaded before the pipe is running but with
5586          * clocks enabled
5587          */
5588         intel_color_load_luts(&pipe_config->base);
5589
5590         intel_ddi_set_pipe_settings(pipe_config);
5591         if (!transcoder_is_dsi(cpu_transcoder))
5592                 intel_ddi_enable_transcoder_func(pipe_config);
5593
5594         if (dev_priv->display.initial_watermarks != NULL)
5595                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5596
5597         if (INTEL_GEN(dev_priv) >= 11)
5598                 icl_pipe_mbus_enable(intel_crtc);
5599
5600         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5601         if (!transcoder_is_dsi(cpu_transcoder))
5602                 intel_enable_pipe(pipe_config);
5603
5604         if (intel_crtc->config->has_pch_encoder)
5605                 lpt_pch_enable(pipe_config);
5606
5607         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5608                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5609
5610         assert_vblank_disabled(crtc);
5611         drm_crtc_vblank_on(crtc);
5612
5613         intel_encoders_enable(crtc, pipe_config, old_state);
5614
5615         if (psl_clkgate_wa) {
5616                 intel_wait_for_vblank(dev_priv, pipe);
5617                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5618         }
5619
5620         /* If we change the relative order between pipe/planes enabling, we need
5621          * to change the workaround. */
5622         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5623         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5624                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5625                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5626         }
5627 }
5628
5629 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5630 {
5631         struct drm_device *dev = crtc->base.dev;
5632         struct drm_i915_private *dev_priv = to_i915(dev);
5633         int pipe = crtc->pipe;
5634
5635         /* To avoid upsetting the power well on haswell only disable the pfit if
5636          * it's in use. The hw state code will make sure we get this right. */
5637         if (force || crtc->config->pch_pfit.enabled) {
5638                 I915_WRITE(PF_CTL(pipe), 0);
5639                 I915_WRITE(PF_WIN_POS(pipe), 0);
5640                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5641         }
5642 }
5643
5644 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5645                                   struct drm_atomic_state *old_state)
5646 {
5647         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5648         struct drm_device *dev = crtc->dev;
5649         struct drm_i915_private *dev_priv = to_i915(dev);
5650         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5651         int pipe = intel_crtc->pipe;
5652
5653         /*
5654          * Sometimes spurious CPU pipe underruns happen when the
5655          * pipe is already disabled, but FDI RX/TX is still enabled.
5656          * Happens at least with VGA+HDMI cloning. Suppress them.
5657          */
5658         if (intel_crtc->config->has_pch_encoder) {
5659                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5660                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5661         }
5662
5663         intel_encoders_disable(crtc, old_crtc_state, old_state);
5664
5665         drm_crtc_vblank_off(crtc);
5666         assert_vblank_disabled(crtc);
5667
5668         intel_disable_pipe(old_crtc_state);
5669
5670         ironlake_pfit_disable(intel_crtc, false);
5671
5672         if (intel_crtc->config->has_pch_encoder)
5673                 ironlake_fdi_disable(crtc);
5674
5675         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5676
5677         if (intel_crtc->config->has_pch_encoder) {
5678                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5679
5680                 if (HAS_PCH_CPT(dev_priv)) {
5681                         i915_reg_t reg;
5682                         u32 temp;
5683
5684                         /* disable TRANS_DP_CTL */
5685                         reg = TRANS_DP_CTL(pipe);
5686                         temp = I915_READ(reg);
5687                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5688                                   TRANS_DP_PORT_SEL_MASK);
5689                         temp |= TRANS_DP_PORT_SEL_NONE;
5690                         I915_WRITE(reg, temp);
5691
5692                         /* disable DPLL_SEL */
5693                         temp = I915_READ(PCH_DPLL_SEL);
5694                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5695                         I915_WRITE(PCH_DPLL_SEL, temp);
5696                 }
5697
5698                 ironlake_fdi_pll_disable(intel_crtc);
5699         }
5700
5701         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5702         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5703 }
5704
5705 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5706                                  struct drm_atomic_state *old_state)
5707 {
5708         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5709         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5710         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5711         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5712
5713         intel_encoders_disable(crtc, old_crtc_state, old_state);
5714
5715         drm_crtc_vblank_off(crtc);
5716         assert_vblank_disabled(crtc);
5717
5718         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5719         if (!transcoder_is_dsi(cpu_transcoder))
5720                 intel_disable_pipe(old_crtc_state);
5721
5722         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5723                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5724
5725         if (!transcoder_is_dsi(cpu_transcoder))
5726                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5727
5728         if (INTEL_GEN(dev_priv) >= 9)
5729                 skylake_scaler_disable(intel_crtc);
5730         else
5731                 ironlake_pfit_disable(intel_crtc, false);
5732
5733         if (!transcoder_is_dsi(cpu_transcoder))
5734                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5735
5736         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5737 }
5738
5739 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5740 {
5741         struct drm_device *dev = crtc->base.dev;
5742         struct drm_i915_private *dev_priv = to_i915(dev);
5743         struct intel_crtc_state *pipe_config = crtc->config;
5744
5745         if (!pipe_config->gmch_pfit.control)
5746                 return;
5747
5748         /*
5749          * The panel fitter should only be adjusted whilst the pipe is disabled,
5750          * according to register description and PRM.
5751          */
5752         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5753         assert_pipe_disabled(dev_priv, crtc->pipe);
5754
5755         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5756         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5757
5758         /* Border color in case we don't scale up to the full screen. Black by
5759          * default, change to something else for debugging. */
5760         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5761 }
5762
5763 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5764 {
5765         switch (port) {
5766         case PORT_A:
5767                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5768         case PORT_B:
5769                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5770         case PORT_C:
5771                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5772         case PORT_D:
5773                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5774         case PORT_E:
5775                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5776         case PORT_F:
5777                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5778         default:
5779                 MISSING_CASE(port);
5780                 return POWER_DOMAIN_PORT_OTHER;
5781         }
5782 }
5783
5784 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5785                                   struct intel_crtc_state *crtc_state)
5786 {
5787         struct drm_device *dev = crtc->dev;
5788         struct drm_i915_private *dev_priv = to_i915(dev);
5789         struct drm_encoder *encoder;
5790         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5791         enum pipe pipe = intel_crtc->pipe;
5792         u64 mask;
5793         enum transcoder transcoder = crtc_state->cpu_transcoder;
5794
5795         if (!crtc_state->base.active)
5796                 return 0;
5797
5798         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5799         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5800         if (crtc_state->pch_pfit.enabled ||
5801             crtc_state->pch_pfit.force_thru)
5802                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5803
5804         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5805                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5806
5807                 mask |= BIT_ULL(intel_encoder->power_domain);
5808         }
5809
5810         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5811                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5812
5813         if (crtc_state->shared_dpll)
5814                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5815
5816         return mask;
5817 }
5818
5819 static u64
5820 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5821                                struct intel_crtc_state *crtc_state)
5822 {
5823         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5824         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5825         enum intel_display_power_domain domain;
5826         u64 domains, new_domains, old_domains;
5827
5828         old_domains = intel_crtc->enabled_power_domains;
5829         intel_crtc->enabled_power_domains = new_domains =
5830                 get_crtc_power_domains(crtc, crtc_state);
5831
5832         domains = new_domains & ~old_domains;
5833
5834         for_each_power_domain(domain, domains)
5835                 intel_display_power_get(dev_priv, domain);
5836
5837         return old_domains & ~new_domains;
5838 }
5839
5840 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5841                                       u64 domains)
5842 {
5843         enum intel_display_power_domain domain;
5844
5845         for_each_power_domain(domain, domains)
5846                 intel_display_power_put(dev_priv, domain);
5847 }
5848
5849 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5850                                    struct drm_atomic_state *old_state)
5851 {
5852         struct intel_atomic_state *old_intel_state =
5853                 to_intel_atomic_state(old_state);
5854         struct drm_crtc *crtc = pipe_config->base.crtc;
5855         struct drm_device *dev = crtc->dev;
5856         struct drm_i915_private *dev_priv = to_i915(dev);
5857         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5858         int pipe = intel_crtc->pipe;
5859
5860         if (WARN_ON(intel_crtc->active))
5861                 return;
5862
5863         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5864                 intel_dp_set_m_n(intel_crtc, M1_N1);
5865
5866         intel_set_pipe_timings(intel_crtc);
5867         intel_set_pipe_src_size(intel_crtc);
5868
5869         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5870                 struct drm_i915_private *dev_priv = to_i915(dev);
5871
5872                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5873                 I915_WRITE(CHV_CANVAS(pipe), 0);
5874         }
5875
5876         i9xx_set_pipeconf(intel_crtc);
5877
5878         intel_crtc->active = true;
5879
5880         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5881
5882         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5883
5884         if (IS_CHERRYVIEW(dev_priv)) {
5885                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5886                 chv_enable_pll(intel_crtc, intel_crtc->config);
5887         } else {
5888                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5889                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5890         }
5891
5892         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5893
5894         i9xx_pfit_enable(intel_crtc);
5895
5896         intel_color_load_luts(&pipe_config->base);
5897
5898         dev_priv->display.initial_watermarks(old_intel_state,
5899                                              pipe_config);
5900         intel_enable_pipe(pipe_config);
5901
5902         assert_vblank_disabled(crtc);
5903         drm_crtc_vblank_on(crtc);
5904
5905         intel_encoders_enable(crtc, pipe_config, old_state);
5906 }
5907
5908 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5909 {
5910         struct drm_device *dev = crtc->base.dev;
5911         struct drm_i915_private *dev_priv = to_i915(dev);
5912
5913         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5914         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5915 }
5916
5917 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5918                              struct drm_atomic_state *old_state)
5919 {
5920         struct intel_atomic_state *old_intel_state =
5921                 to_intel_atomic_state(old_state);
5922         struct drm_crtc *crtc = pipe_config->base.crtc;
5923         struct drm_device *dev = crtc->dev;
5924         struct drm_i915_private *dev_priv = to_i915(dev);
5925         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5926         enum pipe pipe = intel_crtc->pipe;
5927
5928         if (WARN_ON(intel_crtc->active))
5929                 return;
5930
5931         i9xx_set_pll_dividers(intel_crtc);
5932
5933         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5934                 intel_dp_set_m_n(intel_crtc, M1_N1);
5935
5936         intel_set_pipe_timings(intel_crtc);
5937         intel_set_pipe_src_size(intel_crtc);
5938
5939         i9xx_set_pipeconf(intel_crtc);
5940
5941         intel_crtc->active = true;
5942
5943         if (!IS_GEN2(dev_priv))
5944                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5945
5946         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5947
5948         i9xx_enable_pll(intel_crtc, pipe_config);
5949
5950         i9xx_pfit_enable(intel_crtc);
5951
5952         intel_color_load_luts(&pipe_config->base);
5953
5954         if (dev_priv->display.initial_watermarks != NULL)
5955                 dev_priv->display.initial_watermarks(old_intel_state,
5956                                                      intel_crtc->config);
5957         else
5958                 intel_update_watermarks(intel_crtc);
5959         intel_enable_pipe(pipe_config);
5960
5961         assert_vblank_disabled(crtc);
5962         drm_crtc_vblank_on(crtc);
5963
5964         intel_encoders_enable(crtc, pipe_config, old_state);
5965 }
5966
5967 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5968 {
5969         struct drm_device *dev = crtc->base.dev;
5970         struct drm_i915_private *dev_priv = to_i915(dev);
5971
5972         if (!crtc->config->gmch_pfit.control)
5973                 return;
5974
5975         assert_pipe_disabled(dev_priv, crtc->pipe);
5976
5977         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5978                          I915_READ(PFIT_CONTROL));
5979         I915_WRITE(PFIT_CONTROL, 0);
5980 }
5981
5982 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5983                               struct drm_atomic_state *old_state)
5984 {
5985         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5986         struct drm_device *dev = crtc->dev;
5987         struct drm_i915_private *dev_priv = to_i915(dev);
5988         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5989         int pipe = intel_crtc->pipe;
5990
5991         /*
5992          * On gen2 planes are double buffered but the pipe isn't, so we must
5993          * wait for planes to fully turn off before disabling the pipe.
5994          */
5995         if (IS_GEN2(dev_priv))
5996                 intel_wait_for_vblank(dev_priv, pipe);
5997
5998         intel_encoders_disable(crtc, old_crtc_state, old_state);
5999
6000         drm_crtc_vblank_off(crtc);
6001         assert_vblank_disabled(crtc);
6002
6003         intel_disable_pipe(old_crtc_state);
6004
6005         i9xx_pfit_disable(intel_crtc);
6006
6007         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6008
6009         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6010                 if (IS_CHERRYVIEW(dev_priv))
6011                         chv_disable_pll(dev_priv, pipe);
6012                 else if (IS_VALLEYVIEW(dev_priv))
6013                         vlv_disable_pll(dev_priv, pipe);
6014                 else
6015                         i9xx_disable_pll(intel_crtc);
6016         }
6017
6018         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6019
6020         if (!IS_GEN2(dev_priv))
6021                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6022
6023         if (!dev_priv->display.initial_watermarks)
6024                 intel_update_watermarks(intel_crtc);
6025
6026         /* clock the pipe down to 640x480@60 to potentially save power */
6027         if (IS_I830(dev_priv))
6028                 i830_enable_pipe(dev_priv, pipe);
6029 }
6030
6031 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6032                                         struct drm_modeset_acquire_ctx *ctx)
6033 {
6034         struct intel_encoder *encoder;
6035         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6036         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6037         enum intel_display_power_domain domain;
6038         struct intel_plane *plane;
6039         u64 domains;
6040         struct drm_atomic_state *state;
6041         struct intel_crtc_state *crtc_state;
6042         int ret;
6043
6044         if (!intel_crtc->active)
6045                 return;
6046
6047         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6048                 const struct intel_plane_state *plane_state =
6049                         to_intel_plane_state(plane->base.state);
6050
6051                 if (plane_state->base.visible)
6052                         intel_plane_disable_noatomic(intel_crtc, plane);
6053         }
6054
6055         state = drm_atomic_state_alloc(crtc->dev);
6056         if (!state) {
6057                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6058                               crtc->base.id, crtc->name);
6059                 return;
6060         }
6061
6062         state->acquire_ctx = ctx;
6063
6064         /* Everything's already locked, -EDEADLK can't happen. */
6065         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6066         ret = drm_atomic_add_affected_connectors(state, crtc);
6067
6068         WARN_ON(IS_ERR(crtc_state) || ret);
6069
6070         dev_priv->display.crtc_disable(crtc_state, state);
6071
6072         drm_atomic_state_put(state);
6073
6074         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6075                       crtc->base.id, crtc->name);
6076
6077         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6078         crtc->state->active = false;
6079         intel_crtc->active = false;
6080         crtc->enabled = false;
6081         crtc->state->connector_mask = 0;
6082         crtc->state->encoder_mask = 0;
6083
6084         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6085                 encoder->base.crtc = NULL;
6086
6087         intel_fbc_disable(intel_crtc);
6088         intel_update_watermarks(intel_crtc);
6089         intel_disable_shared_dpll(intel_crtc);
6090
6091         domains = intel_crtc->enabled_power_domains;
6092         for_each_power_domain(domain, domains)
6093                 intel_display_power_put(dev_priv, domain);
6094         intel_crtc->enabled_power_domains = 0;
6095
6096         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6097         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6098         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6099 }
6100
6101 /*
6102  * turn all crtc's off, but do not adjust state
6103  * This has to be paired with a call to intel_modeset_setup_hw_state.
6104  */
6105 int intel_display_suspend(struct drm_device *dev)
6106 {
6107         struct drm_i915_private *dev_priv = to_i915(dev);
6108         struct drm_atomic_state *state;
6109         int ret;
6110
6111         state = drm_atomic_helper_suspend(dev);
6112         ret = PTR_ERR_OR_ZERO(state);
6113         if (ret)
6114                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6115         else
6116                 dev_priv->modeset_restore_state = state;
6117         return ret;
6118 }
6119
6120 void intel_encoder_destroy(struct drm_encoder *encoder)
6121 {
6122         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6123
6124         drm_encoder_cleanup(encoder);
6125         kfree(intel_encoder);
6126 }
6127
6128 /* Cross check the actual hw state with our own modeset state tracking (and it's
6129  * internal consistency). */
6130 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6131                                          struct drm_connector_state *conn_state)
6132 {
6133         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6134
6135         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6136                       connector->base.base.id,
6137                       connector->base.name);
6138
6139         if (connector->get_hw_state(connector)) {
6140                 struct intel_encoder *encoder = connector->encoder;
6141
6142                 I915_STATE_WARN(!crtc_state,
6143                          "connector enabled without attached crtc\n");
6144
6145                 if (!crtc_state)
6146                         return;
6147
6148                 I915_STATE_WARN(!crtc_state->active,
6149                       "connector is active, but attached crtc isn't\n");
6150
6151                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6152                         return;
6153
6154                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6155                         "atomic encoder doesn't match attached encoder\n");
6156
6157                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6158                         "attached encoder crtc differs from connector crtc\n");
6159         } else {
6160                 I915_STATE_WARN(crtc_state && crtc_state->active,
6161                         "attached crtc is active, but connector isn't\n");
6162                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6163                         "best encoder set without crtc!\n");
6164         }
6165 }
6166
6167 int intel_connector_init(struct intel_connector *connector)
6168 {
6169         struct intel_digital_connector_state *conn_state;
6170
6171         /*
6172          * Allocate enough memory to hold intel_digital_connector_state,
6173          * This might be a few bytes too many, but for connectors that don't
6174          * need it we'll free the state and allocate a smaller one on the first
6175          * succesful commit anyway.
6176          */
6177         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6178         if (!conn_state)
6179                 return -ENOMEM;
6180
6181         __drm_atomic_helper_connector_reset(&connector->base,
6182                                             &conn_state->base);
6183
6184         return 0;
6185 }
6186
6187 struct intel_connector *intel_connector_alloc(void)
6188 {
6189         struct intel_connector *connector;
6190
6191         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6192         if (!connector)
6193                 return NULL;
6194
6195         if (intel_connector_init(connector) < 0) {
6196                 kfree(connector);
6197                 return NULL;
6198         }
6199
6200         return connector;
6201 }
6202
6203 /*
6204  * Free the bits allocated by intel_connector_alloc.
6205  * This should only be used after intel_connector_alloc has returned
6206  * successfully, and before drm_connector_init returns successfully.
6207  * Otherwise the destroy callbacks for the connector and the state should
6208  * take care of proper cleanup/free
6209  */
6210 void intel_connector_free(struct intel_connector *connector)
6211 {
6212         kfree(to_intel_digital_connector_state(connector->base.state));
6213         kfree(connector);
6214 }
6215
6216 /* Simple connector->get_hw_state implementation for encoders that support only
6217  * one connector and no cloning and hence the encoder state determines the state
6218  * of the connector. */
6219 bool intel_connector_get_hw_state(struct intel_connector *connector)
6220 {
6221         enum pipe pipe = 0;
6222         struct intel_encoder *encoder = connector->encoder;
6223
6224         return encoder->get_hw_state(encoder, &pipe);
6225 }
6226
6227 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6228 {
6229         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6230                 return crtc_state->fdi_lanes;
6231
6232         return 0;
6233 }
6234
6235 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6236                                      struct intel_crtc_state *pipe_config)
6237 {
6238         struct drm_i915_private *dev_priv = to_i915(dev);
6239         struct drm_atomic_state *state = pipe_config->base.state;
6240         struct intel_crtc *other_crtc;
6241         struct intel_crtc_state *other_crtc_state;
6242
6243         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6244                       pipe_name(pipe), pipe_config->fdi_lanes);
6245         if (pipe_config->fdi_lanes > 4) {
6246                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6247                               pipe_name(pipe), pipe_config->fdi_lanes);
6248                 return -EINVAL;
6249         }
6250
6251         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6252                 if (pipe_config->fdi_lanes > 2) {
6253                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6254                                       pipe_config->fdi_lanes);
6255                         return -EINVAL;
6256                 } else {
6257                         return 0;
6258                 }
6259         }
6260
6261         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6262                 return 0;
6263
6264         /* Ivybridge 3 pipe is really complicated */
6265         switch (pipe) {
6266         case PIPE_A:
6267                 return 0;
6268         case PIPE_B:
6269                 if (pipe_config->fdi_lanes <= 2)
6270                         return 0;
6271
6272                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6273                 other_crtc_state =
6274                         intel_atomic_get_crtc_state(state, other_crtc);
6275                 if (IS_ERR(other_crtc_state))
6276                         return PTR_ERR(other_crtc_state);
6277
6278                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6279                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6280                                       pipe_name(pipe), pipe_config->fdi_lanes);
6281                         return -EINVAL;
6282                 }
6283                 return 0;
6284         case PIPE_C:
6285                 if (pipe_config->fdi_lanes > 2) {
6286                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6287                                       pipe_name(pipe), pipe_config->fdi_lanes);
6288                         return -EINVAL;
6289                 }
6290
6291                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6292                 other_crtc_state =
6293                         intel_atomic_get_crtc_state(state, other_crtc);
6294                 if (IS_ERR(other_crtc_state))
6295                         return PTR_ERR(other_crtc_state);
6296
6297                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6298                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6299                         return -EINVAL;
6300                 }
6301                 return 0;
6302         default:
6303                 BUG();
6304         }
6305 }
6306
6307 #define RETRY 1
6308 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6309                                        struct intel_crtc_state *pipe_config)
6310 {
6311         struct drm_device *dev = intel_crtc->base.dev;
6312         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6313         int lane, link_bw, fdi_dotclock, ret;
6314         bool needs_recompute = false;
6315
6316 retry:
6317         /* FDI is a binary signal running at ~2.7GHz, encoding
6318          * each output octet as 10 bits. The actual frequency
6319          * is stored as a divider into a 100MHz clock, and the
6320          * mode pixel clock is stored in units of 1KHz.
6321          * Hence the bw of each lane in terms of the mode signal
6322          * is:
6323          */
6324         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6325
6326         fdi_dotclock = adjusted_mode->crtc_clock;
6327
6328         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6329                                            pipe_config->pipe_bpp);
6330
6331         pipe_config->fdi_lanes = lane;
6332
6333         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6334                                link_bw, &pipe_config->fdi_m_n, false);
6335
6336         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6337         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6338                 pipe_config->pipe_bpp -= 2*3;
6339                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6340                               pipe_config->pipe_bpp);
6341                 needs_recompute = true;
6342                 pipe_config->bw_constrained = true;
6343
6344                 goto retry;
6345         }
6346
6347         if (needs_recompute)
6348                 return RETRY;
6349
6350         return ret;
6351 }
6352
6353 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6354 {
6355         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6356         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6357
6358         /* IPS only exists on ULT machines and is tied to pipe A. */
6359         if (!hsw_crtc_supports_ips(crtc))
6360                 return false;
6361
6362         if (!i915_modparams.enable_ips)
6363                 return false;
6364
6365         if (crtc_state->pipe_bpp > 24)
6366                 return false;
6367
6368         /*
6369          * We compare against max which means we must take
6370          * the increased cdclk requirement into account when
6371          * calculating the new cdclk.
6372          *
6373          * Should measure whether using a lower cdclk w/o IPS
6374          */
6375         if (IS_BROADWELL(dev_priv) &&
6376             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6377                 return false;
6378
6379         return true;
6380 }
6381
6382 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6383 {
6384         struct drm_i915_private *dev_priv =
6385                 to_i915(crtc_state->base.crtc->dev);
6386         struct intel_atomic_state *intel_state =
6387                 to_intel_atomic_state(crtc_state->base.state);
6388
6389         if (!hsw_crtc_state_ips_capable(crtc_state))
6390                 return false;
6391
6392         if (crtc_state->ips_force_disable)
6393                 return false;
6394
6395         /* IPS should be fine as long as at least one plane is enabled. */
6396         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6397                 return false;
6398
6399         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6400         if (IS_BROADWELL(dev_priv) &&
6401             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6402                 return false;
6403
6404         return true;
6405 }
6406
6407 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6408 {
6409         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6410
6411         /* GDG double wide on either pipe, otherwise pipe A only */
6412         return INTEL_GEN(dev_priv) < 4 &&
6413                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6414 }
6415
6416 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6417 {
6418         uint32_t pixel_rate;
6419
6420         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6421
6422         /*
6423          * We only use IF-ID interlacing. If we ever use
6424          * PF-ID we'll need to adjust the pixel_rate here.
6425          */
6426
6427         if (pipe_config->pch_pfit.enabled) {
6428                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6429                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6430
6431                 pipe_w = pipe_config->pipe_src_w;
6432                 pipe_h = pipe_config->pipe_src_h;
6433
6434                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6435                 pfit_h = pfit_size & 0xFFFF;
6436                 if (pipe_w < pfit_w)
6437                         pipe_w = pfit_w;
6438                 if (pipe_h < pfit_h)
6439                         pipe_h = pfit_h;
6440
6441                 if (WARN_ON(!pfit_w || !pfit_h))
6442                         return pixel_rate;
6443
6444                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6445                                      pfit_w * pfit_h);
6446         }
6447
6448         return pixel_rate;
6449 }
6450
6451 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6452 {
6453         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6454
6455         if (HAS_GMCH_DISPLAY(dev_priv))
6456                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6457                 crtc_state->pixel_rate =
6458                         crtc_state->base.adjusted_mode.crtc_clock;
6459         else
6460                 crtc_state->pixel_rate =
6461                         ilk_pipe_pixel_rate(crtc_state);
6462 }
6463
6464 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6465                                      struct intel_crtc_state *pipe_config)
6466 {
6467         struct drm_device *dev = crtc->base.dev;
6468         struct drm_i915_private *dev_priv = to_i915(dev);
6469         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6470         int clock_limit = dev_priv->max_dotclk_freq;
6471
6472         if (INTEL_GEN(dev_priv) < 4) {
6473                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6474
6475                 /*
6476                  * Enable double wide mode when the dot clock
6477                  * is > 90% of the (display) core speed.
6478                  */
6479                 if (intel_crtc_supports_double_wide(crtc) &&
6480                     adjusted_mode->crtc_clock > clock_limit) {
6481                         clock_limit = dev_priv->max_dotclk_freq;
6482                         pipe_config->double_wide = true;
6483                 }
6484         }
6485
6486         if (adjusted_mode->crtc_clock > clock_limit) {
6487                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6488                               adjusted_mode->crtc_clock, clock_limit,
6489                               yesno(pipe_config->double_wide));
6490                 return -EINVAL;
6491         }
6492
6493         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6494                 /*
6495                  * There is only one pipe CSC unit per pipe, and we need that
6496                  * for output conversion from RGB->YCBCR. So if CTM is already
6497                  * applied we can't support YCBCR420 output.
6498                  */
6499                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6500                 return -EINVAL;
6501         }
6502
6503         /*
6504          * Pipe horizontal size must be even in:
6505          * - DVO ganged mode
6506          * - LVDS dual channel mode
6507          * - Double wide pipe
6508          */
6509         if (pipe_config->pipe_src_w & 1) {
6510                 if (pipe_config->double_wide) {
6511                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6512                         return -EINVAL;
6513                 }
6514
6515                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6516                     intel_is_dual_link_lvds(dev)) {
6517                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6518                         return -EINVAL;
6519                 }
6520         }
6521
6522         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6523          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6524          */
6525         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6526                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6527                 return -EINVAL;
6528
6529         intel_crtc_compute_pixel_rate(pipe_config);
6530
6531         if (pipe_config->has_pch_encoder)
6532                 return ironlake_fdi_compute_config(crtc, pipe_config);
6533
6534         return 0;
6535 }
6536
6537 static void
6538 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6539 {
6540         while (*num > DATA_LINK_M_N_MASK ||
6541                *den > DATA_LINK_M_N_MASK) {
6542                 *num >>= 1;
6543                 *den >>= 1;
6544         }
6545 }
6546
6547 static void compute_m_n(unsigned int m, unsigned int n,
6548                         uint32_t *ret_m, uint32_t *ret_n,
6549                         bool reduce_m_n)
6550 {
6551         /*
6552          * Reduce M/N as much as possible without loss in precision. Several DP
6553          * dongles in particular seem to be fussy about too large *link* M/N
6554          * values. The passed in values are more likely to have the least
6555          * significant bits zero than M after rounding below, so do this first.
6556          */
6557         if (reduce_m_n) {
6558                 while ((m & 1) == 0 && (n & 1) == 0) {
6559                         m >>= 1;
6560                         n >>= 1;
6561                 }
6562         }
6563
6564         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6565         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6566         intel_reduce_m_n_ratio(ret_m, ret_n);
6567 }
6568
6569 void
6570 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6571                        int pixel_clock, int link_clock,
6572                        struct intel_link_m_n *m_n,
6573                        bool reduce_m_n)
6574 {
6575         m_n->tu = 64;
6576
6577         compute_m_n(bits_per_pixel * pixel_clock,
6578                     link_clock * nlanes * 8,
6579                     &m_n->gmch_m, &m_n->gmch_n,
6580                     reduce_m_n);
6581
6582         compute_m_n(pixel_clock, link_clock,
6583                     &m_n->link_m, &m_n->link_n,
6584                     reduce_m_n);
6585 }
6586
6587 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6588 {
6589         if (i915_modparams.panel_use_ssc >= 0)
6590                 return i915_modparams.panel_use_ssc != 0;
6591         return dev_priv->vbt.lvds_use_ssc
6592                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6593 }
6594
6595 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6596 {
6597         return (1 << dpll->n) << 16 | dpll->m2;
6598 }
6599
6600 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6601 {
6602         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6603 }
6604
6605 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6606                                      struct intel_crtc_state *crtc_state,
6607                                      struct dpll *reduced_clock)
6608 {
6609         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6610         u32 fp, fp2 = 0;
6611
6612         if (IS_PINEVIEW(dev_priv)) {
6613                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6614                 if (reduced_clock)
6615                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6616         } else {
6617                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6618                 if (reduced_clock)
6619                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6620         }
6621
6622         crtc_state->dpll_hw_state.fp0 = fp;
6623
6624         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6625             reduced_clock) {
6626                 crtc_state->dpll_hw_state.fp1 = fp2;
6627         } else {
6628                 crtc_state->dpll_hw_state.fp1 = fp;
6629         }
6630 }
6631
6632 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6633                 pipe)
6634 {
6635         u32 reg_val;
6636
6637         /*
6638          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6639          * and set it to a reasonable value instead.
6640          */
6641         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6642         reg_val &= 0xffffff00;
6643         reg_val |= 0x00000030;
6644         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6645
6646         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6647         reg_val &= 0x00ffffff;
6648         reg_val |= 0x8c000000;
6649         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6650
6651         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6652         reg_val &= 0xffffff00;
6653         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6654
6655         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6656         reg_val &= 0x00ffffff;
6657         reg_val |= 0xb0000000;
6658         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6659 }
6660
6661 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6662                                          struct intel_link_m_n *m_n)
6663 {
6664         struct drm_device *dev = crtc->base.dev;
6665         struct drm_i915_private *dev_priv = to_i915(dev);
6666         int pipe = crtc->pipe;
6667
6668         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6669         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6670         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6671         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6672 }
6673
6674 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6675                                          struct intel_link_m_n *m_n,
6676                                          struct intel_link_m_n *m2_n2)
6677 {
6678         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6679         int pipe = crtc->pipe;
6680         enum transcoder transcoder = crtc->config->cpu_transcoder;
6681
6682         if (INTEL_GEN(dev_priv) >= 5) {
6683                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6684                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6685                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6686                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6687                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6688                  * for gen < 8) and if DRRS is supported (to make sure the
6689                  * registers are not unnecessarily accessed).
6690                  */
6691                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6692                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6693                         I915_WRITE(PIPE_DATA_M2(transcoder),
6694                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6695                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6696                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6697                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6698                 }
6699         } else {
6700                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6701                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6702                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6703                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6704         }
6705 }
6706
6707 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6708 {
6709         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6710
6711         if (m_n == M1_N1) {
6712                 dp_m_n = &crtc->config->dp_m_n;
6713                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6714         } else if (m_n == M2_N2) {
6715
6716                 /*
6717                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6718                  * needs to be programmed into M1_N1.
6719                  */
6720                 dp_m_n = &crtc->config->dp_m2_n2;
6721         } else {
6722                 DRM_ERROR("Unsupported divider value\n");
6723                 return;
6724         }
6725
6726         if (crtc->config->has_pch_encoder)
6727                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6728         else
6729                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6730 }
6731
6732 static void vlv_compute_dpll(struct intel_crtc *crtc,
6733                              struct intel_crtc_state *pipe_config)
6734 {
6735         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6736                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6737         if (crtc->pipe != PIPE_A)
6738                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6739
6740         /* DPLL not used with DSI, but still need the rest set up */
6741         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6742                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6743                         DPLL_EXT_BUFFER_ENABLE_VLV;
6744
6745         pipe_config->dpll_hw_state.dpll_md =
6746                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6747 }
6748
6749 static void chv_compute_dpll(struct intel_crtc *crtc,
6750                              struct intel_crtc_state *pipe_config)
6751 {
6752         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6753                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6754         if (crtc->pipe != PIPE_A)
6755                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6756
6757         /* DPLL not used with DSI, but still need the rest set up */
6758         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6759                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6760
6761         pipe_config->dpll_hw_state.dpll_md =
6762                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6763 }
6764
6765 static void vlv_prepare_pll(struct intel_crtc *crtc,
6766                             const struct intel_crtc_state *pipe_config)
6767 {
6768         struct drm_device *dev = crtc->base.dev;
6769         struct drm_i915_private *dev_priv = to_i915(dev);
6770         enum pipe pipe = crtc->pipe;
6771         u32 mdiv;
6772         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6773         u32 coreclk, reg_val;
6774
6775         /* Enable Refclk */
6776         I915_WRITE(DPLL(pipe),
6777                    pipe_config->dpll_hw_state.dpll &
6778                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6779
6780         /* No need to actually set up the DPLL with DSI */
6781         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6782                 return;
6783
6784         mutex_lock(&dev_priv->sb_lock);
6785
6786         bestn = pipe_config->dpll.n;
6787         bestm1 = pipe_config->dpll.m1;
6788         bestm2 = pipe_config->dpll.m2;
6789         bestp1 = pipe_config->dpll.p1;
6790         bestp2 = pipe_config->dpll.p2;
6791
6792         /* See eDP HDMI DPIO driver vbios notes doc */
6793
6794         /* PLL B needs special handling */
6795         if (pipe == PIPE_B)
6796                 vlv_pllb_recal_opamp(dev_priv, pipe);
6797
6798         /* Set up Tx target for periodic Rcomp update */
6799         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6800
6801         /* Disable target IRef on PLL */
6802         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6803         reg_val &= 0x00ffffff;
6804         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6805
6806         /* Disable fast lock */
6807         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6808
6809         /* Set idtafcrecal before PLL is enabled */
6810         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6811         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6812         mdiv |= ((bestn << DPIO_N_SHIFT));
6813         mdiv |= (1 << DPIO_K_SHIFT);
6814
6815         /*
6816          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6817          * but we don't support that).
6818          * Note: don't use the DAC post divider as it seems unstable.
6819          */
6820         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6821         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6822
6823         mdiv |= DPIO_ENABLE_CALIBRATION;
6824         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6825
6826         /* Set HBR and RBR LPF coefficients */
6827         if (pipe_config->port_clock == 162000 ||
6828             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6829             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6830                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6831                                  0x009f0003);
6832         else
6833                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6834                                  0x00d0000f);
6835
6836         if (intel_crtc_has_dp_encoder(pipe_config)) {
6837                 /* Use SSC source */
6838                 if (pipe == PIPE_A)
6839                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6840                                          0x0df40000);
6841                 else
6842                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6843                                          0x0df70000);
6844         } else { /* HDMI or VGA */
6845                 /* Use bend source */
6846                 if (pipe == PIPE_A)
6847                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6848                                          0x0df70000);
6849                 else
6850                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6851                                          0x0df40000);
6852         }
6853
6854         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6855         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6856         if (intel_crtc_has_dp_encoder(crtc->config))
6857                 coreclk |= 0x01000000;
6858         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6859
6860         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6861         mutex_unlock(&dev_priv->sb_lock);
6862 }
6863
6864 static void chv_prepare_pll(struct intel_crtc *crtc,
6865                             const struct intel_crtc_state *pipe_config)
6866 {
6867         struct drm_device *dev = crtc->base.dev;
6868         struct drm_i915_private *dev_priv = to_i915(dev);
6869         enum pipe pipe = crtc->pipe;
6870         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6871         u32 loopfilter, tribuf_calcntr;
6872         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6873         u32 dpio_val;
6874         int vco;
6875
6876         /* Enable Refclk and SSC */
6877         I915_WRITE(DPLL(pipe),
6878                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6879
6880         /* No need to actually set up the DPLL with DSI */
6881         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6882                 return;
6883
6884         bestn = pipe_config->dpll.n;
6885         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6886         bestm1 = pipe_config->dpll.m1;
6887         bestm2 = pipe_config->dpll.m2 >> 22;
6888         bestp1 = pipe_config->dpll.p1;
6889         bestp2 = pipe_config->dpll.p2;
6890         vco = pipe_config->dpll.vco;
6891         dpio_val = 0;
6892         loopfilter = 0;
6893
6894         mutex_lock(&dev_priv->sb_lock);
6895
6896         /* p1 and p2 divider */
6897         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6898                         5 << DPIO_CHV_S1_DIV_SHIFT |
6899                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6900                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6901                         1 << DPIO_CHV_K_DIV_SHIFT);
6902
6903         /* Feedback post-divider - m2 */
6904         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6905
6906         /* Feedback refclk divider - n and m1 */
6907         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6908                         DPIO_CHV_M1_DIV_BY_2 |
6909                         1 << DPIO_CHV_N_DIV_SHIFT);
6910
6911         /* M2 fraction division */
6912         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6913
6914         /* M2 fraction division enable */
6915         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6916         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6917         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6918         if (bestm2_frac)
6919                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6920         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6921
6922         /* Program digital lock detect threshold */
6923         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6924         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6925                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6926         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6927         if (!bestm2_frac)
6928                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6929         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6930
6931         /* Loop filter */
6932         if (vco == 5400000) {
6933                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6934                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6935                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6936                 tribuf_calcntr = 0x9;
6937         } else if (vco <= 6200000) {
6938                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6939                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6940                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6941                 tribuf_calcntr = 0x9;
6942         } else if (vco <= 6480000) {
6943                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6944                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6945                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6946                 tribuf_calcntr = 0x8;
6947         } else {
6948                 /* Not supported. Apply the same limits as in the max case */
6949                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6950                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6951                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6952                 tribuf_calcntr = 0;
6953         }
6954         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6955
6956         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6957         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6958         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6959         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6960
6961         /* AFC Recal */
6962         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6963                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6964                         DPIO_AFC_RECAL);
6965
6966         mutex_unlock(&dev_priv->sb_lock);
6967 }
6968
6969 /**
6970  * vlv_force_pll_on - forcibly enable just the PLL
6971  * @dev_priv: i915 private structure
6972  * @pipe: pipe PLL to enable
6973  * @dpll: PLL configuration
6974  *
6975  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6976  * in cases where we need the PLL enabled even when @pipe is not going to
6977  * be enabled.
6978  */
6979 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6980                      const struct dpll *dpll)
6981 {
6982         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6983         struct intel_crtc_state *pipe_config;
6984
6985         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6986         if (!pipe_config)
6987                 return -ENOMEM;
6988
6989         pipe_config->base.crtc = &crtc->base;
6990         pipe_config->pixel_multiplier = 1;
6991         pipe_config->dpll = *dpll;
6992
6993         if (IS_CHERRYVIEW(dev_priv)) {
6994                 chv_compute_dpll(crtc, pipe_config);
6995                 chv_prepare_pll(crtc, pipe_config);
6996                 chv_enable_pll(crtc, pipe_config);
6997         } else {
6998                 vlv_compute_dpll(crtc, pipe_config);
6999                 vlv_prepare_pll(crtc, pipe_config);
7000                 vlv_enable_pll(crtc, pipe_config);
7001         }
7002
7003         kfree(pipe_config);
7004
7005         return 0;
7006 }
7007
7008 /**
7009  * vlv_force_pll_off - forcibly disable just the PLL
7010  * @dev_priv: i915 private structure
7011  * @pipe: pipe PLL to disable
7012  *
7013  * Disable the PLL for @pipe. To be used in cases where we need
7014  * the PLL enabled even when @pipe is not going to be enabled.
7015  */
7016 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7017 {
7018         if (IS_CHERRYVIEW(dev_priv))
7019                 chv_disable_pll(dev_priv, pipe);
7020         else
7021                 vlv_disable_pll(dev_priv, pipe);
7022 }
7023
7024 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7025                               struct intel_crtc_state *crtc_state,
7026                               struct dpll *reduced_clock)
7027 {
7028         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7029         u32 dpll;
7030         struct dpll *clock = &crtc_state->dpll;
7031
7032         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7033
7034         dpll = DPLL_VGA_MODE_DIS;
7035
7036         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7037                 dpll |= DPLLB_MODE_LVDS;
7038         else
7039                 dpll |= DPLLB_MODE_DAC_SERIAL;
7040
7041         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7042             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7043                 dpll |= (crtc_state->pixel_multiplier - 1)
7044                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7045         }
7046
7047         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7048             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7049                 dpll |= DPLL_SDVO_HIGH_SPEED;
7050
7051         if (intel_crtc_has_dp_encoder(crtc_state))
7052                 dpll |= DPLL_SDVO_HIGH_SPEED;
7053
7054         /* compute bitmask from p1 value */
7055         if (IS_PINEVIEW(dev_priv))
7056                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7057         else {
7058                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7059                 if (IS_G4X(dev_priv) && reduced_clock)
7060                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7061         }
7062         switch (clock->p2) {
7063         case 5:
7064                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7065                 break;
7066         case 7:
7067                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7068                 break;
7069         case 10:
7070                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7071                 break;
7072         case 14:
7073                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7074                 break;
7075         }
7076         if (INTEL_GEN(dev_priv) >= 4)
7077                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7078
7079         if (crtc_state->sdvo_tv_clock)
7080                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7081         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7082                  intel_panel_use_ssc(dev_priv))
7083                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7084         else
7085                 dpll |= PLL_REF_INPUT_DREFCLK;
7086
7087         dpll |= DPLL_VCO_ENABLE;
7088         crtc_state->dpll_hw_state.dpll = dpll;
7089
7090         if (INTEL_GEN(dev_priv) >= 4) {
7091                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7092                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7093                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7094         }
7095 }
7096
7097 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7098                               struct intel_crtc_state *crtc_state,
7099                               struct dpll *reduced_clock)
7100 {
7101         struct drm_device *dev = crtc->base.dev;
7102         struct drm_i915_private *dev_priv = to_i915(dev);
7103         u32 dpll;
7104         struct dpll *clock = &crtc_state->dpll;
7105
7106         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7107
7108         dpll = DPLL_VGA_MODE_DIS;
7109
7110         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7111                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7112         } else {
7113                 if (clock->p1 == 2)
7114                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7115                 else
7116                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7117                 if (clock->p2 == 4)
7118                         dpll |= PLL_P2_DIVIDE_BY_4;
7119         }
7120
7121         if (!IS_I830(dev_priv) &&
7122             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7123                 dpll |= DPLL_DVO_2X_MODE;
7124
7125         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7126             intel_panel_use_ssc(dev_priv))
7127                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7128         else
7129                 dpll |= PLL_REF_INPUT_DREFCLK;
7130
7131         dpll |= DPLL_VCO_ENABLE;
7132         crtc_state->dpll_hw_state.dpll = dpll;
7133 }
7134
7135 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7136 {
7137         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7138         enum pipe pipe = intel_crtc->pipe;
7139         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7140         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7141         uint32_t crtc_vtotal, crtc_vblank_end;
7142         int vsyncshift = 0;
7143
7144         /* We need to be careful not to changed the adjusted mode, for otherwise
7145          * the hw state checker will get angry at the mismatch. */
7146         crtc_vtotal = adjusted_mode->crtc_vtotal;
7147         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7148
7149         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7150                 /* the chip adds 2 halflines automatically */
7151                 crtc_vtotal -= 1;
7152                 crtc_vblank_end -= 1;
7153
7154                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7155                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7156                 else
7157                         vsyncshift = adjusted_mode->crtc_hsync_start -
7158                                 adjusted_mode->crtc_htotal / 2;
7159                 if (vsyncshift < 0)
7160                         vsyncshift += adjusted_mode->crtc_htotal;
7161         }
7162
7163         if (INTEL_GEN(dev_priv) > 3)
7164                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7165
7166         I915_WRITE(HTOTAL(cpu_transcoder),
7167                    (adjusted_mode->crtc_hdisplay - 1) |
7168                    ((adjusted_mode->crtc_htotal - 1) << 16));
7169         I915_WRITE(HBLANK(cpu_transcoder),
7170                    (adjusted_mode->crtc_hblank_start - 1) |
7171                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7172         I915_WRITE(HSYNC(cpu_transcoder),
7173                    (adjusted_mode->crtc_hsync_start - 1) |
7174                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7175
7176         I915_WRITE(VTOTAL(cpu_transcoder),
7177                    (adjusted_mode->crtc_vdisplay - 1) |
7178                    ((crtc_vtotal - 1) << 16));
7179         I915_WRITE(VBLANK(cpu_transcoder),
7180                    (adjusted_mode->crtc_vblank_start - 1) |
7181                    ((crtc_vblank_end - 1) << 16));
7182         I915_WRITE(VSYNC(cpu_transcoder),
7183                    (adjusted_mode->crtc_vsync_start - 1) |
7184                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7185
7186         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7187          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7188          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7189          * bits. */
7190         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7191             (pipe == PIPE_B || pipe == PIPE_C))
7192                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7193
7194 }
7195
7196 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7197 {
7198         struct drm_device *dev = intel_crtc->base.dev;
7199         struct drm_i915_private *dev_priv = to_i915(dev);
7200         enum pipe pipe = intel_crtc->pipe;
7201
7202         /* pipesrc controls the size that is scaled from, which should
7203          * always be the user's requested size.
7204          */
7205         I915_WRITE(PIPESRC(pipe),
7206                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7207                    (intel_crtc->config->pipe_src_h - 1));
7208 }
7209
7210 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7211                                    struct intel_crtc_state *pipe_config)
7212 {
7213         struct drm_device *dev = crtc->base.dev;
7214         struct drm_i915_private *dev_priv = to_i915(dev);
7215         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7216         uint32_t tmp;
7217
7218         tmp = I915_READ(HTOTAL(cpu_transcoder));
7219         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7220         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7221         tmp = I915_READ(HBLANK(cpu_transcoder));
7222         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7223         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7224         tmp = I915_READ(HSYNC(cpu_transcoder));
7225         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7226         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7227
7228         tmp = I915_READ(VTOTAL(cpu_transcoder));
7229         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7230         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7231         tmp = I915_READ(VBLANK(cpu_transcoder));
7232         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7233         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7234         tmp = I915_READ(VSYNC(cpu_transcoder));
7235         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7236         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7237
7238         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7239                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7240                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7241                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7242         }
7243 }
7244
7245 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7246                                     struct intel_crtc_state *pipe_config)
7247 {
7248         struct drm_device *dev = crtc->base.dev;
7249         struct drm_i915_private *dev_priv = to_i915(dev);
7250         u32 tmp;
7251
7252         tmp = I915_READ(PIPESRC(crtc->pipe));
7253         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7254         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7255
7256         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7257         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7258 }
7259
7260 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7261                                  struct intel_crtc_state *pipe_config)
7262 {
7263         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7264         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7265         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7266         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7267
7268         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7269         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7270         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7271         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7272
7273         mode->flags = pipe_config->base.adjusted_mode.flags;
7274         mode->type = DRM_MODE_TYPE_DRIVER;
7275
7276         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7277
7278         mode->hsync = drm_mode_hsync(mode);
7279         mode->vrefresh = drm_mode_vrefresh(mode);
7280         drm_mode_set_name(mode);
7281 }
7282
7283 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7284 {
7285         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7286         uint32_t pipeconf;
7287
7288         pipeconf = 0;
7289
7290         /* we keep both pipes enabled on 830 */
7291         if (IS_I830(dev_priv))
7292                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7293
7294         if (intel_crtc->config->double_wide)
7295                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7296
7297         /* only g4x and later have fancy bpc/dither controls */
7298         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7299             IS_CHERRYVIEW(dev_priv)) {
7300                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7301                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7302                         pipeconf |= PIPECONF_DITHER_EN |
7303                                     PIPECONF_DITHER_TYPE_SP;
7304
7305                 switch (intel_crtc->config->pipe_bpp) {
7306                 case 18:
7307                         pipeconf |= PIPECONF_6BPC;
7308                         break;
7309                 case 24:
7310                         pipeconf |= PIPECONF_8BPC;
7311                         break;
7312                 case 30:
7313                         pipeconf |= PIPECONF_10BPC;
7314                         break;
7315                 default:
7316                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7317                         BUG();
7318                 }
7319         }
7320
7321         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7322                 if (INTEL_GEN(dev_priv) < 4 ||
7323                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7324                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7325                 else
7326                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7327         } else
7328                 pipeconf |= PIPECONF_PROGRESSIVE;
7329
7330         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7331              intel_crtc->config->limited_color_range)
7332                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7333
7334         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7335         POSTING_READ(PIPECONF(intel_crtc->pipe));
7336 }
7337
7338 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7339                                    struct intel_crtc_state *crtc_state)
7340 {
7341         struct drm_device *dev = crtc->base.dev;
7342         struct drm_i915_private *dev_priv = to_i915(dev);
7343         const struct intel_limit *limit;
7344         int refclk = 48000;
7345
7346         memset(&crtc_state->dpll_hw_state, 0,
7347                sizeof(crtc_state->dpll_hw_state));
7348
7349         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7350                 if (intel_panel_use_ssc(dev_priv)) {
7351                         refclk = dev_priv->vbt.lvds_ssc_freq;
7352                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7353                 }
7354
7355                 limit = &intel_limits_i8xx_lvds;
7356         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7357                 limit = &intel_limits_i8xx_dvo;
7358         } else {
7359                 limit = &intel_limits_i8xx_dac;
7360         }
7361
7362         if (!crtc_state->clock_set &&
7363             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7364                                  refclk, NULL, &crtc_state->dpll)) {
7365                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7366                 return -EINVAL;
7367         }
7368
7369         i8xx_compute_dpll(crtc, crtc_state, NULL);
7370
7371         return 0;
7372 }
7373
7374 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7375                                   struct intel_crtc_state *crtc_state)
7376 {
7377         struct drm_device *dev = crtc->base.dev;
7378         struct drm_i915_private *dev_priv = to_i915(dev);
7379         const struct intel_limit *limit;
7380         int refclk = 96000;
7381
7382         memset(&crtc_state->dpll_hw_state, 0,
7383                sizeof(crtc_state->dpll_hw_state));
7384
7385         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7386                 if (intel_panel_use_ssc(dev_priv)) {
7387                         refclk = dev_priv->vbt.lvds_ssc_freq;
7388                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7389                 }
7390
7391                 if (intel_is_dual_link_lvds(dev))
7392                         limit = &intel_limits_g4x_dual_channel_lvds;
7393                 else
7394                         limit = &intel_limits_g4x_single_channel_lvds;
7395         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7396                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7397                 limit = &intel_limits_g4x_hdmi;
7398         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7399                 limit = &intel_limits_g4x_sdvo;
7400         } else {
7401                 /* The option is for other outputs */
7402                 limit = &intel_limits_i9xx_sdvo;
7403         }
7404
7405         if (!crtc_state->clock_set &&
7406             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7407                                 refclk, NULL, &crtc_state->dpll)) {
7408                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7409                 return -EINVAL;
7410         }
7411
7412         i9xx_compute_dpll(crtc, crtc_state, NULL);
7413
7414         return 0;
7415 }
7416
7417 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7418                                   struct intel_crtc_state *crtc_state)
7419 {
7420         struct drm_device *dev = crtc->base.dev;
7421         struct drm_i915_private *dev_priv = to_i915(dev);
7422         const struct intel_limit *limit;
7423         int refclk = 96000;
7424
7425         memset(&crtc_state->dpll_hw_state, 0,
7426                sizeof(crtc_state->dpll_hw_state));
7427
7428         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7429                 if (intel_panel_use_ssc(dev_priv)) {
7430                         refclk = dev_priv->vbt.lvds_ssc_freq;
7431                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7432                 }
7433
7434                 limit = &intel_limits_pineview_lvds;
7435         } else {
7436                 limit = &intel_limits_pineview_sdvo;
7437         }
7438
7439         if (!crtc_state->clock_set &&
7440             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7441                                 refclk, NULL, &crtc_state->dpll)) {
7442                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7443                 return -EINVAL;
7444         }
7445
7446         i9xx_compute_dpll(crtc, crtc_state, NULL);
7447
7448         return 0;
7449 }
7450
7451 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7452                                    struct intel_crtc_state *crtc_state)
7453 {
7454         struct drm_device *dev = crtc->base.dev;
7455         struct drm_i915_private *dev_priv = to_i915(dev);
7456         const struct intel_limit *limit;
7457         int refclk = 96000;
7458
7459         memset(&crtc_state->dpll_hw_state, 0,
7460                sizeof(crtc_state->dpll_hw_state));
7461
7462         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7463                 if (intel_panel_use_ssc(dev_priv)) {
7464                         refclk = dev_priv->vbt.lvds_ssc_freq;
7465                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7466                 }
7467
7468                 limit = &intel_limits_i9xx_lvds;
7469         } else {
7470                 limit = &intel_limits_i9xx_sdvo;
7471         }
7472
7473         if (!crtc_state->clock_set &&
7474             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7475                                  refclk, NULL, &crtc_state->dpll)) {
7476                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7477                 return -EINVAL;
7478         }
7479
7480         i9xx_compute_dpll(crtc, crtc_state, NULL);
7481
7482         return 0;
7483 }
7484
7485 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7486                                   struct intel_crtc_state *crtc_state)
7487 {
7488         int refclk = 100000;
7489         const struct intel_limit *limit = &intel_limits_chv;
7490
7491         memset(&crtc_state->dpll_hw_state, 0,
7492                sizeof(crtc_state->dpll_hw_state));
7493
7494         if (!crtc_state->clock_set &&
7495             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7496                                 refclk, NULL, &crtc_state->dpll)) {
7497                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7498                 return -EINVAL;
7499         }
7500
7501         chv_compute_dpll(crtc, crtc_state);
7502
7503         return 0;
7504 }
7505
7506 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7507                                   struct intel_crtc_state *crtc_state)
7508 {
7509         int refclk = 100000;
7510         const struct intel_limit *limit = &intel_limits_vlv;
7511
7512         memset(&crtc_state->dpll_hw_state, 0,
7513                sizeof(crtc_state->dpll_hw_state));
7514
7515         if (!crtc_state->clock_set &&
7516             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7517                                 refclk, NULL, &crtc_state->dpll)) {
7518                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7519                 return -EINVAL;
7520         }
7521
7522         vlv_compute_dpll(crtc, crtc_state);
7523
7524         return 0;
7525 }
7526
7527 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7528                                  struct intel_crtc_state *pipe_config)
7529 {
7530         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7531         uint32_t tmp;
7532
7533         if (INTEL_GEN(dev_priv) <= 3 &&
7534             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7535                 return;
7536
7537         tmp = I915_READ(PFIT_CONTROL);
7538         if (!(tmp & PFIT_ENABLE))
7539                 return;
7540
7541         /* Check whether the pfit is attached to our pipe. */
7542         if (INTEL_GEN(dev_priv) < 4) {
7543                 if (crtc->pipe != PIPE_B)
7544                         return;
7545         } else {
7546                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7547                         return;
7548         }
7549
7550         pipe_config->gmch_pfit.control = tmp;
7551         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7552 }
7553
7554 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7555                                struct intel_crtc_state *pipe_config)
7556 {
7557         struct drm_device *dev = crtc->base.dev;
7558         struct drm_i915_private *dev_priv = to_i915(dev);
7559         int pipe = pipe_config->cpu_transcoder;
7560         struct dpll clock;
7561         u32 mdiv;
7562         int refclk = 100000;
7563
7564         /* In case of DSI, DPLL will not be used */
7565         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7566                 return;
7567
7568         mutex_lock(&dev_priv->sb_lock);
7569         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7570         mutex_unlock(&dev_priv->sb_lock);
7571
7572         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7573         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7574         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7575         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7576         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7577
7578         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7579 }
7580
7581 static void
7582 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7583                               struct intel_initial_plane_config *plane_config)
7584 {
7585         struct drm_device *dev = crtc->base.dev;
7586         struct drm_i915_private *dev_priv = to_i915(dev);
7587         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7588         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7589         enum pipe pipe = crtc->pipe;
7590         u32 val, base, offset;
7591         int fourcc, pixel_format;
7592         unsigned int aligned_height;
7593         struct drm_framebuffer *fb;
7594         struct intel_framebuffer *intel_fb;
7595
7596         if (!plane->get_hw_state(plane))
7597                 return;
7598
7599         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7600         if (!intel_fb) {
7601                 DRM_DEBUG_KMS("failed to alloc fb\n");
7602                 return;
7603         }
7604
7605         fb = &intel_fb->base;
7606
7607         fb->dev = dev;
7608
7609         val = I915_READ(DSPCNTR(i9xx_plane));
7610
7611         if (INTEL_GEN(dev_priv) >= 4) {
7612                 if (val & DISPPLANE_TILED) {
7613                         plane_config->tiling = I915_TILING_X;
7614                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7615                 }
7616         }
7617
7618         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7619         fourcc = i9xx_format_to_fourcc(pixel_format);
7620         fb->format = drm_format_info(fourcc);
7621
7622         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7623                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7624                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7625         } else if (INTEL_GEN(dev_priv) >= 4) {
7626                 if (plane_config->tiling)
7627                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7628                 else
7629                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7630                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7631         } else {
7632                 base = I915_READ(DSPADDR(i9xx_plane));
7633         }
7634         plane_config->base = base;
7635
7636         val = I915_READ(PIPESRC(pipe));
7637         fb->width = ((val >> 16) & 0xfff) + 1;
7638         fb->height = ((val >> 0) & 0xfff) + 1;
7639
7640         val = I915_READ(DSPSTRIDE(i9xx_plane));
7641         fb->pitches[0] = val & 0xffffffc0;
7642
7643         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7644
7645         plane_config->size = fb->pitches[0] * aligned_height;
7646
7647         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7648                       crtc->base.name, plane->base.name, fb->width, fb->height,
7649                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7650                       plane_config->size);
7651
7652         plane_config->fb = intel_fb;
7653 }
7654
7655 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7656                                struct intel_crtc_state *pipe_config)
7657 {
7658         struct drm_device *dev = crtc->base.dev;
7659         struct drm_i915_private *dev_priv = to_i915(dev);
7660         int pipe = pipe_config->cpu_transcoder;
7661         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7662         struct dpll clock;
7663         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7664         int refclk = 100000;
7665
7666         /* In case of DSI, DPLL will not be used */
7667         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7668                 return;
7669
7670         mutex_lock(&dev_priv->sb_lock);
7671         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7672         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7673         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7674         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7675         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7676         mutex_unlock(&dev_priv->sb_lock);
7677
7678         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7679         clock.m2 = (pll_dw0 & 0xff) << 22;
7680         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7681                 clock.m2 |= pll_dw2 & 0x3fffff;
7682         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7683         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7684         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7685
7686         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7687 }
7688
7689 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7690                                  struct intel_crtc_state *pipe_config)
7691 {
7692         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7693         enum intel_display_power_domain power_domain;
7694         uint32_t tmp;
7695         bool ret;
7696
7697         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7698         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7699                 return false;
7700
7701         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7702         pipe_config->shared_dpll = NULL;
7703
7704         ret = false;
7705
7706         tmp = I915_READ(PIPECONF(crtc->pipe));
7707         if (!(tmp & PIPECONF_ENABLE))
7708                 goto out;
7709
7710         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7711             IS_CHERRYVIEW(dev_priv)) {
7712                 switch (tmp & PIPECONF_BPC_MASK) {
7713                 case PIPECONF_6BPC:
7714                         pipe_config->pipe_bpp = 18;
7715                         break;
7716                 case PIPECONF_8BPC:
7717                         pipe_config->pipe_bpp = 24;
7718                         break;
7719                 case PIPECONF_10BPC:
7720                         pipe_config->pipe_bpp = 30;
7721                         break;
7722                 default:
7723                         break;
7724                 }
7725         }
7726
7727         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7728             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7729                 pipe_config->limited_color_range = true;
7730
7731         if (INTEL_GEN(dev_priv) < 4)
7732                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7733
7734         intel_get_pipe_timings(crtc, pipe_config);
7735         intel_get_pipe_src_size(crtc, pipe_config);
7736
7737         i9xx_get_pfit_config(crtc, pipe_config);
7738
7739         if (INTEL_GEN(dev_priv) >= 4) {
7740                 /* No way to read it out on pipes B and C */
7741                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7742                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7743                 else
7744                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7745                 pipe_config->pixel_multiplier =
7746                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7747                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7748                 pipe_config->dpll_hw_state.dpll_md = tmp;
7749         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7750                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7751                 tmp = I915_READ(DPLL(crtc->pipe));
7752                 pipe_config->pixel_multiplier =
7753                         ((tmp & SDVO_MULTIPLIER_MASK)
7754                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7755         } else {
7756                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7757                  * port and will be fixed up in the encoder->get_config
7758                  * function. */
7759                 pipe_config->pixel_multiplier = 1;
7760         }
7761         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7762         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7763                 /*
7764                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7765                  * on 830. Filter it out here so that we don't
7766                  * report errors due to that.
7767                  */
7768                 if (IS_I830(dev_priv))
7769                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7770
7771                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7772                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7773         } else {
7774                 /* Mask out read-only status bits. */
7775                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7776                                                      DPLL_PORTC_READY_MASK |
7777                                                      DPLL_PORTB_READY_MASK);
7778         }
7779
7780         if (IS_CHERRYVIEW(dev_priv))
7781                 chv_crtc_clock_get(crtc, pipe_config);
7782         else if (IS_VALLEYVIEW(dev_priv))
7783                 vlv_crtc_clock_get(crtc, pipe_config);
7784         else
7785                 i9xx_crtc_clock_get(crtc, pipe_config);
7786
7787         /*
7788          * Normally the dotclock is filled in by the encoder .get_config()
7789          * but in case the pipe is enabled w/o any ports we need a sane
7790          * default.
7791          */
7792         pipe_config->base.adjusted_mode.crtc_clock =
7793                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7794
7795         ret = true;
7796
7797 out:
7798         intel_display_power_put(dev_priv, power_domain);
7799
7800         return ret;
7801 }
7802
7803 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7804 {
7805         struct intel_encoder *encoder;
7806         int i;
7807         u32 val, final;
7808         bool has_lvds = false;
7809         bool has_cpu_edp = false;
7810         bool has_panel = false;
7811         bool has_ck505 = false;
7812         bool can_ssc = false;
7813         bool using_ssc_source = false;
7814
7815         /* We need to take the global config into account */
7816         for_each_intel_encoder(&dev_priv->drm, encoder) {
7817                 switch (encoder->type) {
7818                 case INTEL_OUTPUT_LVDS:
7819                         has_panel = true;
7820                         has_lvds = true;
7821                         break;
7822                 case INTEL_OUTPUT_EDP:
7823                         has_panel = true;
7824                         if (encoder->port == PORT_A)
7825                                 has_cpu_edp = true;
7826                         break;
7827                 default:
7828                         break;
7829                 }
7830         }
7831
7832         if (HAS_PCH_IBX(dev_priv)) {
7833                 has_ck505 = dev_priv->vbt.display_clock_mode;
7834                 can_ssc = has_ck505;
7835         } else {
7836                 has_ck505 = false;
7837                 can_ssc = true;
7838         }
7839
7840         /* Check if any DPLLs are using the SSC source */
7841         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7842                 u32 temp = I915_READ(PCH_DPLL(i));
7843
7844                 if (!(temp & DPLL_VCO_ENABLE))
7845                         continue;
7846
7847                 if ((temp & PLL_REF_INPUT_MASK) ==
7848                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7849                         using_ssc_source = true;
7850                         break;
7851                 }
7852         }
7853
7854         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7855                       has_panel, has_lvds, has_ck505, using_ssc_source);
7856
7857         /* Ironlake: try to setup display ref clock before DPLL
7858          * enabling. This is only under driver's control after
7859          * PCH B stepping, previous chipset stepping should be
7860          * ignoring this setting.
7861          */
7862         val = I915_READ(PCH_DREF_CONTROL);
7863
7864         /* As we must carefully and slowly disable/enable each source in turn,
7865          * compute the final state we want first and check if we need to
7866          * make any changes at all.
7867          */
7868         final = val;
7869         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7870         if (has_ck505)
7871                 final |= DREF_NONSPREAD_CK505_ENABLE;
7872         else
7873                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7874
7875         final &= ~DREF_SSC_SOURCE_MASK;
7876         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7877         final &= ~DREF_SSC1_ENABLE;
7878
7879         if (has_panel) {
7880                 final |= DREF_SSC_SOURCE_ENABLE;
7881
7882                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7883                         final |= DREF_SSC1_ENABLE;
7884
7885                 if (has_cpu_edp) {
7886                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7887                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7888                         else
7889                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7890                 } else
7891                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7892         } else if (using_ssc_source) {
7893                 final |= DREF_SSC_SOURCE_ENABLE;
7894                 final |= DREF_SSC1_ENABLE;
7895         }
7896
7897         if (final == val)
7898                 return;
7899
7900         /* Always enable nonspread source */
7901         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7902
7903         if (has_ck505)
7904                 val |= DREF_NONSPREAD_CK505_ENABLE;
7905         else
7906                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7907
7908         if (has_panel) {
7909                 val &= ~DREF_SSC_SOURCE_MASK;
7910                 val |= DREF_SSC_SOURCE_ENABLE;
7911
7912                 /* SSC must be turned on before enabling the CPU output  */
7913                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7914                         DRM_DEBUG_KMS("Using SSC on panel\n");
7915                         val |= DREF_SSC1_ENABLE;
7916                 } else
7917                         val &= ~DREF_SSC1_ENABLE;
7918
7919                 /* Get SSC going before enabling the outputs */
7920                 I915_WRITE(PCH_DREF_CONTROL, val);
7921                 POSTING_READ(PCH_DREF_CONTROL);
7922                 udelay(200);
7923
7924                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7925
7926                 /* Enable CPU source on CPU attached eDP */
7927                 if (has_cpu_edp) {
7928                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7929                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7930                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7931                         } else
7932                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7933                 } else
7934                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7935
7936                 I915_WRITE(PCH_DREF_CONTROL, val);
7937                 POSTING_READ(PCH_DREF_CONTROL);
7938                 udelay(200);
7939         } else {
7940                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7941
7942                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7943
7944                 /* Turn off CPU output */
7945                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7946
7947                 I915_WRITE(PCH_DREF_CONTROL, val);
7948                 POSTING_READ(PCH_DREF_CONTROL);
7949                 udelay(200);
7950
7951                 if (!using_ssc_source) {
7952                         DRM_DEBUG_KMS("Disabling SSC source\n");
7953
7954                         /* Turn off the SSC source */
7955                         val &= ~DREF_SSC_SOURCE_MASK;
7956                         val |= DREF_SSC_SOURCE_DISABLE;
7957
7958                         /* Turn off SSC1 */
7959                         val &= ~DREF_SSC1_ENABLE;
7960
7961                         I915_WRITE(PCH_DREF_CONTROL, val);
7962                         POSTING_READ(PCH_DREF_CONTROL);
7963                         udelay(200);
7964                 }
7965         }
7966
7967         BUG_ON(val != final);
7968 }
7969
7970 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7971 {
7972         uint32_t tmp;
7973
7974         tmp = I915_READ(SOUTH_CHICKEN2);
7975         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7976         I915_WRITE(SOUTH_CHICKEN2, tmp);
7977
7978         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7979                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7980                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7981
7982         tmp = I915_READ(SOUTH_CHICKEN2);
7983         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7984         I915_WRITE(SOUTH_CHICKEN2, tmp);
7985
7986         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7987                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7988                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7989 }
7990
7991 /* WaMPhyProgramming:hsw */
7992 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7993 {
7994         uint32_t tmp;
7995
7996         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7997         tmp &= ~(0xFF << 24);
7998         tmp |= (0x12 << 24);
7999         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8000
8001         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8002         tmp |= (1 << 11);
8003         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8004
8005         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8006         tmp |= (1 << 11);
8007         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8008
8009         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8010         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8011         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8012
8013         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8014         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8015         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8016
8017         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8018         tmp &= ~(7 << 13);
8019         tmp |= (5 << 13);
8020         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8021
8022         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8023         tmp &= ~(7 << 13);
8024         tmp |= (5 << 13);
8025         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8026
8027         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8028         tmp &= ~0xFF;
8029         tmp |= 0x1C;
8030         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8031
8032         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8033         tmp &= ~0xFF;
8034         tmp |= 0x1C;
8035         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8036
8037         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8038         tmp &= ~(0xFF << 16);
8039         tmp |= (0x1C << 16);
8040         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8041
8042         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8043         tmp &= ~(0xFF << 16);
8044         tmp |= (0x1C << 16);
8045         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8046
8047         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8048         tmp |= (1 << 27);
8049         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8050
8051         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8052         tmp |= (1 << 27);
8053         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8054
8055         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8056         tmp &= ~(0xF << 28);
8057         tmp |= (4 << 28);
8058         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8059
8060         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8061         tmp &= ~(0xF << 28);
8062         tmp |= (4 << 28);
8063         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8064 }
8065
8066 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8067  * Programming" based on the parameters passed:
8068  * - Sequence to enable CLKOUT_DP
8069  * - Sequence to enable CLKOUT_DP without spread
8070  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8071  */
8072 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8073                                  bool with_spread, bool with_fdi)
8074 {
8075         uint32_t reg, tmp;
8076
8077         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8078                 with_spread = true;
8079         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8080             with_fdi, "LP PCH doesn't have FDI\n"))
8081                 with_fdi = false;
8082
8083         mutex_lock(&dev_priv->sb_lock);
8084
8085         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8086         tmp &= ~SBI_SSCCTL_DISABLE;
8087         tmp |= SBI_SSCCTL_PATHALT;
8088         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8089
8090         udelay(24);
8091
8092         if (with_spread) {
8093                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8094                 tmp &= ~SBI_SSCCTL_PATHALT;
8095                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8096
8097                 if (with_fdi) {
8098                         lpt_reset_fdi_mphy(dev_priv);
8099                         lpt_program_fdi_mphy(dev_priv);
8100                 }
8101         }
8102
8103         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8104         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8105         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8106         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8107
8108         mutex_unlock(&dev_priv->sb_lock);
8109 }
8110
8111 /* Sequence to disable CLKOUT_DP */
8112 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8113 {
8114         uint32_t reg, tmp;
8115
8116         mutex_lock(&dev_priv->sb_lock);
8117
8118         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8119         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8120         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8121         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8122
8123         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8124         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8125                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8126                         tmp |= SBI_SSCCTL_PATHALT;
8127                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8128                         udelay(32);
8129                 }
8130                 tmp |= SBI_SSCCTL_DISABLE;
8131                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8132         }
8133
8134         mutex_unlock(&dev_priv->sb_lock);
8135 }
8136
8137 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8138
8139 static const uint16_t sscdivintphase[] = {
8140         [BEND_IDX( 50)] = 0x3B23,
8141         [BEND_IDX( 45)] = 0x3B23,
8142         [BEND_IDX( 40)] = 0x3C23,
8143         [BEND_IDX( 35)] = 0x3C23,
8144         [BEND_IDX( 30)] = 0x3D23,
8145         [BEND_IDX( 25)] = 0x3D23,
8146         [BEND_IDX( 20)] = 0x3E23,
8147         [BEND_IDX( 15)] = 0x3E23,
8148         [BEND_IDX( 10)] = 0x3F23,
8149         [BEND_IDX(  5)] = 0x3F23,
8150         [BEND_IDX(  0)] = 0x0025,
8151         [BEND_IDX( -5)] = 0x0025,
8152         [BEND_IDX(-10)] = 0x0125,
8153         [BEND_IDX(-15)] = 0x0125,
8154         [BEND_IDX(-20)] = 0x0225,
8155         [BEND_IDX(-25)] = 0x0225,
8156         [BEND_IDX(-30)] = 0x0325,
8157         [BEND_IDX(-35)] = 0x0325,
8158         [BEND_IDX(-40)] = 0x0425,
8159         [BEND_IDX(-45)] = 0x0425,
8160         [BEND_IDX(-50)] = 0x0525,
8161 };
8162
8163 /*
8164  * Bend CLKOUT_DP
8165  * steps -50 to 50 inclusive, in steps of 5
8166  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8167  * change in clock period = -(steps / 10) * 5.787 ps
8168  */
8169 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8170 {
8171         uint32_t tmp;
8172         int idx = BEND_IDX(steps);
8173
8174         if (WARN_ON(steps % 5 != 0))
8175                 return;
8176
8177         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8178                 return;
8179
8180         mutex_lock(&dev_priv->sb_lock);
8181
8182         if (steps % 10 != 0)
8183                 tmp = 0xAAAAAAAB;
8184         else
8185                 tmp = 0x00000000;
8186         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8187
8188         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8189         tmp &= 0xffff0000;
8190         tmp |= sscdivintphase[idx];
8191         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8192
8193         mutex_unlock(&dev_priv->sb_lock);
8194 }
8195
8196 #undef BEND_IDX
8197
8198 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8199 {
8200         struct intel_encoder *encoder;
8201         bool has_vga = false;
8202
8203         for_each_intel_encoder(&dev_priv->drm, encoder) {
8204                 switch (encoder->type) {
8205                 case INTEL_OUTPUT_ANALOG:
8206                         has_vga = true;
8207                         break;
8208                 default:
8209                         break;
8210                 }
8211         }
8212
8213         if (has_vga) {
8214                 lpt_bend_clkout_dp(dev_priv, 0);
8215                 lpt_enable_clkout_dp(dev_priv, true, true);
8216         } else {
8217                 lpt_disable_clkout_dp(dev_priv);
8218         }
8219 }
8220
8221 /*
8222  * Initialize reference clocks when the driver loads
8223  */
8224 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8225 {
8226         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8227                 ironlake_init_pch_refclk(dev_priv);
8228         else if (HAS_PCH_LPT(dev_priv))
8229                 lpt_init_pch_refclk(dev_priv);
8230 }
8231
8232 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8233 {
8234         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8235         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8236         int pipe = intel_crtc->pipe;
8237         uint32_t val;
8238
8239         val = 0;
8240
8241         switch (intel_crtc->config->pipe_bpp) {
8242         case 18:
8243                 val |= PIPECONF_6BPC;
8244                 break;
8245         case 24:
8246                 val |= PIPECONF_8BPC;
8247                 break;
8248         case 30:
8249                 val |= PIPECONF_10BPC;
8250                 break;
8251         case 36:
8252                 val |= PIPECONF_12BPC;
8253                 break;
8254         default:
8255                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8256                 BUG();
8257         }
8258
8259         if (intel_crtc->config->dither)
8260                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8261
8262         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8263                 val |= PIPECONF_INTERLACED_ILK;
8264         else
8265                 val |= PIPECONF_PROGRESSIVE;
8266
8267         if (intel_crtc->config->limited_color_range)
8268                 val |= PIPECONF_COLOR_RANGE_SELECT;
8269
8270         I915_WRITE(PIPECONF(pipe), val);
8271         POSTING_READ(PIPECONF(pipe));
8272 }
8273
8274 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8275 {
8276         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8277         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8278         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8279         u32 val = 0;
8280
8281         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8282                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8283
8284         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8285                 val |= PIPECONF_INTERLACED_ILK;
8286         else
8287                 val |= PIPECONF_PROGRESSIVE;
8288
8289         I915_WRITE(PIPECONF(cpu_transcoder), val);
8290         POSTING_READ(PIPECONF(cpu_transcoder));
8291 }
8292
8293 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8294 {
8295         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8296         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8297         struct intel_crtc_state *config = intel_crtc->config;
8298
8299         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8300                 u32 val = 0;
8301
8302                 switch (intel_crtc->config->pipe_bpp) {
8303                 case 18:
8304                         val |= PIPEMISC_DITHER_6_BPC;
8305                         break;
8306                 case 24:
8307                         val |= PIPEMISC_DITHER_8_BPC;
8308                         break;
8309                 case 30:
8310                         val |= PIPEMISC_DITHER_10_BPC;
8311                         break;
8312                 case 36:
8313                         val |= PIPEMISC_DITHER_12_BPC;
8314                         break;
8315                 default:
8316                         /* Case prevented by pipe_config_set_bpp. */
8317                         BUG();
8318                 }
8319
8320                 if (intel_crtc->config->dither)
8321                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8322
8323                 if (config->ycbcr420) {
8324                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8325                                 PIPEMISC_YUV420_ENABLE |
8326                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8327                 }
8328
8329                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8330         }
8331 }
8332
8333 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8334 {
8335         /*
8336          * Account for spread spectrum to avoid
8337          * oversubscribing the link. Max center spread
8338          * is 2.5%; use 5% for safety's sake.
8339          */
8340         u32 bps = target_clock * bpp * 21 / 20;
8341         return DIV_ROUND_UP(bps, link_bw * 8);
8342 }
8343
8344 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8345 {
8346         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8347 }
8348
8349 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8350                                   struct intel_crtc_state *crtc_state,
8351                                   struct dpll *reduced_clock)
8352 {
8353         struct drm_crtc *crtc = &intel_crtc->base;
8354         struct drm_device *dev = crtc->dev;
8355         struct drm_i915_private *dev_priv = to_i915(dev);
8356         u32 dpll, fp, fp2;
8357         int factor;
8358
8359         /* Enable autotuning of the PLL clock (if permissible) */
8360         factor = 21;
8361         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8362                 if ((intel_panel_use_ssc(dev_priv) &&
8363                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8364                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8365                         factor = 25;
8366         } else if (crtc_state->sdvo_tv_clock)
8367                 factor = 20;
8368
8369         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8370
8371         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8372                 fp |= FP_CB_TUNE;
8373
8374         if (reduced_clock) {
8375                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8376
8377                 if (reduced_clock->m < factor * reduced_clock->n)
8378                         fp2 |= FP_CB_TUNE;
8379         } else {
8380                 fp2 = fp;
8381         }
8382
8383         dpll = 0;
8384
8385         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8386                 dpll |= DPLLB_MODE_LVDS;
8387         else
8388                 dpll |= DPLLB_MODE_DAC_SERIAL;
8389
8390         dpll |= (crtc_state->pixel_multiplier - 1)
8391                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8392
8393         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8394             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8395                 dpll |= DPLL_SDVO_HIGH_SPEED;
8396
8397         if (intel_crtc_has_dp_encoder(crtc_state))
8398                 dpll |= DPLL_SDVO_HIGH_SPEED;
8399
8400         /*
8401          * The high speed IO clock is only really required for
8402          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8403          * possible to share the DPLL between CRT and HDMI. Enabling
8404          * the clock needlessly does no real harm, except use up a
8405          * bit of power potentially.
8406          *
8407          * We'll limit this to IVB with 3 pipes, since it has only two
8408          * DPLLs and so DPLL sharing is the only way to get three pipes
8409          * driving PCH ports at the same time. On SNB we could do this,
8410          * and potentially avoid enabling the second DPLL, but it's not
8411          * clear if it''s a win or loss power wise. No point in doing
8412          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8413          */
8414         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8415             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8416                 dpll |= DPLL_SDVO_HIGH_SPEED;
8417
8418         /* compute bitmask from p1 value */
8419         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8420         /* also FPA1 */
8421         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8422
8423         switch (crtc_state->dpll.p2) {
8424         case 5:
8425                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8426                 break;
8427         case 7:
8428                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8429                 break;
8430         case 10:
8431                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8432                 break;
8433         case 14:
8434                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8435                 break;
8436         }
8437
8438         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8439             intel_panel_use_ssc(dev_priv))
8440                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8441         else
8442                 dpll |= PLL_REF_INPUT_DREFCLK;
8443
8444         dpll |= DPLL_VCO_ENABLE;
8445
8446         crtc_state->dpll_hw_state.dpll = dpll;
8447         crtc_state->dpll_hw_state.fp0 = fp;
8448         crtc_state->dpll_hw_state.fp1 = fp2;
8449 }
8450
8451 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8452                                        struct intel_crtc_state *crtc_state)
8453 {
8454         struct drm_device *dev = crtc->base.dev;
8455         struct drm_i915_private *dev_priv = to_i915(dev);
8456         const struct intel_limit *limit;
8457         int refclk = 120000;
8458
8459         memset(&crtc_state->dpll_hw_state, 0,
8460                sizeof(crtc_state->dpll_hw_state));
8461
8462         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8463         if (!crtc_state->has_pch_encoder)
8464                 return 0;
8465
8466         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8467                 if (intel_panel_use_ssc(dev_priv)) {
8468                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8469                                       dev_priv->vbt.lvds_ssc_freq);
8470                         refclk = dev_priv->vbt.lvds_ssc_freq;
8471                 }
8472
8473                 if (intel_is_dual_link_lvds(dev)) {
8474                         if (refclk == 100000)
8475                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8476                         else
8477                                 limit = &intel_limits_ironlake_dual_lvds;
8478                 } else {
8479                         if (refclk == 100000)
8480                                 limit = &intel_limits_ironlake_single_lvds_100m;
8481                         else
8482                                 limit = &intel_limits_ironlake_single_lvds;
8483                 }
8484         } else {
8485                 limit = &intel_limits_ironlake_dac;
8486         }
8487
8488         if (!crtc_state->clock_set &&
8489             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8490                                 refclk, NULL, &crtc_state->dpll)) {
8491                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8492                 return -EINVAL;
8493         }
8494
8495         ironlake_compute_dpll(crtc, crtc_state, NULL);
8496
8497         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8498                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8499                                  pipe_name(crtc->pipe));
8500                 return -EINVAL;
8501         }
8502
8503         return 0;
8504 }
8505
8506 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8507                                          struct intel_link_m_n *m_n)
8508 {
8509         struct drm_device *dev = crtc->base.dev;
8510         struct drm_i915_private *dev_priv = to_i915(dev);
8511         enum pipe pipe = crtc->pipe;
8512
8513         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8514         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8515         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8516                 & ~TU_SIZE_MASK;
8517         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8518         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8519                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8520 }
8521
8522 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8523                                          enum transcoder transcoder,
8524                                          struct intel_link_m_n *m_n,
8525                                          struct intel_link_m_n *m2_n2)
8526 {
8527         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8528         enum pipe pipe = crtc->pipe;
8529
8530         if (INTEL_GEN(dev_priv) >= 5) {
8531                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8532                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8533                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8534                         & ~TU_SIZE_MASK;
8535                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8536                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8537                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8538                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8539                  * gen < 8) and if DRRS is supported (to make sure the
8540                  * registers are not unnecessarily read).
8541                  */
8542                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8543                         crtc->config->has_drrs) {
8544                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8545                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8546                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8547                                         & ~TU_SIZE_MASK;
8548                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8549                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8550                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8551                 }
8552         } else {
8553                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8554                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8555                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8556                         & ~TU_SIZE_MASK;
8557                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8558                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8559                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8560         }
8561 }
8562
8563 void intel_dp_get_m_n(struct intel_crtc *crtc,
8564                       struct intel_crtc_state *pipe_config)
8565 {
8566         if (pipe_config->has_pch_encoder)
8567                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8568         else
8569                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8570                                              &pipe_config->dp_m_n,
8571                                              &pipe_config->dp_m2_n2);
8572 }
8573
8574 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8575                                         struct intel_crtc_state *pipe_config)
8576 {
8577         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8578                                      &pipe_config->fdi_m_n, NULL);
8579 }
8580
8581 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8582                                     struct intel_crtc_state *pipe_config)
8583 {
8584         struct drm_device *dev = crtc->base.dev;
8585         struct drm_i915_private *dev_priv = to_i915(dev);
8586         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8587         uint32_t ps_ctrl = 0;
8588         int id = -1;
8589         int i;
8590
8591         /* find scaler attached to this pipe */
8592         for (i = 0; i < crtc->num_scalers; i++) {
8593                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8594                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8595                         id = i;
8596                         pipe_config->pch_pfit.enabled = true;
8597                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8598                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8599                         break;
8600                 }
8601         }
8602
8603         scaler_state->scaler_id = id;
8604         if (id >= 0) {
8605                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8606         } else {
8607                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8608         }
8609 }
8610
8611 static void
8612 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8613                                  struct intel_initial_plane_config *plane_config)
8614 {
8615         struct drm_device *dev = crtc->base.dev;
8616         struct drm_i915_private *dev_priv = to_i915(dev);
8617         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8618         enum plane_id plane_id = plane->id;
8619         enum pipe pipe = crtc->pipe;
8620         u32 val, base, offset, stride_mult, tiling, alpha;
8621         int fourcc, pixel_format;
8622         unsigned int aligned_height;
8623         struct drm_framebuffer *fb;
8624         struct intel_framebuffer *intel_fb;
8625
8626         if (!plane->get_hw_state(plane))
8627                 return;
8628
8629         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8630         if (!intel_fb) {
8631                 DRM_DEBUG_KMS("failed to alloc fb\n");
8632                 return;
8633         }
8634
8635         fb = &intel_fb->base;
8636
8637         fb->dev = dev;
8638
8639         val = I915_READ(PLANE_CTL(pipe, plane_id));
8640
8641         if (INTEL_GEN(dev_priv) >= 11)
8642                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8643         else
8644                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8645
8646         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8647                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8648                 alpha &= PLANE_COLOR_ALPHA_MASK;
8649         } else {
8650                 alpha = val & PLANE_CTL_ALPHA_MASK;
8651         }
8652
8653         fourcc = skl_format_to_fourcc(pixel_format,
8654                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8655         fb->format = drm_format_info(fourcc);
8656
8657         tiling = val & PLANE_CTL_TILED_MASK;
8658         switch (tiling) {
8659         case PLANE_CTL_TILED_LINEAR:
8660                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8661                 break;
8662         case PLANE_CTL_TILED_X:
8663                 plane_config->tiling = I915_TILING_X;
8664                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8665                 break;
8666         case PLANE_CTL_TILED_Y:
8667                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8668                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8669                 else
8670                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8671                 break;
8672         case PLANE_CTL_TILED_YF:
8673                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8674                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8675                 else
8676                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8677                 break;
8678         default:
8679                 MISSING_CASE(tiling);
8680                 goto error;
8681         }
8682
8683         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8684         plane_config->base = base;
8685
8686         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8687
8688         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8689         fb->height = ((val >> 16) & 0xfff) + 1;
8690         fb->width = ((val >> 0) & 0x1fff) + 1;
8691
8692         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8693         stride_mult = intel_fb_stride_alignment(fb, 0);
8694         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8695
8696         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8697
8698         plane_config->size = fb->pitches[0] * aligned_height;
8699
8700         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8701                       crtc->base.name, plane->base.name, fb->width, fb->height,
8702                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8703                       plane_config->size);
8704
8705         plane_config->fb = intel_fb;
8706         return;
8707
8708 error:
8709         kfree(intel_fb);
8710 }
8711
8712 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8713                                      struct intel_crtc_state *pipe_config)
8714 {
8715         struct drm_device *dev = crtc->base.dev;
8716         struct drm_i915_private *dev_priv = to_i915(dev);
8717         uint32_t tmp;
8718
8719         tmp = I915_READ(PF_CTL(crtc->pipe));
8720
8721         if (tmp & PF_ENABLE) {
8722                 pipe_config->pch_pfit.enabled = true;
8723                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8724                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8725
8726                 /* We currently do not free assignements of panel fitters on
8727                  * ivb/hsw (since we don't use the higher upscaling modes which
8728                  * differentiates them) so just WARN about this case for now. */
8729                 if (IS_GEN7(dev_priv)) {
8730                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8731                                 PF_PIPE_SEL_IVB(crtc->pipe));
8732                 }
8733         }
8734 }
8735
8736 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8737                                      struct intel_crtc_state *pipe_config)
8738 {
8739         struct drm_device *dev = crtc->base.dev;
8740         struct drm_i915_private *dev_priv = to_i915(dev);
8741         enum intel_display_power_domain power_domain;
8742         uint32_t tmp;
8743         bool ret;
8744
8745         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8746         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8747                 return false;
8748
8749         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8750         pipe_config->shared_dpll = NULL;
8751
8752         ret = false;
8753         tmp = I915_READ(PIPECONF(crtc->pipe));
8754         if (!(tmp & PIPECONF_ENABLE))
8755                 goto out;
8756
8757         switch (tmp & PIPECONF_BPC_MASK) {
8758         case PIPECONF_6BPC:
8759                 pipe_config->pipe_bpp = 18;
8760                 break;
8761         case PIPECONF_8BPC:
8762                 pipe_config->pipe_bpp = 24;
8763                 break;
8764         case PIPECONF_10BPC:
8765                 pipe_config->pipe_bpp = 30;
8766                 break;
8767         case PIPECONF_12BPC:
8768                 pipe_config->pipe_bpp = 36;
8769                 break;
8770         default:
8771                 break;
8772         }
8773
8774         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8775                 pipe_config->limited_color_range = true;
8776
8777         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8778                 struct intel_shared_dpll *pll;
8779                 enum intel_dpll_id pll_id;
8780
8781                 pipe_config->has_pch_encoder = true;
8782
8783                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8784                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8785                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8786
8787                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8788
8789                 if (HAS_PCH_IBX(dev_priv)) {
8790                         /*
8791                          * The pipe->pch transcoder and pch transcoder->pll
8792                          * mapping is fixed.
8793                          */
8794                         pll_id = (enum intel_dpll_id) crtc->pipe;
8795                 } else {
8796                         tmp = I915_READ(PCH_DPLL_SEL);
8797                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8798                                 pll_id = DPLL_ID_PCH_PLL_B;
8799                         else
8800                                 pll_id= DPLL_ID_PCH_PLL_A;
8801                 }
8802
8803                 pipe_config->shared_dpll =
8804                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8805                 pll = pipe_config->shared_dpll;
8806
8807                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
8808                                                 &pipe_config->dpll_hw_state));
8809
8810                 tmp = pipe_config->dpll_hw_state.dpll;
8811                 pipe_config->pixel_multiplier =
8812                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8813                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8814
8815                 ironlake_pch_clock_get(crtc, pipe_config);
8816         } else {
8817                 pipe_config->pixel_multiplier = 1;
8818         }
8819
8820         intel_get_pipe_timings(crtc, pipe_config);
8821         intel_get_pipe_src_size(crtc, pipe_config);
8822
8823         ironlake_get_pfit_config(crtc, pipe_config);
8824
8825         ret = true;
8826
8827 out:
8828         intel_display_power_put(dev_priv, power_domain);
8829
8830         return ret;
8831 }
8832
8833 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8834 {
8835         struct drm_device *dev = &dev_priv->drm;
8836         struct intel_crtc *crtc;
8837
8838         for_each_intel_crtc(dev, crtc)
8839                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8840                      pipe_name(crtc->pipe));
8841
8842         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8843                         "Display power well on\n");
8844         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8845         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8846         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8847         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8848         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8849              "CPU PWM1 enabled\n");
8850         if (IS_HASWELL(dev_priv))
8851                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8852                      "CPU PWM2 enabled\n");
8853         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8854              "PCH PWM1 enabled\n");
8855         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8856              "Utility pin enabled\n");
8857         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8858
8859         /*
8860          * In theory we can still leave IRQs enabled, as long as only the HPD
8861          * interrupts remain enabled. We used to check for that, but since it's
8862          * gen-specific and since we only disable LCPLL after we fully disable
8863          * the interrupts, the check below should be enough.
8864          */
8865         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8866 }
8867
8868 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8869 {
8870         if (IS_HASWELL(dev_priv))
8871                 return I915_READ(D_COMP_HSW);
8872         else
8873                 return I915_READ(D_COMP_BDW);
8874 }
8875
8876 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8877 {
8878         if (IS_HASWELL(dev_priv)) {
8879                 mutex_lock(&dev_priv->pcu_lock);
8880                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8881                                             val))
8882                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8883                 mutex_unlock(&dev_priv->pcu_lock);
8884         } else {
8885                 I915_WRITE(D_COMP_BDW, val);
8886                 POSTING_READ(D_COMP_BDW);
8887         }
8888 }
8889
8890 /*
8891  * This function implements pieces of two sequences from BSpec:
8892  * - Sequence for display software to disable LCPLL
8893  * - Sequence for display software to allow package C8+
8894  * The steps implemented here are just the steps that actually touch the LCPLL
8895  * register. Callers should take care of disabling all the display engine
8896  * functions, doing the mode unset, fixing interrupts, etc.
8897  */
8898 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8899                               bool switch_to_fclk, bool allow_power_down)
8900 {
8901         uint32_t val;
8902
8903         assert_can_disable_lcpll(dev_priv);
8904
8905         val = I915_READ(LCPLL_CTL);
8906
8907         if (switch_to_fclk) {
8908                 val |= LCPLL_CD_SOURCE_FCLK;
8909                 I915_WRITE(LCPLL_CTL, val);
8910
8911                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8912                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8913                         DRM_ERROR("Switching to FCLK failed\n");
8914
8915                 val = I915_READ(LCPLL_CTL);
8916         }
8917
8918         val |= LCPLL_PLL_DISABLE;
8919         I915_WRITE(LCPLL_CTL, val);
8920         POSTING_READ(LCPLL_CTL);
8921
8922         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8923                 DRM_ERROR("LCPLL still locked\n");
8924
8925         val = hsw_read_dcomp(dev_priv);
8926         val |= D_COMP_COMP_DISABLE;
8927         hsw_write_dcomp(dev_priv, val);
8928         ndelay(100);
8929
8930         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8931                      1))
8932                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8933
8934         if (allow_power_down) {
8935                 val = I915_READ(LCPLL_CTL);
8936                 val |= LCPLL_POWER_DOWN_ALLOW;
8937                 I915_WRITE(LCPLL_CTL, val);
8938                 POSTING_READ(LCPLL_CTL);
8939         }
8940 }
8941
8942 /*
8943  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8944  * source.
8945  */
8946 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8947 {
8948         uint32_t val;
8949
8950         val = I915_READ(LCPLL_CTL);
8951
8952         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8953                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8954                 return;
8955
8956         /*
8957          * Make sure we're not on PC8 state before disabling PC8, otherwise
8958          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8959          */
8960         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8961
8962         if (val & LCPLL_POWER_DOWN_ALLOW) {
8963                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8964                 I915_WRITE(LCPLL_CTL, val);
8965                 POSTING_READ(LCPLL_CTL);
8966         }
8967
8968         val = hsw_read_dcomp(dev_priv);
8969         val |= D_COMP_COMP_FORCE;
8970         val &= ~D_COMP_COMP_DISABLE;
8971         hsw_write_dcomp(dev_priv, val);
8972
8973         val = I915_READ(LCPLL_CTL);
8974         val &= ~LCPLL_PLL_DISABLE;
8975         I915_WRITE(LCPLL_CTL, val);
8976
8977         if (intel_wait_for_register(dev_priv,
8978                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8979                                     5))
8980                 DRM_ERROR("LCPLL not locked yet\n");
8981
8982         if (val & LCPLL_CD_SOURCE_FCLK) {
8983                 val = I915_READ(LCPLL_CTL);
8984                 val &= ~LCPLL_CD_SOURCE_FCLK;
8985                 I915_WRITE(LCPLL_CTL, val);
8986
8987                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8988                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8989                         DRM_ERROR("Switching back to LCPLL failed\n");
8990         }
8991
8992         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8993
8994         intel_update_cdclk(dev_priv);
8995         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
8996 }
8997
8998 /*
8999  * Package states C8 and deeper are really deep PC states that can only be
9000  * reached when all the devices on the system allow it, so even if the graphics
9001  * device allows PC8+, it doesn't mean the system will actually get to these
9002  * states. Our driver only allows PC8+ when going into runtime PM.
9003  *
9004  * The requirements for PC8+ are that all the outputs are disabled, the power
9005  * well is disabled and most interrupts are disabled, and these are also
9006  * requirements for runtime PM. When these conditions are met, we manually do
9007  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9008  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9009  * hang the machine.
9010  *
9011  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9012  * the state of some registers, so when we come back from PC8+ we need to
9013  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9014  * need to take care of the registers kept by RC6. Notice that this happens even
9015  * if we don't put the device in PCI D3 state (which is what currently happens
9016  * because of the runtime PM support).
9017  *
9018  * For more, read "Display Sequences for Package C8" on the hardware
9019  * documentation.
9020  */
9021 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9022 {
9023         uint32_t val;
9024
9025         DRM_DEBUG_KMS("Enabling package C8+\n");
9026
9027         if (HAS_PCH_LPT_LP(dev_priv)) {
9028                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9029                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9030                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9031         }
9032
9033         lpt_disable_clkout_dp(dev_priv);
9034         hsw_disable_lcpll(dev_priv, true, true);
9035 }
9036
9037 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9038 {
9039         uint32_t val;
9040
9041         DRM_DEBUG_KMS("Disabling package C8+\n");
9042
9043         hsw_restore_lcpll(dev_priv);
9044         lpt_init_pch_refclk(dev_priv);
9045
9046         if (HAS_PCH_LPT_LP(dev_priv)) {
9047                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9048                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9049                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9050         }
9051 }
9052
9053 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9054                                       struct intel_crtc_state *crtc_state)
9055 {
9056         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9057                 struct intel_encoder *encoder =
9058                         intel_ddi_get_crtc_new_encoder(crtc_state);
9059
9060                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9061                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9062                                          pipe_name(crtc->pipe));
9063                         return -EINVAL;
9064                 }
9065         }
9066
9067         return 0;
9068 }
9069
9070 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9071                                    enum port port,
9072                                    struct intel_crtc_state *pipe_config)
9073 {
9074         enum intel_dpll_id id;
9075         u32 temp;
9076
9077         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9078         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9079
9080         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9081                 return;
9082
9083         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9084 }
9085
9086 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9087                                 enum port port,
9088                                 struct intel_crtc_state *pipe_config)
9089 {
9090         enum intel_dpll_id id;
9091
9092         switch (port) {
9093         case PORT_A:
9094                 id = DPLL_ID_SKL_DPLL0;
9095                 break;
9096         case PORT_B:
9097                 id = DPLL_ID_SKL_DPLL1;
9098                 break;
9099         case PORT_C:
9100                 id = DPLL_ID_SKL_DPLL2;
9101                 break;
9102         default:
9103                 DRM_ERROR("Incorrect port type\n");
9104                 return;
9105         }
9106
9107         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9108 }
9109
9110 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9111                                 enum port port,
9112                                 struct intel_crtc_state *pipe_config)
9113 {
9114         enum intel_dpll_id id;
9115         u32 temp;
9116
9117         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9118         id = temp >> (port * 3 + 1);
9119
9120         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9121                 return;
9122
9123         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9124 }
9125
9126 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9127                                 enum port port,
9128                                 struct intel_crtc_state *pipe_config)
9129 {
9130         enum intel_dpll_id id;
9131         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9132
9133         switch (ddi_pll_sel) {
9134         case PORT_CLK_SEL_WRPLL1:
9135                 id = DPLL_ID_WRPLL1;
9136                 break;
9137         case PORT_CLK_SEL_WRPLL2:
9138                 id = DPLL_ID_WRPLL2;
9139                 break;
9140         case PORT_CLK_SEL_SPLL:
9141                 id = DPLL_ID_SPLL;
9142                 break;
9143         case PORT_CLK_SEL_LCPLL_810:
9144                 id = DPLL_ID_LCPLL_810;
9145                 break;
9146         case PORT_CLK_SEL_LCPLL_1350:
9147                 id = DPLL_ID_LCPLL_1350;
9148                 break;
9149         case PORT_CLK_SEL_LCPLL_2700:
9150                 id = DPLL_ID_LCPLL_2700;
9151                 break;
9152         default:
9153                 MISSING_CASE(ddi_pll_sel);
9154                 /* fall through */
9155         case PORT_CLK_SEL_NONE:
9156                 return;
9157         }
9158
9159         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9160 }
9161
9162 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9163                                      struct intel_crtc_state *pipe_config,
9164                                      u64 *power_domain_mask)
9165 {
9166         struct drm_device *dev = crtc->base.dev;
9167         struct drm_i915_private *dev_priv = to_i915(dev);
9168         enum intel_display_power_domain power_domain;
9169         u32 tmp;
9170
9171         /*
9172          * The pipe->transcoder mapping is fixed with the exception of the eDP
9173          * transcoder handled below.
9174          */
9175         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9176
9177         /*
9178          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9179          * consistency and less surprising code; it's in always on power).
9180          */
9181         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9182         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9183                 enum pipe trans_edp_pipe;
9184                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9185                 default:
9186                         WARN(1, "unknown pipe linked to edp transcoder\n");
9187                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9188                 case TRANS_DDI_EDP_INPUT_A_ON:
9189                         trans_edp_pipe = PIPE_A;
9190                         break;
9191                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9192                         trans_edp_pipe = PIPE_B;
9193                         break;
9194                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9195                         trans_edp_pipe = PIPE_C;
9196                         break;
9197                 }
9198
9199                 if (trans_edp_pipe == crtc->pipe)
9200                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9201         }
9202
9203         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9204         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9205                 return false;
9206         *power_domain_mask |= BIT_ULL(power_domain);
9207
9208         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9209
9210         return tmp & PIPECONF_ENABLE;
9211 }
9212
9213 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9214                                          struct intel_crtc_state *pipe_config,
9215                                          u64 *power_domain_mask)
9216 {
9217         struct drm_device *dev = crtc->base.dev;
9218         struct drm_i915_private *dev_priv = to_i915(dev);
9219         enum intel_display_power_domain power_domain;
9220         enum port port;
9221         enum transcoder cpu_transcoder;
9222         u32 tmp;
9223
9224         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9225                 if (port == PORT_A)
9226                         cpu_transcoder = TRANSCODER_DSI_A;
9227                 else
9228                         cpu_transcoder = TRANSCODER_DSI_C;
9229
9230                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9231                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9232                         continue;
9233                 *power_domain_mask |= BIT_ULL(power_domain);
9234
9235                 /*
9236                  * The PLL needs to be enabled with a valid divider
9237                  * configuration, otherwise accessing DSI registers will hang
9238                  * the machine. See BSpec North Display Engine
9239                  * registers/MIPI[BXT]. We can break out here early, since we
9240                  * need the same DSI PLL to be enabled for both DSI ports.
9241                  */
9242                 if (!intel_dsi_pll_is_enabled(dev_priv))
9243                         break;
9244
9245                 /* XXX: this works for video mode only */
9246                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9247                 if (!(tmp & DPI_ENABLE))
9248                         continue;
9249
9250                 tmp = I915_READ(MIPI_CTRL(port));
9251                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9252                         continue;
9253
9254                 pipe_config->cpu_transcoder = cpu_transcoder;
9255                 break;
9256         }
9257
9258         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9259 }
9260
9261 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9262                                        struct intel_crtc_state *pipe_config)
9263 {
9264         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9265         struct intel_shared_dpll *pll;
9266         enum port port;
9267         uint32_t tmp;
9268
9269         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9270
9271         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9272
9273         if (IS_CANNONLAKE(dev_priv))
9274                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9275         else if (IS_GEN9_BC(dev_priv))
9276                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9277         else if (IS_GEN9_LP(dev_priv))
9278                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9279         else
9280                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9281
9282         pll = pipe_config->shared_dpll;
9283         if (pll) {
9284                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9285                                                 &pipe_config->dpll_hw_state));
9286         }
9287
9288         /*
9289          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9290          * DDI E. So just check whether this pipe is wired to DDI E and whether
9291          * the PCH transcoder is on.
9292          */
9293         if (INTEL_GEN(dev_priv) < 9 &&
9294             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9295                 pipe_config->has_pch_encoder = true;
9296
9297                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9298                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9299                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9300
9301                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9302         }
9303 }
9304
9305 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9306                                     struct intel_crtc_state *pipe_config)
9307 {
9308         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9309         enum intel_display_power_domain power_domain;
9310         u64 power_domain_mask;
9311         bool active;
9312
9313         intel_crtc_init_scalers(crtc, pipe_config);
9314
9315         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9316         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9317                 return false;
9318         power_domain_mask = BIT_ULL(power_domain);
9319
9320         pipe_config->shared_dpll = NULL;
9321
9322         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9323
9324         if (IS_GEN9_LP(dev_priv) &&
9325             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9326                 WARN_ON(active);
9327                 active = true;
9328         }
9329
9330         if (!active)
9331                 goto out;
9332
9333         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9334                 haswell_get_ddi_port_state(crtc, pipe_config);
9335                 intel_get_pipe_timings(crtc, pipe_config);
9336         }
9337
9338         intel_get_pipe_src_size(crtc, pipe_config);
9339
9340         pipe_config->gamma_mode =
9341                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9342
9343         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9344                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9345                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9346
9347                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9348                         bool blend_mode_420 = tmp &
9349                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9350
9351                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9352                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9353                             pipe_config->ycbcr420 != blend_mode_420)
9354                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9355                 } else if (clrspace_yuv) {
9356                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9357                 }
9358         }
9359
9360         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9361         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9362                 power_domain_mask |= BIT_ULL(power_domain);
9363                 if (INTEL_GEN(dev_priv) >= 9)
9364                         skylake_get_pfit_config(crtc, pipe_config);
9365                 else
9366                         ironlake_get_pfit_config(crtc, pipe_config);
9367         }
9368
9369         if (hsw_crtc_supports_ips(crtc)) {
9370                 if (IS_HASWELL(dev_priv))
9371                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9372                 else {
9373                         /*
9374                          * We cannot readout IPS state on broadwell, set to
9375                          * true so we can set it to a defined state on first
9376                          * commit.
9377                          */
9378                         pipe_config->ips_enabled = true;
9379                 }
9380         }
9381
9382         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9383             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9384                 pipe_config->pixel_multiplier =
9385                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9386         } else {
9387                 pipe_config->pixel_multiplier = 1;
9388         }
9389
9390 out:
9391         for_each_power_domain(power_domain, power_domain_mask)
9392                 intel_display_power_put(dev_priv, power_domain);
9393
9394         return active;
9395 }
9396
9397 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9398 {
9399         struct drm_i915_private *dev_priv =
9400                 to_i915(plane_state->base.plane->dev);
9401         const struct drm_framebuffer *fb = plane_state->base.fb;
9402         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9403         u32 base;
9404
9405         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9406                 base = obj->phys_handle->busaddr;
9407         else
9408                 base = intel_plane_ggtt_offset(plane_state);
9409
9410         base += plane_state->main.offset;
9411
9412         /* ILK+ do this automagically */
9413         if (HAS_GMCH_DISPLAY(dev_priv) &&
9414             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9415                 base += (plane_state->base.crtc_h *
9416                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9417
9418         return base;
9419 }
9420
9421 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9422 {
9423         int x = plane_state->base.crtc_x;
9424         int y = plane_state->base.crtc_y;
9425         u32 pos = 0;
9426
9427         if (x < 0) {
9428                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9429                 x = -x;
9430         }
9431         pos |= x << CURSOR_X_SHIFT;
9432
9433         if (y < 0) {
9434                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9435                 y = -y;
9436         }
9437         pos |= y << CURSOR_Y_SHIFT;
9438
9439         return pos;
9440 }
9441
9442 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9443 {
9444         const struct drm_mode_config *config =
9445                 &plane_state->base.plane->dev->mode_config;
9446         int width = plane_state->base.crtc_w;
9447         int height = plane_state->base.crtc_h;
9448
9449         return width > 0 && width <= config->cursor_width &&
9450                 height > 0 && height <= config->cursor_height;
9451 }
9452
9453 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9454                               struct intel_plane_state *plane_state)
9455 {
9456         const struct drm_framebuffer *fb = plane_state->base.fb;
9457         int src_x, src_y;
9458         u32 offset;
9459         int ret;
9460
9461         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9462                                                   &crtc_state->base,
9463                                                   DRM_PLANE_HELPER_NO_SCALING,
9464                                                   DRM_PLANE_HELPER_NO_SCALING,
9465                                                   true, true);
9466         if (ret)
9467                 return ret;
9468
9469         if (!fb)
9470                 return 0;
9471
9472         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9473                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9474                 return -EINVAL;
9475         }
9476
9477         src_x = plane_state->base.src_x >> 16;
9478         src_y = plane_state->base.src_y >> 16;
9479
9480         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9481         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9482
9483         if (src_x != 0 || src_y != 0) {
9484                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9485                 return -EINVAL;
9486         }
9487
9488         plane_state->main.offset = offset;
9489
9490         return 0;
9491 }
9492
9493 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9494                            const struct intel_plane_state *plane_state)
9495 {
9496         const struct drm_framebuffer *fb = plane_state->base.fb;
9497
9498         return CURSOR_ENABLE |
9499                 CURSOR_GAMMA_ENABLE |
9500                 CURSOR_FORMAT_ARGB |
9501                 CURSOR_STRIDE(fb->pitches[0]);
9502 }
9503
9504 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9505 {
9506         int width = plane_state->base.crtc_w;
9507
9508         /*
9509          * 845g/865g are only limited by the width of their cursors,
9510          * the height is arbitrary up to the precision of the register.
9511          */
9512         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9513 }
9514
9515 static int i845_check_cursor(struct intel_plane *plane,
9516                              struct intel_crtc_state *crtc_state,
9517                              struct intel_plane_state *plane_state)
9518 {
9519         const struct drm_framebuffer *fb = plane_state->base.fb;
9520         int ret;
9521
9522         ret = intel_check_cursor(crtc_state, plane_state);
9523         if (ret)
9524                 return ret;
9525
9526         /* if we want to turn off the cursor ignore width and height */
9527         if (!fb)
9528                 return 0;
9529
9530         /* Check for which cursor types we support */
9531         if (!i845_cursor_size_ok(plane_state)) {
9532                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9533                           plane_state->base.crtc_w,
9534                           plane_state->base.crtc_h);
9535                 return -EINVAL;
9536         }
9537
9538         switch (fb->pitches[0]) {
9539         case 256:
9540         case 512:
9541         case 1024:
9542         case 2048:
9543                 break;
9544         default:
9545                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9546                               fb->pitches[0]);
9547                 return -EINVAL;
9548         }
9549
9550         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9551
9552         return 0;
9553 }
9554
9555 static void i845_update_cursor(struct intel_plane *plane,
9556                                const struct intel_crtc_state *crtc_state,
9557                                const struct intel_plane_state *plane_state)
9558 {
9559         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9560         u32 cntl = 0, base = 0, pos = 0, size = 0;
9561         unsigned long irqflags;
9562
9563         if (plane_state && plane_state->base.visible) {
9564                 unsigned int width = plane_state->base.crtc_w;
9565                 unsigned int height = plane_state->base.crtc_h;
9566
9567                 cntl = plane_state->ctl;
9568                 size = (height << 12) | width;
9569
9570                 base = intel_cursor_base(plane_state);
9571                 pos = intel_cursor_position(plane_state);
9572         }
9573
9574         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9575
9576         /* On these chipsets we can only modify the base/size/stride
9577          * whilst the cursor is disabled.
9578          */
9579         if (plane->cursor.base != base ||
9580             plane->cursor.size != size ||
9581             plane->cursor.cntl != cntl) {
9582                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9583                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9584                 I915_WRITE_FW(CURSIZE, size);
9585                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9586                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9587
9588                 plane->cursor.base = base;
9589                 plane->cursor.size = size;
9590                 plane->cursor.cntl = cntl;
9591         } else {
9592                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9593         }
9594
9595         POSTING_READ_FW(CURCNTR(PIPE_A));
9596
9597         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9598 }
9599
9600 static void i845_disable_cursor(struct intel_plane *plane,
9601                                 struct intel_crtc *crtc)
9602 {
9603         i845_update_cursor(plane, NULL, NULL);
9604 }
9605
9606 static bool i845_cursor_get_hw_state(struct intel_plane *plane)
9607 {
9608         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9609         enum intel_display_power_domain power_domain;
9610         bool ret;
9611
9612         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9613         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9614                 return false;
9615
9616         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9617
9618         intel_display_power_put(dev_priv, power_domain);
9619
9620         return ret;
9621 }
9622
9623 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9624                            const struct intel_plane_state *plane_state)
9625 {
9626         struct drm_i915_private *dev_priv =
9627                 to_i915(plane_state->base.plane->dev);
9628         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9629         u32 cntl;
9630
9631         cntl = MCURSOR_GAMMA_ENABLE;
9632
9633         if (HAS_DDI(dev_priv))
9634                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9635
9636         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9637                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9638
9639         switch (plane_state->base.crtc_w) {
9640         case 64:
9641                 cntl |= CURSOR_MODE_64_ARGB_AX;
9642                 break;
9643         case 128:
9644                 cntl |= CURSOR_MODE_128_ARGB_AX;
9645                 break;
9646         case 256:
9647                 cntl |= CURSOR_MODE_256_ARGB_AX;
9648                 break;
9649         default:
9650                 MISSING_CASE(plane_state->base.crtc_w);
9651                 return 0;
9652         }
9653
9654         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9655                 cntl |= CURSOR_ROTATE_180;
9656
9657         return cntl;
9658 }
9659
9660 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9661 {
9662         struct drm_i915_private *dev_priv =
9663                 to_i915(plane_state->base.plane->dev);
9664         int width = plane_state->base.crtc_w;
9665         int height = plane_state->base.crtc_h;
9666
9667         if (!intel_cursor_size_ok(plane_state))
9668                 return false;
9669
9670         /* Cursor width is limited to a few power-of-two sizes */
9671         switch (width) {
9672         case 256:
9673         case 128:
9674         case 64:
9675                 break;
9676         default:
9677                 return false;
9678         }
9679
9680         /*
9681          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9682          * height from 8 lines up to the cursor width, when the
9683          * cursor is not rotated. Everything else requires square
9684          * cursors.
9685          */
9686         if (HAS_CUR_FBC(dev_priv) &&
9687             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9688                 if (height < 8 || height > width)
9689                         return false;
9690         } else {
9691                 if (height != width)
9692                         return false;
9693         }
9694
9695         return true;
9696 }
9697
9698 static int i9xx_check_cursor(struct intel_plane *plane,
9699                              struct intel_crtc_state *crtc_state,
9700                              struct intel_plane_state *plane_state)
9701 {
9702         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9703         const struct drm_framebuffer *fb = plane_state->base.fb;
9704         enum pipe pipe = plane->pipe;
9705         int ret;
9706
9707         ret = intel_check_cursor(crtc_state, plane_state);
9708         if (ret)
9709                 return ret;
9710
9711         /* if we want to turn off the cursor ignore width and height */
9712         if (!fb)
9713                 return 0;
9714
9715         /* Check for which cursor types we support */
9716         if (!i9xx_cursor_size_ok(plane_state)) {
9717                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9718                           plane_state->base.crtc_w,
9719                           plane_state->base.crtc_h);
9720                 return -EINVAL;
9721         }
9722
9723         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9724                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9725                               fb->pitches[0], plane_state->base.crtc_w);
9726                 return -EINVAL;
9727         }
9728
9729         /*
9730          * There's something wrong with the cursor on CHV pipe C.
9731          * If it straddles the left edge of the screen then
9732          * moving it away from the edge or disabling it often
9733          * results in a pipe underrun, and often that can lead to
9734          * dead pipe (constant underrun reported, and it scans
9735          * out just a solid color). To recover from that, the
9736          * display power well must be turned off and on again.
9737          * Refuse the put the cursor into that compromised position.
9738          */
9739         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9740             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9741                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9742                 return -EINVAL;
9743         }
9744
9745         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9746
9747         return 0;
9748 }
9749
9750 static void i9xx_update_cursor(struct intel_plane *plane,
9751                                const struct intel_crtc_state *crtc_state,
9752                                const struct intel_plane_state *plane_state)
9753 {
9754         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9755         enum pipe pipe = plane->pipe;
9756         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9757         unsigned long irqflags;
9758
9759         if (plane_state && plane_state->base.visible) {
9760                 cntl = plane_state->ctl;
9761
9762                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9763                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9764
9765                 base = intel_cursor_base(plane_state);
9766                 pos = intel_cursor_position(plane_state);
9767         }
9768
9769         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9770
9771         /*
9772          * On some platforms writing CURCNTR first will also
9773          * cause CURPOS to be armed by the CURBASE write.
9774          * Without the CURCNTR write the CURPOS write would
9775          * arm itself. Thus we always start the full update
9776          * with a CURCNTR write.
9777          *
9778          * On other platforms CURPOS always requires the
9779          * CURBASE write to arm the update. Additonally
9780          * a write to any of the cursor register will cancel
9781          * an already armed cursor update. Thus leaving out
9782          * the CURBASE write after CURPOS could lead to a
9783          * cursor that doesn't appear to move, or even change
9784          * shape. Thus we always write CURBASE.
9785          *
9786          * CURCNTR and CUR_FBC_CTL are always
9787          * armed by the CURBASE write only.
9788          */
9789         if (plane->cursor.base != base ||
9790             plane->cursor.size != fbc_ctl ||
9791             plane->cursor.cntl != cntl) {
9792                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9793                 if (HAS_CUR_FBC(dev_priv))
9794                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9795                 I915_WRITE_FW(CURPOS(pipe), pos);
9796                 I915_WRITE_FW(CURBASE(pipe), base);
9797
9798                 plane->cursor.base = base;
9799                 plane->cursor.size = fbc_ctl;
9800                 plane->cursor.cntl = cntl;
9801         } else {
9802                 I915_WRITE_FW(CURPOS(pipe), pos);
9803                 I915_WRITE_FW(CURBASE(pipe), base);
9804         }
9805
9806         POSTING_READ_FW(CURBASE(pipe));
9807
9808         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9809 }
9810
9811 static void i9xx_disable_cursor(struct intel_plane *plane,
9812                                 struct intel_crtc *crtc)
9813 {
9814         i9xx_update_cursor(plane, NULL, NULL);
9815 }
9816
9817 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane)
9818 {
9819         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9820         enum intel_display_power_domain power_domain;
9821         enum pipe pipe = plane->pipe;
9822         bool ret;
9823
9824         /*
9825          * Not 100% correct for planes that can move between pipes,
9826          * but that's only the case for gen2-3 which don't have any
9827          * display power wells.
9828          */
9829         power_domain = POWER_DOMAIN_PIPE(pipe);
9830         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9831                 return false;
9832
9833         ret = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
9834
9835         intel_display_power_put(dev_priv, power_domain);
9836
9837         return ret;
9838 }
9839
9840 /* VESA 640x480x72Hz mode to set on the pipe */
9841 static const struct drm_display_mode load_detect_mode = {
9842         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9843                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9844 };
9845
9846 struct drm_framebuffer *
9847 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9848                          struct drm_mode_fb_cmd2 *mode_cmd)
9849 {
9850         struct intel_framebuffer *intel_fb;
9851         int ret;
9852
9853         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9854         if (!intel_fb)
9855                 return ERR_PTR(-ENOMEM);
9856
9857         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9858         if (ret)
9859                 goto err;
9860
9861         return &intel_fb->base;
9862
9863 err:
9864         kfree(intel_fb);
9865         return ERR_PTR(ret);
9866 }
9867
9868 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
9869                                         struct drm_crtc *crtc)
9870 {
9871         struct drm_plane *plane;
9872         struct drm_plane_state *plane_state;
9873         int ret, i;
9874
9875         ret = drm_atomic_add_affected_planes(state, crtc);
9876         if (ret)
9877                 return ret;
9878
9879         for_each_new_plane_in_state(state, plane, plane_state, i) {
9880                 if (plane_state->crtc != crtc)
9881                         continue;
9882
9883                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
9884                 if (ret)
9885                         return ret;
9886
9887                 drm_atomic_set_fb_for_plane(plane_state, NULL);
9888         }
9889
9890         return 0;
9891 }
9892
9893 int intel_get_load_detect_pipe(struct drm_connector *connector,
9894                                const struct drm_display_mode *mode,
9895                                struct intel_load_detect_pipe *old,
9896                                struct drm_modeset_acquire_ctx *ctx)
9897 {
9898         struct intel_crtc *intel_crtc;
9899         struct intel_encoder *intel_encoder =
9900                 intel_attached_encoder(connector);
9901         struct drm_crtc *possible_crtc;
9902         struct drm_encoder *encoder = &intel_encoder->base;
9903         struct drm_crtc *crtc = NULL;
9904         struct drm_device *dev = encoder->dev;
9905         struct drm_i915_private *dev_priv = to_i915(dev);
9906         struct drm_mode_config *config = &dev->mode_config;
9907         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9908         struct drm_connector_state *connector_state;
9909         struct intel_crtc_state *crtc_state;
9910         int ret, i = -1;
9911
9912         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9913                       connector->base.id, connector->name,
9914                       encoder->base.id, encoder->name);
9915
9916         old->restore_state = NULL;
9917
9918         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9919
9920         /*
9921          * Algorithm gets a little messy:
9922          *
9923          *   - if the connector already has an assigned crtc, use it (but make
9924          *     sure it's on first)
9925          *
9926          *   - try to find the first unused crtc that can drive this connector,
9927          *     and use that if we find one
9928          */
9929
9930         /* See if we already have a CRTC for this connector */
9931         if (connector->state->crtc) {
9932                 crtc = connector->state->crtc;
9933
9934                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9935                 if (ret)
9936                         goto fail;
9937
9938                 /* Make sure the crtc and connector are running */
9939                 goto found;
9940         }
9941
9942         /* Find an unused one (if possible) */
9943         for_each_crtc(dev, possible_crtc) {
9944                 i++;
9945                 if (!(encoder->possible_crtcs & (1 << i)))
9946                         continue;
9947
9948                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9949                 if (ret)
9950                         goto fail;
9951
9952                 if (possible_crtc->state->enable) {
9953                         drm_modeset_unlock(&possible_crtc->mutex);
9954                         continue;
9955                 }
9956
9957                 crtc = possible_crtc;
9958                 break;
9959         }
9960
9961         /*
9962          * If we didn't find an unused CRTC, don't use any.
9963          */
9964         if (!crtc) {
9965                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9966                 ret = -ENODEV;
9967                 goto fail;
9968         }
9969
9970 found:
9971         intel_crtc = to_intel_crtc(crtc);
9972
9973         state = drm_atomic_state_alloc(dev);
9974         restore_state = drm_atomic_state_alloc(dev);
9975         if (!state || !restore_state) {
9976                 ret = -ENOMEM;
9977                 goto fail;
9978         }
9979
9980         state->acquire_ctx = ctx;
9981         restore_state->acquire_ctx = ctx;
9982
9983         connector_state = drm_atomic_get_connector_state(state, connector);
9984         if (IS_ERR(connector_state)) {
9985                 ret = PTR_ERR(connector_state);
9986                 goto fail;
9987         }
9988
9989         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
9990         if (ret)
9991                 goto fail;
9992
9993         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9994         if (IS_ERR(crtc_state)) {
9995                 ret = PTR_ERR(crtc_state);
9996                 goto fail;
9997         }
9998
9999         crtc_state->base.active = crtc_state->base.enable = true;
10000
10001         if (!mode)
10002                 mode = &load_detect_mode;
10003
10004         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10005         if (ret)
10006                 goto fail;
10007
10008         ret = intel_modeset_disable_planes(state, crtc);
10009         if (ret)
10010                 goto fail;
10011
10012         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10013         if (!ret)
10014                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10015         if (ret) {
10016                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10017                 goto fail;
10018         }
10019
10020         ret = drm_atomic_commit(state);
10021         if (ret) {
10022                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10023                 goto fail;
10024         }
10025
10026         old->restore_state = restore_state;
10027         drm_atomic_state_put(state);
10028
10029         /* let the connector get through one full cycle before testing */
10030         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10031         return true;
10032
10033 fail:
10034         if (state) {
10035                 drm_atomic_state_put(state);
10036                 state = NULL;
10037         }
10038         if (restore_state) {
10039                 drm_atomic_state_put(restore_state);
10040                 restore_state = NULL;
10041         }
10042
10043         if (ret == -EDEADLK)
10044                 return ret;
10045
10046         return false;
10047 }
10048
10049 void intel_release_load_detect_pipe(struct drm_connector *connector,
10050                                     struct intel_load_detect_pipe *old,
10051                                     struct drm_modeset_acquire_ctx *ctx)
10052 {
10053         struct intel_encoder *intel_encoder =
10054                 intel_attached_encoder(connector);
10055         struct drm_encoder *encoder = &intel_encoder->base;
10056         struct drm_atomic_state *state = old->restore_state;
10057         int ret;
10058
10059         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10060                       connector->base.id, connector->name,
10061                       encoder->base.id, encoder->name);
10062
10063         if (!state)
10064                 return;
10065
10066         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10067         if (ret)
10068                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10069         drm_atomic_state_put(state);
10070 }
10071
10072 static int i9xx_pll_refclk(struct drm_device *dev,
10073                            const struct intel_crtc_state *pipe_config)
10074 {
10075         struct drm_i915_private *dev_priv = to_i915(dev);
10076         u32 dpll = pipe_config->dpll_hw_state.dpll;
10077
10078         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10079                 return dev_priv->vbt.lvds_ssc_freq;
10080         else if (HAS_PCH_SPLIT(dev_priv))
10081                 return 120000;
10082         else if (!IS_GEN2(dev_priv))
10083                 return 96000;
10084         else
10085                 return 48000;
10086 }
10087
10088 /* Returns the clock of the currently programmed mode of the given pipe. */
10089 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10090                                 struct intel_crtc_state *pipe_config)
10091 {
10092         struct drm_device *dev = crtc->base.dev;
10093         struct drm_i915_private *dev_priv = to_i915(dev);
10094         int pipe = pipe_config->cpu_transcoder;
10095         u32 dpll = pipe_config->dpll_hw_state.dpll;
10096         u32 fp;
10097         struct dpll clock;
10098         int port_clock;
10099         int refclk = i9xx_pll_refclk(dev, pipe_config);
10100
10101         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10102                 fp = pipe_config->dpll_hw_state.fp0;
10103         else
10104                 fp = pipe_config->dpll_hw_state.fp1;
10105
10106         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10107         if (IS_PINEVIEW(dev_priv)) {
10108                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10109                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10110         } else {
10111                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10112                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10113         }
10114
10115         if (!IS_GEN2(dev_priv)) {
10116                 if (IS_PINEVIEW(dev_priv))
10117                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10118                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10119                 else
10120                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10121                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10122
10123                 switch (dpll & DPLL_MODE_MASK) {
10124                 case DPLLB_MODE_DAC_SERIAL:
10125                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10126                                 5 : 10;
10127                         break;
10128                 case DPLLB_MODE_LVDS:
10129                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10130                                 7 : 14;
10131                         break;
10132                 default:
10133                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10134                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10135                         return;
10136                 }
10137
10138                 if (IS_PINEVIEW(dev_priv))
10139                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10140                 else
10141                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10142         } else {
10143                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10144                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10145
10146                 if (is_lvds) {
10147                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10148                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10149
10150                         if (lvds & LVDS_CLKB_POWER_UP)
10151                                 clock.p2 = 7;
10152                         else
10153                                 clock.p2 = 14;
10154                 } else {
10155                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10156                                 clock.p1 = 2;
10157                         else {
10158                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10159                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10160                         }
10161                         if (dpll & PLL_P2_DIVIDE_BY_4)
10162                                 clock.p2 = 4;
10163                         else
10164                                 clock.p2 = 2;
10165                 }
10166
10167                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10168         }
10169
10170         /*
10171          * This value includes pixel_multiplier. We will use
10172          * port_clock to compute adjusted_mode.crtc_clock in the
10173          * encoder's get_config() function.
10174          */
10175         pipe_config->port_clock = port_clock;
10176 }
10177
10178 int intel_dotclock_calculate(int link_freq,
10179                              const struct intel_link_m_n *m_n)
10180 {
10181         /*
10182          * The calculation for the data clock is:
10183          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10184          * But we want to avoid losing precison if possible, so:
10185          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10186          *
10187          * and the link clock is simpler:
10188          * link_clock = (m * link_clock) / n
10189          */
10190
10191         if (!m_n->link_n)
10192                 return 0;
10193
10194         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10195 }
10196
10197 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10198                                    struct intel_crtc_state *pipe_config)
10199 {
10200         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10201
10202         /* read out port_clock from the DPLL */
10203         i9xx_crtc_clock_get(crtc, pipe_config);
10204
10205         /*
10206          * In case there is an active pipe without active ports,
10207          * we may need some idea for the dotclock anyway.
10208          * Calculate one based on the FDI configuration.
10209          */
10210         pipe_config->base.adjusted_mode.crtc_clock =
10211                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10212                                          &pipe_config->fdi_m_n);
10213 }
10214
10215 /* Returns the currently programmed mode of the given encoder. */
10216 struct drm_display_mode *
10217 intel_encoder_current_mode(struct intel_encoder *encoder)
10218 {
10219         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10220         struct intel_crtc_state *crtc_state;
10221         struct drm_display_mode *mode;
10222         struct intel_crtc *crtc;
10223         enum pipe pipe;
10224
10225         if (!encoder->get_hw_state(encoder, &pipe))
10226                 return NULL;
10227
10228         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10229
10230         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10231         if (!mode)
10232                 return NULL;
10233
10234         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10235         if (!crtc_state) {
10236                 kfree(mode);
10237                 return NULL;
10238         }
10239
10240         crtc_state->base.crtc = &crtc->base;
10241
10242         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10243                 kfree(crtc_state);
10244                 kfree(mode);
10245                 return NULL;
10246         }
10247
10248         encoder->get_config(encoder, crtc_state);
10249
10250         intel_mode_from_pipe_config(mode, crtc_state);
10251
10252         kfree(crtc_state);
10253
10254         return mode;
10255 }
10256
10257 static void intel_crtc_destroy(struct drm_crtc *crtc)
10258 {
10259         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10260
10261         drm_crtc_cleanup(crtc);
10262         kfree(intel_crtc);
10263 }
10264
10265 /**
10266  * intel_wm_need_update - Check whether watermarks need updating
10267  * @plane: drm plane
10268  * @state: new plane state
10269  *
10270  * Check current plane state versus the new one to determine whether
10271  * watermarks need to be recalculated.
10272  *
10273  * Returns true or false.
10274  */
10275 static bool intel_wm_need_update(struct drm_plane *plane,
10276                                  struct drm_plane_state *state)
10277 {
10278         struct intel_plane_state *new = to_intel_plane_state(state);
10279         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10280
10281         /* Update watermarks on tiling or size changes. */
10282         if (new->base.visible != cur->base.visible)
10283                 return true;
10284
10285         if (!cur->base.fb || !new->base.fb)
10286                 return false;
10287
10288         if (cur->base.fb->modifier != new->base.fb->modifier ||
10289             cur->base.rotation != new->base.rotation ||
10290             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10291             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10292             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10293             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10294                 return true;
10295
10296         return false;
10297 }
10298
10299 static bool needs_scaling(const struct intel_plane_state *state)
10300 {
10301         int src_w = drm_rect_width(&state->base.src) >> 16;
10302         int src_h = drm_rect_height(&state->base.src) >> 16;
10303         int dst_w = drm_rect_width(&state->base.dst);
10304         int dst_h = drm_rect_height(&state->base.dst);
10305
10306         return (src_w != dst_w || src_h != dst_h);
10307 }
10308
10309 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10310                                     struct drm_crtc_state *crtc_state,
10311                                     const struct intel_plane_state *old_plane_state,
10312                                     struct drm_plane_state *plane_state)
10313 {
10314         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10315         struct drm_crtc *crtc = crtc_state->crtc;
10316         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10317         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10318         struct drm_device *dev = crtc->dev;
10319         struct drm_i915_private *dev_priv = to_i915(dev);
10320         bool mode_changed = needs_modeset(crtc_state);
10321         bool was_crtc_enabled = old_crtc_state->base.active;
10322         bool is_crtc_enabled = crtc_state->active;
10323         bool turn_off, turn_on, visible, was_visible;
10324         struct drm_framebuffer *fb = plane_state->fb;
10325         int ret;
10326
10327         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10328                 ret = skl_update_scaler_plane(
10329                         to_intel_crtc_state(crtc_state),
10330                         to_intel_plane_state(plane_state));
10331                 if (ret)
10332                         return ret;
10333         }
10334
10335         was_visible = old_plane_state->base.visible;
10336         visible = plane_state->visible;
10337
10338         if (!was_crtc_enabled && WARN_ON(was_visible))
10339                 was_visible = false;
10340
10341         /*
10342          * Visibility is calculated as if the crtc was on, but
10343          * after scaler setup everything depends on it being off
10344          * when the crtc isn't active.
10345          *
10346          * FIXME this is wrong for watermarks. Watermarks should also
10347          * be computed as if the pipe would be active. Perhaps move
10348          * per-plane wm computation to the .check_plane() hook, and
10349          * only combine the results from all planes in the current place?
10350          */
10351         if (!is_crtc_enabled) {
10352                 plane_state->visible = visible = false;
10353                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10354         }
10355
10356         if (!was_visible && !visible)
10357                 return 0;
10358
10359         if (fb != old_plane_state->base.fb)
10360                 pipe_config->fb_changed = true;
10361
10362         turn_off = was_visible && (!visible || mode_changed);
10363         turn_on = visible && (!was_visible || mode_changed);
10364
10365         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10366                          intel_crtc->base.base.id, intel_crtc->base.name,
10367                          plane->base.base.id, plane->base.name,
10368                          fb ? fb->base.id : -1);
10369
10370         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10371                          plane->base.base.id, plane->base.name,
10372                          was_visible, visible,
10373                          turn_off, turn_on, mode_changed);
10374
10375         if (turn_on) {
10376                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10377                         pipe_config->update_wm_pre = true;
10378
10379                 /* must disable cxsr around plane enable/disable */
10380                 if (plane->id != PLANE_CURSOR)
10381                         pipe_config->disable_cxsr = true;
10382         } else if (turn_off) {
10383                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10384                         pipe_config->update_wm_post = true;
10385
10386                 /* must disable cxsr around plane enable/disable */
10387                 if (plane->id != PLANE_CURSOR)
10388                         pipe_config->disable_cxsr = true;
10389         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10390                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10391                         /* FIXME bollocks */
10392                         pipe_config->update_wm_pre = true;
10393                         pipe_config->update_wm_post = true;
10394                 }
10395         }
10396
10397         if (visible || was_visible)
10398                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10399
10400         /*
10401          * WaCxSRDisabledForSpriteScaling:ivb
10402          *
10403          * cstate->update_wm was already set above, so this flag will
10404          * take effect when we commit and program watermarks.
10405          */
10406         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10407             needs_scaling(to_intel_plane_state(plane_state)) &&
10408             !needs_scaling(old_plane_state))
10409                 pipe_config->disable_lp_wm = true;
10410
10411         return 0;
10412 }
10413
10414 static bool encoders_cloneable(const struct intel_encoder *a,
10415                                const struct intel_encoder *b)
10416 {
10417         /* masks could be asymmetric, so check both ways */
10418         return a == b || (a->cloneable & (1 << b->type) &&
10419                           b->cloneable & (1 << a->type));
10420 }
10421
10422 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10423                                          struct intel_crtc *crtc,
10424                                          struct intel_encoder *encoder)
10425 {
10426         struct intel_encoder *source_encoder;
10427         struct drm_connector *connector;
10428         struct drm_connector_state *connector_state;
10429         int i;
10430
10431         for_each_new_connector_in_state(state, connector, connector_state, i) {
10432                 if (connector_state->crtc != &crtc->base)
10433                         continue;
10434
10435                 source_encoder =
10436                         to_intel_encoder(connector_state->best_encoder);
10437                 if (!encoders_cloneable(encoder, source_encoder))
10438                         return false;
10439         }
10440
10441         return true;
10442 }
10443
10444 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10445                                    struct drm_crtc_state *crtc_state)
10446 {
10447         struct drm_device *dev = crtc->dev;
10448         struct drm_i915_private *dev_priv = to_i915(dev);
10449         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10450         struct intel_crtc_state *pipe_config =
10451                 to_intel_crtc_state(crtc_state);
10452         struct drm_atomic_state *state = crtc_state->state;
10453         int ret;
10454         bool mode_changed = needs_modeset(crtc_state);
10455
10456         if (mode_changed && !crtc_state->active)
10457                 pipe_config->update_wm_post = true;
10458
10459         if (mode_changed && crtc_state->enable &&
10460             dev_priv->display.crtc_compute_clock &&
10461             !WARN_ON(pipe_config->shared_dpll)) {
10462                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10463                                                            pipe_config);
10464                 if (ret)
10465                         return ret;
10466         }
10467
10468         if (crtc_state->color_mgmt_changed) {
10469                 ret = intel_color_check(crtc, crtc_state);
10470                 if (ret)
10471                         return ret;
10472
10473                 /*
10474                  * Changing color management on Intel hardware is
10475                  * handled as part of planes update.
10476                  */
10477                 crtc_state->planes_changed = true;
10478         }
10479
10480         ret = 0;
10481         if (dev_priv->display.compute_pipe_wm) {
10482                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10483                 if (ret) {
10484                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10485                         return ret;
10486                 }
10487         }
10488
10489         if (dev_priv->display.compute_intermediate_wm &&
10490             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10491                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10492                         return 0;
10493
10494                 /*
10495                  * Calculate 'intermediate' watermarks that satisfy both the
10496                  * old state and the new state.  We can program these
10497                  * immediately.
10498                  */
10499                 ret = dev_priv->display.compute_intermediate_wm(dev,
10500                                                                 intel_crtc,
10501                                                                 pipe_config);
10502                 if (ret) {
10503                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10504                         return ret;
10505                 }
10506         } else if (dev_priv->display.compute_intermediate_wm) {
10507                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10508                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10509         }
10510
10511         if (INTEL_GEN(dev_priv) >= 9) {
10512                 if (mode_changed)
10513                         ret = skl_update_scaler_crtc(pipe_config);
10514
10515                 if (!ret)
10516                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10517                                                             pipe_config);
10518                 if (!ret)
10519                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10520                                                          pipe_config);
10521         }
10522
10523         if (HAS_IPS(dev_priv))
10524                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10525
10526         return ret;
10527 }
10528
10529 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10530         .atomic_begin = intel_begin_crtc_commit,
10531         .atomic_flush = intel_finish_crtc_commit,
10532         .atomic_check = intel_crtc_atomic_check,
10533 };
10534
10535 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10536 {
10537         struct intel_connector *connector;
10538         struct drm_connector_list_iter conn_iter;
10539
10540         drm_connector_list_iter_begin(dev, &conn_iter);
10541         for_each_intel_connector_iter(connector, &conn_iter) {
10542                 if (connector->base.state->crtc)
10543                         drm_connector_unreference(&connector->base);
10544
10545                 if (connector->base.encoder) {
10546                         connector->base.state->best_encoder =
10547                                 connector->base.encoder;
10548                         connector->base.state->crtc =
10549                                 connector->base.encoder->crtc;
10550
10551                         drm_connector_reference(&connector->base);
10552                 } else {
10553                         connector->base.state->best_encoder = NULL;
10554                         connector->base.state->crtc = NULL;
10555                 }
10556         }
10557         drm_connector_list_iter_end(&conn_iter);
10558 }
10559
10560 static void
10561 connected_sink_compute_bpp(struct intel_connector *connector,
10562                            struct intel_crtc_state *pipe_config)
10563 {
10564         const struct drm_display_info *info = &connector->base.display_info;
10565         int bpp = pipe_config->pipe_bpp;
10566
10567         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10568                       connector->base.base.id,
10569                       connector->base.name);
10570
10571         /* Don't use an invalid EDID bpc value */
10572         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10573                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10574                               bpp, info->bpc * 3);
10575                 pipe_config->pipe_bpp = info->bpc * 3;
10576         }
10577
10578         /* Clamp bpp to 8 on screens without EDID 1.4 */
10579         if (info->bpc == 0 && bpp > 24) {
10580                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10581                               bpp);
10582                 pipe_config->pipe_bpp = 24;
10583         }
10584 }
10585
10586 static int
10587 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10588                           struct intel_crtc_state *pipe_config)
10589 {
10590         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10591         struct drm_atomic_state *state;
10592         struct drm_connector *connector;
10593         struct drm_connector_state *connector_state;
10594         int bpp, i;
10595
10596         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10597             IS_CHERRYVIEW(dev_priv)))
10598                 bpp = 10*3;
10599         else if (INTEL_GEN(dev_priv) >= 5)
10600                 bpp = 12*3;
10601         else
10602                 bpp = 8*3;
10603
10604
10605         pipe_config->pipe_bpp = bpp;
10606
10607         state = pipe_config->base.state;
10608
10609         /* Clamp display bpp to EDID value */
10610         for_each_new_connector_in_state(state, connector, connector_state, i) {
10611                 if (connector_state->crtc != &crtc->base)
10612                         continue;
10613
10614                 connected_sink_compute_bpp(to_intel_connector(connector),
10615                                            pipe_config);
10616         }
10617
10618         return bpp;
10619 }
10620
10621 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10622 {
10623         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10624                         "type: 0x%x flags: 0x%x\n",
10625                 mode->crtc_clock,
10626                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10627                 mode->crtc_hsync_end, mode->crtc_htotal,
10628                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10629                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10630 }
10631
10632 static inline void
10633 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10634                       unsigned int lane_count, struct intel_link_m_n *m_n)
10635 {
10636         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10637                       id, lane_count,
10638                       m_n->gmch_m, m_n->gmch_n,
10639                       m_n->link_m, m_n->link_n, m_n->tu);
10640 }
10641
10642 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10643
10644 static const char * const output_type_str[] = {
10645         OUTPUT_TYPE(UNUSED),
10646         OUTPUT_TYPE(ANALOG),
10647         OUTPUT_TYPE(DVO),
10648         OUTPUT_TYPE(SDVO),
10649         OUTPUT_TYPE(LVDS),
10650         OUTPUT_TYPE(TVOUT),
10651         OUTPUT_TYPE(HDMI),
10652         OUTPUT_TYPE(DP),
10653         OUTPUT_TYPE(EDP),
10654         OUTPUT_TYPE(DSI),
10655         OUTPUT_TYPE(DDI),
10656         OUTPUT_TYPE(DP_MST),
10657 };
10658
10659 #undef OUTPUT_TYPE
10660
10661 static void snprintf_output_types(char *buf, size_t len,
10662                                   unsigned int output_types)
10663 {
10664         char *str = buf;
10665         int i;
10666
10667         str[0] = '\0';
10668
10669         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10670                 int r;
10671
10672                 if ((output_types & BIT(i)) == 0)
10673                         continue;
10674
10675                 r = snprintf(str, len, "%s%s",
10676                              str != buf ? "," : "", output_type_str[i]);
10677                 if (r >= len)
10678                         break;
10679                 str += r;
10680                 len -= r;
10681
10682                 output_types &= ~BIT(i);
10683         }
10684
10685         WARN_ON_ONCE(output_types != 0);
10686 }
10687
10688 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10689                                    struct intel_crtc_state *pipe_config,
10690                                    const char *context)
10691 {
10692         struct drm_device *dev = crtc->base.dev;
10693         struct drm_i915_private *dev_priv = to_i915(dev);
10694         struct drm_plane *plane;
10695         struct intel_plane *intel_plane;
10696         struct intel_plane_state *state;
10697         struct drm_framebuffer *fb;
10698         char buf[64];
10699
10700         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10701                       crtc->base.base.id, crtc->base.name, context);
10702
10703         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10704         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10705                       buf, pipe_config->output_types);
10706
10707         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10708                       transcoder_name(pipe_config->cpu_transcoder),
10709                       pipe_config->pipe_bpp, pipe_config->dither);
10710
10711         if (pipe_config->has_pch_encoder)
10712                 intel_dump_m_n_config(pipe_config, "fdi",
10713                                       pipe_config->fdi_lanes,
10714                                       &pipe_config->fdi_m_n);
10715
10716         if (pipe_config->ycbcr420)
10717                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10718
10719         if (intel_crtc_has_dp_encoder(pipe_config)) {
10720                 intel_dump_m_n_config(pipe_config, "dp m_n",
10721                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10722                 if (pipe_config->has_drrs)
10723                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10724                                               pipe_config->lane_count,
10725                                               &pipe_config->dp_m2_n2);
10726         }
10727
10728         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10729                       pipe_config->has_audio, pipe_config->has_infoframe);
10730
10731         DRM_DEBUG_KMS("requested mode:\n");
10732         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10733         DRM_DEBUG_KMS("adjusted mode:\n");
10734         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10735         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10736         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10737                       pipe_config->port_clock,
10738                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10739                       pipe_config->pixel_rate);
10740
10741         if (INTEL_GEN(dev_priv) >= 9)
10742                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10743                               crtc->num_scalers,
10744                               pipe_config->scaler_state.scaler_users,
10745                               pipe_config->scaler_state.scaler_id);
10746
10747         if (HAS_GMCH_DISPLAY(dev_priv))
10748                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10749                               pipe_config->gmch_pfit.control,
10750                               pipe_config->gmch_pfit.pgm_ratios,
10751                               pipe_config->gmch_pfit.lvds_border_bits);
10752         else
10753                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10754                               pipe_config->pch_pfit.pos,
10755                               pipe_config->pch_pfit.size,
10756                               enableddisabled(pipe_config->pch_pfit.enabled));
10757
10758         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10759                       pipe_config->ips_enabled, pipe_config->double_wide);
10760
10761         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10762
10763         DRM_DEBUG_KMS("planes on this crtc\n");
10764         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10765                 struct drm_format_name_buf format_name;
10766                 intel_plane = to_intel_plane(plane);
10767                 if (intel_plane->pipe != crtc->pipe)
10768                         continue;
10769
10770                 state = to_intel_plane_state(plane->state);
10771                 fb = state->base.fb;
10772                 if (!fb) {
10773                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10774                                       plane->base.id, plane->name, state->scaler_id);
10775                         continue;
10776                 }
10777
10778                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10779                               plane->base.id, plane->name,
10780                               fb->base.id, fb->width, fb->height,
10781                               drm_get_format_name(fb->format->format, &format_name));
10782                 if (INTEL_GEN(dev_priv) >= 9)
10783                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10784                                       state->scaler_id,
10785                                       state->base.src.x1 >> 16,
10786                                       state->base.src.y1 >> 16,
10787                                       drm_rect_width(&state->base.src) >> 16,
10788                                       drm_rect_height(&state->base.src) >> 16,
10789                                       state->base.dst.x1, state->base.dst.y1,
10790                                       drm_rect_width(&state->base.dst),
10791                                       drm_rect_height(&state->base.dst));
10792         }
10793 }
10794
10795 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10796 {
10797         struct drm_device *dev = state->dev;
10798         struct drm_connector *connector;
10799         struct drm_connector_list_iter conn_iter;
10800         unsigned int used_ports = 0;
10801         unsigned int used_mst_ports = 0;
10802         bool ret = true;
10803
10804         /*
10805          * Walk the connector list instead of the encoder
10806          * list to detect the problem on ddi platforms
10807          * where there's just one encoder per digital port.
10808          */
10809         drm_connector_list_iter_begin(dev, &conn_iter);
10810         drm_for_each_connector_iter(connector, &conn_iter) {
10811                 struct drm_connector_state *connector_state;
10812                 struct intel_encoder *encoder;
10813
10814                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
10815                 if (!connector_state)
10816                         connector_state = connector->state;
10817
10818                 if (!connector_state->best_encoder)
10819                         continue;
10820
10821                 encoder = to_intel_encoder(connector_state->best_encoder);
10822
10823                 WARN_ON(!connector_state->crtc);
10824
10825                 switch (encoder->type) {
10826                         unsigned int port_mask;
10827                 case INTEL_OUTPUT_DDI:
10828                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
10829                                 break;
10830                 case INTEL_OUTPUT_DP:
10831                 case INTEL_OUTPUT_HDMI:
10832                 case INTEL_OUTPUT_EDP:
10833                         port_mask = 1 << encoder->port;
10834
10835                         /* the same port mustn't appear more than once */
10836                         if (used_ports & port_mask)
10837                                 ret = false;
10838
10839                         used_ports |= port_mask;
10840                         break;
10841                 case INTEL_OUTPUT_DP_MST:
10842                         used_mst_ports |=
10843                                 1 << encoder->port;
10844                         break;
10845                 default:
10846                         break;
10847                 }
10848         }
10849         drm_connector_list_iter_end(&conn_iter);
10850
10851         /* can't mix MST and SST/HDMI on the same port */
10852         if (used_ports & used_mst_ports)
10853                 return false;
10854
10855         return ret;
10856 }
10857
10858 static void
10859 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10860 {
10861         struct drm_i915_private *dev_priv =
10862                 to_i915(crtc_state->base.crtc->dev);
10863         struct intel_crtc_scaler_state scaler_state;
10864         struct intel_dpll_hw_state dpll_hw_state;
10865         struct intel_shared_dpll *shared_dpll;
10866         struct intel_crtc_wm_state wm_state;
10867         bool force_thru, ips_force_disable;
10868
10869         /* FIXME: before the switch to atomic started, a new pipe_config was
10870          * kzalloc'd. Code that depends on any field being zero should be
10871          * fixed, so that the crtc_state can be safely duplicated. For now,
10872          * only fields that are know to not cause problems are preserved. */
10873
10874         scaler_state = crtc_state->scaler_state;
10875         shared_dpll = crtc_state->shared_dpll;
10876         dpll_hw_state = crtc_state->dpll_hw_state;
10877         force_thru = crtc_state->pch_pfit.force_thru;
10878         ips_force_disable = crtc_state->ips_force_disable;
10879         if (IS_G4X(dev_priv) ||
10880             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10881                 wm_state = crtc_state->wm;
10882
10883         /* Keep base drm_crtc_state intact, only clear our extended struct */
10884         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
10885         memset(&crtc_state->base + 1, 0,
10886                sizeof(*crtc_state) - sizeof(crtc_state->base));
10887
10888         crtc_state->scaler_state = scaler_state;
10889         crtc_state->shared_dpll = shared_dpll;
10890         crtc_state->dpll_hw_state = dpll_hw_state;
10891         crtc_state->pch_pfit.force_thru = force_thru;
10892         crtc_state->ips_force_disable = ips_force_disable;
10893         if (IS_G4X(dev_priv) ||
10894             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10895                 crtc_state->wm = wm_state;
10896 }
10897
10898 static int
10899 intel_modeset_pipe_config(struct drm_crtc *crtc,
10900                           struct intel_crtc_state *pipe_config)
10901 {
10902         struct drm_atomic_state *state = pipe_config->base.state;
10903         struct intel_encoder *encoder;
10904         struct drm_connector *connector;
10905         struct drm_connector_state *connector_state;
10906         int base_bpp, ret = -EINVAL;
10907         int i;
10908         bool retry = true;
10909
10910         clear_intel_crtc_state(pipe_config);
10911
10912         pipe_config->cpu_transcoder =
10913                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10914
10915         /*
10916          * Sanitize sync polarity flags based on requested ones. If neither
10917          * positive or negative polarity is requested, treat this as meaning
10918          * negative polarity.
10919          */
10920         if (!(pipe_config->base.adjusted_mode.flags &
10921               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10922                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10923
10924         if (!(pipe_config->base.adjusted_mode.flags &
10925               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10926                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10927
10928         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10929                                              pipe_config);
10930         if (base_bpp < 0)
10931                 goto fail;
10932
10933         /*
10934          * Determine the real pipe dimensions. Note that stereo modes can
10935          * increase the actual pipe size due to the frame doubling and
10936          * insertion of additional space for blanks between the frame. This
10937          * is stored in the crtc timings. We use the requested mode to do this
10938          * computation to clearly distinguish it from the adjusted mode, which
10939          * can be changed by the connectors in the below retry loop.
10940          */
10941         drm_mode_get_hv_timing(&pipe_config->base.mode,
10942                                &pipe_config->pipe_src_w,
10943                                &pipe_config->pipe_src_h);
10944
10945         for_each_new_connector_in_state(state, connector, connector_state, i) {
10946                 if (connector_state->crtc != crtc)
10947                         continue;
10948
10949                 encoder = to_intel_encoder(connector_state->best_encoder);
10950
10951                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
10952                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10953                         goto fail;
10954                 }
10955
10956                 /*
10957                  * Determine output_types before calling the .compute_config()
10958                  * hooks so that the hooks can use this information safely.
10959                  */
10960                 if (encoder->compute_output_type)
10961                         pipe_config->output_types |=
10962                                 BIT(encoder->compute_output_type(encoder, pipe_config,
10963                                                                  connector_state));
10964                 else
10965                         pipe_config->output_types |= BIT(encoder->type);
10966         }
10967
10968 encoder_retry:
10969         /* Ensure the port clock defaults are reset when retrying. */
10970         pipe_config->port_clock = 0;
10971         pipe_config->pixel_multiplier = 1;
10972
10973         /* Fill in default crtc timings, allow encoders to overwrite them. */
10974         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10975                               CRTC_STEREO_DOUBLE);
10976
10977         /* Pass our mode to the connectors and the CRTC to give them a chance to
10978          * adjust it according to limitations or connector properties, and also
10979          * a chance to reject the mode entirely.
10980          */
10981         for_each_new_connector_in_state(state, connector, connector_state, i) {
10982                 if (connector_state->crtc != crtc)
10983                         continue;
10984
10985                 encoder = to_intel_encoder(connector_state->best_encoder);
10986
10987                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
10988                         DRM_DEBUG_KMS("Encoder config failure\n");
10989                         goto fail;
10990                 }
10991         }
10992
10993         /* Set default port clock if not overwritten by the encoder. Needs to be
10994          * done afterwards in case the encoder adjusts the mode. */
10995         if (!pipe_config->port_clock)
10996                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
10997                         * pipe_config->pixel_multiplier;
10998
10999         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11000         if (ret < 0) {
11001                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11002                 goto fail;
11003         }
11004
11005         if (ret == RETRY) {
11006                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11007                         ret = -EINVAL;
11008                         goto fail;
11009                 }
11010
11011                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11012                 retry = false;
11013                 goto encoder_retry;
11014         }
11015
11016         /* Dithering seems to not pass-through bits correctly when it should, so
11017          * only enable it on 6bpc panels and when its not a compliance
11018          * test requesting 6bpc video pattern.
11019          */
11020         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11021                 !pipe_config->dither_force_disable;
11022         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11023                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11024
11025 fail:
11026         return ret;
11027 }
11028
11029 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11030 {
11031         int diff;
11032
11033         if (clock1 == clock2)
11034                 return true;
11035
11036         if (!clock1 || !clock2)
11037                 return false;
11038
11039         diff = abs(clock1 - clock2);
11040
11041         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11042                 return true;
11043
11044         return false;
11045 }
11046
11047 static bool
11048 intel_compare_m_n(unsigned int m, unsigned int n,
11049                   unsigned int m2, unsigned int n2,
11050                   bool exact)
11051 {
11052         if (m == m2 && n == n2)
11053                 return true;
11054
11055         if (exact || !m || !n || !m2 || !n2)
11056                 return false;
11057
11058         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11059
11060         if (n > n2) {
11061                 while (n > n2) {
11062                         m2 <<= 1;
11063                         n2 <<= 1;
11064                 }
11065         } else if (n < n2) {
11066                 while (n < n2) {
11067                         m <<= 1;
11068                         n <<= 1;
11069                 }
11070         }
11071
11072         if (n != n2)
11073                 return false;
11074
11075         return intel_fuzzy_clock_check(m, m2);
11076 }
11077
11078 static bool
11079 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11080                        struct intel_link_m_n *m2_n2,
11081                        bool adjust)
11082 {
11083         if (m_n->tu == m2_n2->tu &&
11084             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11085                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11086             intel_compare_m_n(m_n->link_m, m_n->link_n,
11087                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11088                 if (adjust)
11089                         *m2_n2 = *m_n;
11090
11091                 return true;
11092         }
11093
11094         return false;
11095 }
11096
11097 static void __printf(3, 4)
11098 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11099 {
11100         struct va_format vaf;
11101         va_list args;
11102
11103         va_start(args, format);
11104         vaf.fmt = format;
11105         vaf.va = &args;
11106
11107         if (adjust)
11108                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11109         else
11110                 drm_err("mismatch in %s %pV", name, &vaf);
11111
11112         va_end(args);
11113 }
11114
11115 static bool
11116 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11117                           struct intel_crtc_state *current_config,
11118                           struct intel_crtc_state *pipe_config,
11119                           bool adjust)
11120 {
11121         bool ret = true;
11122         bool fixup_inherited = adjust &&
11123                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11124                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11125
11126 #define PIPE_CONF_CHECK_X(name) \
11127         if (current_config->name != pipe_config->name) { \
11128                 pipe_config_err(adjust, __stringify(name), \
11129                           "(expected 0x%08x, found 0x%08x)\n", \
11130                           current_config->name, \
11131                           pipe_config->name); \
11132                 ret = false; \
11133         }
11134
11135 #define PIPE_CONF_CHECK_I(name) \
11136         if (current_config->name != pipe_config->name) { \
11137                 pipe_config_err(adjust, __stringify(name), \
11138                           "(expected %i, found %i)\n", \
11139                           current_config->name, \
11140                           pipe_config->name); \
11141                 ret = false; \
11142         }
11143
11144 #define PIPE_CONF_CHECK_BOOL(name)      \
11145         if (current_config->name != pipe_config->name) { \
11146                 pipe_config_err(adjust, __stringify(name), \
11147                           "(expected %s, found %s)\n", \
11148                           yesno(current_config->name), \
11149                           yesno(pipe_config->name)); \
11150                 ret = false; \
11151         }
11152
11153 /*
11154  * Checks state where we only read out the enabling, but not the entire
11155  * state itself (like full infoframes or ELD for audio). These states
11156  * require a full modeset on bootup to fix up.
11157  */
11158 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) \
11159         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11160                 PIPE_CONF_CHECK_BOOL(name); \
11161         } else { \
11162                 pipe_config_err(adjust, __stringify(name), \
11163                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11164                           yesno(current_config->name), \
11165                           yesno(pipe_config->name)); \
11166                 ret = false; \
11167         }
11168
11169 #define PIPE_CONF_CHECK_P(name) \
11170         if (current_config->name != pipe_config->name) { \
11171                 pipe_config_err(adjust, __stringify(name), \
11172                           "(expected %p, found %p)\n", \
11173                           current_config->name, \
11174                           pipe_config->name); \
11175                 ret = false; \
11176         }
11177
11178 #define PIPE_CONF_CHECK_M_N(name) \
11179         if (!intel_compare_link_m_n(&current_config->name, \
11180                                     &pipe_config->name,\
11181                                     adjust)) { \
11182                 pipe_config_err(adjust, __stringify(name), \
11183                           "(expected tu %i gmch %i/%i link %i/%i, " \
11184                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11185                           current_config->name.tu, \
11186                           current_config->name.gmch_m, \
11187                           current_config->name.gmch_n, \
11188                           current_config->name.link_m, \
11189                           current_config->name.link_n, \
11190                           pipe_config->name.tu, \
11191                           pipe_config->name.gmch_m, \
11192                           pipe_config->name.gmch_n, \
11193                           pipe_config->name.link_m, \
11194                           pipe_config->name.link_n); \
11195                 ret = false; \
11196         }
11197
11198 /* This is required for BDW+ where there is only one set of registers for
11199  * switching between high and low RR.
11200  * This macro can be used whenever a comparison has to be made between one
11201  * hw state and multiple sw state variables.
11202  */
11203 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11204         if (!intel_compare_link_m_n(&current_config->name, \
11205                                     &pipe_config->name, adjust) && \
11206             !intel_compare_link_m_n(&current_config->alt_name, \
11207                                     &pipe_config->name, adjust)) { \
11208                 pipe_config_err(adjust, __stringify(name), \
11209                           "(expected tu %i gmch %i/%i link %i/%i, " \
11210                           "or tu %i gmch %i/%i link %i/%i, " \
11211                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11212                           current_config->name.tu, \
11213                           current_config->name.gmch_m, \
11214                           current_config->name.gmch_n, \
11215                           current_config->name.link_m, \
11216                           current_config->name.link_n, \
11217                           current_config->alt_name.tu, \
11218                           current_config->alt_name.gmch_m, \
11219                           current_config->alt_name.gmch_n, \
11220                           current_config->alt_name.link_m, \
11221                           current_config->alt_name.link_n, \
11222                           pipe_config->name.tu, \
11223                           pipe_config->name.gmch_m, \
11224                           pipe_config->name.gmch_n, \
11225                           pipe_config->name.link_m, \
11226                           pipe_config->name.link_n); \
11227                 ret = false; \
11228         }
11229
11230 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11231         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11232                 pipe_config_err(adjust, __stringify(name), \
11233                           "(%x) (expected %i, found %i)\n", \
11234                           (mask), \
11235                           current_config->name & (mask), \
11236                           pipe_config->name & (mask)); \
11237                 ret = false; \
11238         }
11239
11240 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11241         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11242                 pipe_config_err(adjust, __stringify(name), \
11243                           "(expected %i, found %i)\n", \
11244                           current_config->name, \
11245                           pipe_config->name); \
11246                 ret = false; \
11247         }
11248
11249 #define PIPE_CONF_QUIRK(quirk)  \
11250         ((current_config->quirks | pipe_config->quirks) & (quirk))
11251
11252         PIPE_CONF_CHECK_I(cpu_transcoder);
11253
11254         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11255         PIPE_CONF_CHECK_I(fdi_lanes);
11256         PIPE_CONF_CHECK_M_N(fdi_m_n);
11257
11258         PIPE_CONF_CHECK_I(lane_count);
11259         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11260
11261         if (INTEL_GEN(dev_priv) < 8) {
11262                 PIPE_CONF_CHECK_M_N(dp_m_n);
11263
11264                 if (current_config->has_drrs)
11265                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11266         } else
11267                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11268
11269         PIPE_CONF_CHECK_X(output_types);
11270
11271         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11272         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11273         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11274         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11275         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11276         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11277
11278         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11279         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11280         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11281         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11282         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11283         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11284
11285         PIPE_CONF_CHECK_I(pixel_multiplier);
11286         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11287         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11288             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11289                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11290
11291         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11292         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11293         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11294         PIPE_CONF_CHECK_BOOL(ycbcr420);
11295
11296         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11297
11298         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11299                               DRM_MODE_FLAG_INTERLACE);
11300
11301         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11302                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11303                                       DRM_MODE_FLAG_PHSYNC);
11304                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11305                                       DRM_MODE_FLAG_NHSYNC);
11306                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11307                                       DRM_MODE_FLAG_PVSYNC);
11308                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11309                                       DRM_MODE_FLAG_NVSYNC);
11310         }
11311
11312         PIPE_CONF_CHECK_X(gmch_pfit.control);
11313         /* pfit ratios are autocomputed by the hw on gen4+ */
11314         if (INTEL_GEN(dev_priv) < 4)
11315                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11316         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11317
11318         if (!adjust) {
11319                 PIPE_CONF_CHECK_I(pipe_src_w);
11320                 PIPE_CONF_CHECK_I(pipe_src_h);
11321
11322                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11323                 if (current_config->pch_pfit.enabled) {
11324                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11325                         PIPE_CONF_CHECK_X(pch_pfit.size);
11326                 }
11327
11328                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11329                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11330         }
11331
11332         PIPE_CONF_CHECK_BOOL(double_wide);
11333
11334         PIPE_CONF_CHECK_P(shared_dpll);
11335         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11336         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11337         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11338         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11339         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11340         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11341         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11342         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11343         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11344         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11345         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11346         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11347         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11348         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11349         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11350         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11351         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11352         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11353         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11354         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11355         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11356
11357         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11358         PIPE_CONF_CHECK_X(dsi_pll.div);
11359
11360         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11361                 PIPE_CONF_CHECK_I(pipe_bpp);
11362
11363         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11364         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11365
11366         PIPE_CONF_CHECK_I(min_voltage_level);
11367
11368 #undef PIPE_CONF_CHECK_X
11369 #undef PIPE_CONF_CHECK_I
11370 #undef PIPE_CONF_CHECK_BOOL
11371 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11372 #undef PIPE_CONF_CHECK_P
11373 #undef PIPE_CONF_CHECK_FLAGS
11374 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11375 #undef PIPE_CONF_QUIRK
11376
11377         return ret;
11378 }
11379
11380 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11381                                            const struct intel_crtc_state *pipe_config)
11382 {
11383         if (pipe_config->has_pch_encoder) {
11384                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11385                                                             &pipe_config->fdi_m_n);
11386                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11387
11388                 /*
11389                  * FDI already provided one idea for the dotclock.
11390                  * Yell if the encoder disagrees.
11391                  */
11392                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11393                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11394                      fdi_dotclock, dotclock);
11395         }
11396 }
11397
11398 static void verify_wm_state(struct drm_crtc *crtc,
11399                             struct drm_crtc_state *new_state)
11400 {
11401         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11402         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11403         struct skl_pipe_wm hw_wm, *sw_wm;
11404         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11405         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11406         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11407         const enum pipe pipe = intel_crtc->pipe;
11408         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11409
11410         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11411                 return;
11412
11413         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11414         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11415
11416         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11417         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11418
11419         /* planes */
11420         for_each_universal_plane(dev_priv, pipe, plane) {
11421                 hw_plane_wm = &hw_wm.planes[plane];
11422                 sw_plane_wm = &sw_wm->planes[plane];
11423
11424                 /* Watermarks */
11425                 for (level = 0; level <= max_level; level++) {
11426                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11427                                                 &sw_plane_wm->wm[level]))
11428                                 continue;
11429
11430                         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",
11431                                   pipe_name(pipe), plane + 1, level,
11432                                   sw_plane_wm->wm[level].plane_en,
11433                                   sw_plane_wm->wm[level].plane_res_b,
11434                                   sw_plane_wm->wm[level].plane_res_l,
11435                                   hw_plane_wm->wm[level].plane_en,
11436                                   hw_plane_wm->wm[level].plane_res_b,
11437                                   hw_plane_wm->wm[level].plane_res_l);
11438                 }
11439
11440                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11441                                          &sw_plane_wm->trans_wm)) {
11442                         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",
11443                                   pipe_name(pipe), plane + 1,
11444                                   sw_plane_wm->trans_wm.plane_en,
11445                                   sw_plane_wm->trans_wm.plane_res_b,
11446                                   sw_plane_wm->trans_wm.plane_res_l,
11447                                   hw_plane_wm->trans_wm.plane_en,
11448                                   hw_plane_wm->trans_wm.plane_res_b,
11449                                   hw_plane_wm->trans_wm.plane_res_l);
11450                 }
11451
11452                 /* DDB */
11453                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11454                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11455
11456                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11457                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11458                                   pipe_name(pipe), plane + 1,
11459                                   sw_ddb_entry->start, sw_ddb_entry->end,
11460                                   hw_ddb_entry->start, hw_ddb_entry->end);
11461                 }
11462         }
11463
11464         /*
11465          * cursor
11466          * If the cursor plane isn't active, we may not have updated it's ddb
11467          * allocation. In that case since the ddb allocation will be updated
11468          * once the plane becomes visible, we can skip this check
11469          */
11470         if (1) {
11471                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11472                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11473
11474                 /* Watermarks */
11475                 for (level = 0; level <= max_level; level++) {
11476                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11477                                                 &sw_plane_wm->wm[level]))
11478                                 continue;
11479
11480                         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",
11481                                   pipe_name(pipe), level,
11482                                   sw_plane_wm->wm[level].plane_en,
11483                                   sw_plane_wm->wm[level].plane_res_b,
11484                                   sw_plane_wm->wm[level].plane_res_l,
11485                                   hw_plane_wm->wm[level].plane_en,
11486                                   hw_plane_wm->wm[level].plane_res_b,
11487                                   hw_plane_wm->wm[level].plane_res_l);
11488                 }
11489
11490                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11491                                          &sw_plane_wm->trans_wm)) {
11492                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11493                                   pipe_name(pipe),
11494                                   sw_plane_wm->trans_wm.plane_en,
11495                                   sw_plane_wm->trans_wm.plane_res_b,
11496                                   sw_plane_wm->trans_wm.plane_res_l,
11497                                   hw_plane_wm->trans_wm.plane_en,
11498                                   hw_plane_wm->trans_wm.plane_res_b,
11499                                   hw_plane_wm->trans_wm.plane_res_l);
11500                 }
11501
11502                 /* DDB */
11503                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11504                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11505
11506                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11507                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11508                                   pipe_name(pipe),
11509                                   sw_ddb_entry->start, sw_ddb_entry->end,
11510                                   hw_ddb_entry->start, hw_ddb_entry->end);
11511                 }
11512         }
11513 }
11514
11515 static void
11516 verify_connector_state(struct drm_device *dev,
11517                        struct drm_atomic_state *state,
11518                        struct drm_crtc *crtc)
11519 {
11520         struct drm_connector *connector;
11521         struct drm_connector_state *new_conn_state;
11522         int i;
11523
11524         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11525                 struct drm_encoder *encoder = connector->encoder;
11526                 struct drm_crtc_state *crtc_state = NULL;
11527
11528                 if (new_conn_state->crtc != crtc)
11529                         continue;
11530
11531                 if (crtc)
11532                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11533
11534                 intel_connector_verify_state(crtc_state, new_conn_state);
11535
11536                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11537                      "connector's atomic encoder doesn't match legacy encoder\n");
11538         }
11539 }
11540
11541 static void
11542 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11543 {
11544         struct intel_encoder *encoder;
11545         struct drm_connector *connector;
11546         struct drm_connector_state *old_conn_state, *new_conn_state;
11547         int i;
11548
11549         for_each_intel_encoder(dev, encoder) {
11550                 bool enabled = false, found = false;
11551                 enum pipe pipe;
11552
11553                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11554                               encoder->base.base.id,
11555                               encoder->base.name);
11556
11557                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11558                                                    new_conn_state, i) {
11559                         if (old_conn_state->best_encoder == &encoder->base)
11560                                 found = true;
11561
11562                         if (new_conn_state->best_encoder != &encoder->base)
11563                                 continue;
11564                         found = enabled = true;
11565
11566                         I915_STATE_WARN(new_conn_state->crtc !=
11567                                         encoder->base.crtc,
11568                              "connector's crtc doesn't match encoder crtc\n");
11569                 }
11570
11571                 if (!found)
11572                         continue;
11573
11574                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11575                      "encoder's enabled state mismatch "
11576                      "(expected %i, found %i)\n",
11577                      !!encoder->base.crtc, enabled);
11578
11579                 if (!encoder->base.crtc) {
11580                         bool active;
11581
11582                         active = encoder->get_hw_state(encoder, &pipe);
11583                         I915_STATE_WARN(active,
11584                              "encoder detached but still enabled on pipe %c.\n",
11585                              pipe_name(pipe));
11586                 }
11587         }
11588 }
11589
11590 static void
11591 verify_crtc_state(struct drm_crtc *crtc,
11592                   struct drm_crtc_state *old_crtc_state,
11593                   struct drm_crtc_state *new_crtc_state)
11594 {
11595         struct drm_device *dev = crtc->dev;
11596         struct drm_i915_private *dev_priv = to_i915(dev);
11597         struct intel_encoder *encoder;
11598         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11599         struct intel_crtc_state *pipe_config, *sw_config;
11600         struct drm_atomic_state *old_state;
11601         bool active;
11602
11603         old_state = old_crtc_state->state;
11604         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11605         pipe_config = to_intel_crtc_state(old_crtc_state);
11606         memset(pipe_config, 0, sizeof(*pipe_config));
11607         pipe_config->base.crtc = crtc;
11608         pipe_config->base.state = old_state;
11609
11610         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11611
11612         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11613
11614         /* we keep both pipes enabled on 830 */
11615         if (IS_I830(dev_priv))
11616                 active = new_crtc_state->active;
11617
11618         I915_STATE_WARN(new_crtc_state->active != active,
11619              "crtc active state doesn't match with hw state "
11620              "(expected %i, found %i)\n", new_crtc_state->active, active);
11621
11622         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11623              "transitional active state does not match atomic hw state "
11624              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11625
11626         for_each_encoder_on_crtc(dev, crtc, encoder) {
11627                 enum pipe pipe;
11628
11629                 active = encoder->get_hw_state(encoder, &pipe);
11630                 I915_STATE_WARN(active != new_crtc_state->active,
11631                         "[ENCODER:%i] active %i with crtc active %i\n",
11632                         encoder->base.base.id, active, new_crtc_state->active);
11633
11634                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11635                                 "Encoder connected to wrong pipe %c\n",
11636                                 pipe_name(pipe));
11637
11638                 if (active)
11639                         encoder->get_config(encoder, pipe_config);
11640         }
11641
11642         intel_crtc_compute_pixel_rate(pipe_config);
11643
11644         if (!new_crtc_state->active)
11645                 return;
11646
11647         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11648
11649         sw_config = to_intel_crtc_state(new_crtc_state);
11650         if (!intel_pipe_config_compare(dev_priv, sw_config,
11651                                        pipe_config, false)) {
11652                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11653                 intel_dump_pipe_config(intel_crtc, pipe_config,
11654                                        "[hw state]");
11655                 intel_dump_pipe_config(intel_crtc, sw_config,
11656                                        "[sw state]");
11657         }
11658 }
11659
11660 static void
11661 intel_verify_planes(struct intel_atomic_state *state)
11662 {
11663         struct intel_plane *plane;
11664         const struct intel_plane_state *plane_state;
11665         int i;
11666
11667         for_each_new_intel_plane_in_state(state, plane,
11668                                           plane_state, i)
11669                 assert_plane(plane, plane_state->base.visible);
11670 }
11671
11672 static void
11673 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11674                          struct intel_shared_dpll *pll,
11675                          struct drm_crtc *crtc,
11676                          struct drm_crtc_state *new_state)
11677 {
11678         struct intel_dpll_hw_state dpll_hw_state;
11679         unsigned crtc_mask;
11680         bool active;
11681
11682         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11683
11684         DRM_DEBUG_KMS("%s\n", pll->info->name);
11685
11686         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
11687
11688         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
11689                 I915_STATE_WARN(!pll->on && pll->active_mask,
11690                      "pll in active use but not on in sw tracking\n");
11691                 I915_STATE_WARN(pll->on && !pll->active_mask,
11692                      "pll is on but not used by any active crtc\n");
11693                 I915_STATE_WARN(pll->on != active,
11694                      "pll on state mismatch (expected %i, found %i)\n",
11695                      pll->on, active);
11696         }
11697
11698         if (!crtc) {
11699                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11700                                 "more active pll users than references: %x vs %x\n",
11701                                 pll->active_mask, pll->state.crtc_mask);
11702
11703                 return;
11704         }
11705
11706         crtc_mask = 1 << drm_crtc_index(crtc);
11707
11708         if (new_state->active)
11709                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11710                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11711                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11712         else
11713                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11714                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11715                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11716
11717         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11718                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11719                         crtc_mask, pll->state.crtc_mask);
11720
11721         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11722                                           &dpll_hw_state,
11723                                           sizeof(dpll_hw_state)),
11724                         "pll hw state mismatch\n");
11725 }
11726
11727 static void
11728 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11729                          struct drm_crtc_state *old_crtc_state,
11730                          struct drm_crtc_state *new_crtc_state)
11731 {
11732         struct drm_i915_private *dev_priv = to_i915(dev);
11733         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11734         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11735
11736         if (new_state->shared_dpll)
11737                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11738
11739         if (old_state->shared_dpll &&
11740             old_state->shared_dpll != new_state->shared_dpll) {
11741                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
11742                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11743
11744                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11745                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11746                                 pipe_name(drm_crtc_index(crtc)));
11747                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11748                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11749                                 pipe_name(drm_crtc_index(crtc)));
11750         }
11751 }
11752
11753 static void
11754 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11755                           struct drm_atomic_state *state,
11756                           struct drm_crtc_state *old_state,
11757                           struct drm_crtc_state *new_state)
11758 {
11759         if (!needs_modeset(new_state) &&
11760             !to_intel_crtc_state(new_state)->update_pipe)
11761                 return;
11762
11763         verify_wm_state(crtc, new_state);
11764         verify_connector_state(crtc->dev, state, crtc);
11765         verify_crtc_state(crtc, old_state, new_state);
11766         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11767 }
11768
11769 static void
11770 verify_disabled_dpll_state(struct drm_device *dev)
11771 {
11772         struct drm_i915_private *dev_priv = to_i915(dev);
11773         int i;
11774
11775         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11776                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
11777 }
11778
11779 static void
11780 intel_modeset_verify_disabled(struct drm_device *dev,
11781                               struct drm_atomic_state *state)
11782 {
11783         verify_encoder_state(dev, state);
11784         verify_connector_state(dev, state, NULL);
11785         verify_disabled_dpll_state(dev);
11786 }
11787
11788 static void update_scanline_offset(struct intel_crtc *crtc)
11789 {
11790         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11791
11792         /*
11793          * The scanline counter increments at the leading edge of hsync.
11794          *
11795          * On most platforms it starts counting from vtotal-1 on the
11796          * first active line. That means the scanline counter value is
11797          * always one less than what we would expect. Ie. just after
11798          * start of vblank, which also occurs at start of hsync (on the
11799          * last active line), the scanline counter will read vblank_start-1.
11800          *
11801          * On gen2 the scanline counter starts counting from 1 instead
11802          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11803          * to keep the value positive), instead of adding one.
11804          *
11805          * On HSW+ the behaviour of the scanline counter depends on the output
11806          * type. For DP ports it behaves like most other platforms, but on HDMI
11807          * there's an extra 1 line difference. So we need to add two instead of
11808          * one to the value.
11809          *
11810          * On VLV/CHV DSI the scanline counter would appear to increment
11811          * approx. 1/3 of a scanline before start of vblank. Unfortunately
11812          * that means we can't tell whether we're in vblank or not while
11813          * we're on that particular line. We must still set scanline_offset
11814          * to 1 so that the vblank timestamps come out correct when we query
11815          * the scanline counter from within the vblank interrupt handler.
11816          * However if queried just before the start of vblank we'll get an
11817          * answer that's slightly in the future.
11818          */
11819         if (IS_GEN2(dev_priv)) {
11820                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
11821                 int vtotal;
11822
11823                 vtotal = adjusted_mode->crtc_vtotal;
11824                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
11825                         vtotal /= 2;
11826
11827                 crtc->scanline_offset = vtotal - 1;
11828         } else if (HAS_DDI(dev_priv) &&
11829                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
11830                 crtc->scanline_offset = 2;
11831         } else
11832                 crtc->scanline_offset = 1;
11833 }
11834
11835 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
11836 {
11837         struct drm_device *dev = state->dev;
11838         struct drm_i915_private *dev_priv = to_i915(dev);
11839         struct drm_crtc *crtc;
11840         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11841         int i;
11842
11843         if (!dev_priv->display.crtc_compute_clock)
11844                 return;
11845
11846         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11847                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11848                 struct intel_shared_dpll *old_dpll =
11849                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
11850
11851                 if (!needs_modeset(new_crtc_state))
11852                         continue;
11853
11854                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
11855
11856                 if (!old_dpll)
11857                         continue;
11858
11859                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
11860         }
11861 }
11862
11863 /*
11864  * This implements the workaround described in the "notes" section of the mode
11865  * set sequence documentation. When going from no pipes or single pipe to
11866  * multiple pipes, and planes are enabled after the pipe, we need to wait at
11867  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
11868  */
11869 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
11870 {
11871         struct drm_crtc_state *crtc_state;
11872         struct intel_crtc *intel_crtc;
11873         struct drm_crtc *crtc;
11874         struct intel_crtc_state *first_crtc_state = NULL;
11875         struct intel_crtc_state *other_crtc_state = NULL;
11876         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
11877         int i;
11878
11879         /* look at all crtc's that are going to be enabled in during modeset */
11880         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
11881                 intel_crtc = to_intel_crtc(crtc);
11882
11883                 if (!crtc_state->active || !needs_modeset(crtc_state))
11884                         continue;
11885
11886                 if (first_crtc_state) {
11887                         other_crtc_state = to_intel_crtc_state(crtc_state);
11888                         break;
11889                 } else {
11890                         first_crtc_state = to_intel_crtc_state(crtc_state);
11891                         first_pipe = intel_crtc->pipe;
11892                 }
11893         }
11894
11895         /* No workaround needed? */
11896         if (!first_crtc_state)
11897                 return 0;
11898
11899         /* w/a possibly needed, check how many crtc's are already enabled. */
11900         for_each_intel_crtc(state->dev, intel_crtc) {
11901                 struct intel_crtc_state *pipe_config;
11902
11903                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
11904                 if (IS_ERR(pipe_config))
11905                         return PTR_ERR(pipe_config);
11906
11907                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
11908
11909                 if (!pipe_config->base.active ||
11910                     needs_modeset(&pipe_config->base))
11911                         continue;
11912
11913                 /* 2 or more enabled crtcs means no need for w/a */
11914                 if (enabled_pipe != INVALID_PIPE)
11915                         return 0;
11916
11917                 enabled_pipe = intel_crtc->pipe;
11918         }
11919
11920         if (enabled_pipe != INVALID_PIPE)
11921                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
11922         else if (other_crtc_state)
11923                 other_crtc_state->hsw_workaround_pipe = first_pipe;
11924
11925         return 0;
11926 }
11927
11928 static int intel_lock_all_pipes(struct drm_atomic_state *state)
11929 {
11930         struct drm_crtc *crtc;
11931
11932         /* Add all pipes to the state */
11933         for_each_crtc(state->dev, crtc) {
11934                 struct drm_crtc_state *crtc_state;
11935
11936                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11937                 if (IS_ERR(crtc_state))
11938                         return PTR_ERR(crtc_state);
11939         }
11940
11941         return 0;
11942 }
11943
11944 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
11945 {
11946         struct drm_crtc *crtc;
11947
11948         /*
11949          * Add all pipes to the state, and force
11950          * a modeset on all the active ones.
11951          */
11952         for_each_crtc(state->dev, crtc) {
11953                 struct drm_crtc_state *crtc_state;
11954                 int ret;
11955
11956                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11957                 if (IS_ERR(crtc_state))
11958                         return PTR_ERR(crtc_state);
11959
11960                 if (!crtc_state->active || needs_modeset(crtc_state))
11961                         continue;
11962
11963                 crtc_state->mode_changed = true;
11964
11965                 ret = drm_atomic_add_affected_connectors(state, crtc);
11966                 if (ret)
11967                         return ret;
11968
11969                 ret = drm_atomic_add_affected_planes(state, crtc);
11970                 if (ret)
11971                         return ret;
11972         }
11973
11974         return 0;
11975 }
11976
11977 static int intel_modeset_checks(struct drm_atomic_state *state)
11978 {
11979         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
11980         struct drm_i915_private *dev_priv = to_i915(state->dev);
11981         struct drm_crtc *crtc;
11982         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11983         int ret = 0, i;
11984
11985         if (!check_digital_port_conflicts(state)) {
11986                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
11987                 return -EINVAL;
11988         }
11989
11990         intel_state->modeset = true;
11991         intel_state->active_crtcs = dev_priv->active_crtcs;
11992         intel_state->cdclk.logical = dev_priv->cdclk.logical;
11993         intel_state->cdclk.actual = dev_priv->cdclk.actual;
11994
11995         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11996                 if (new_crtc_state->active)
11997                         intel_state->active_crtcs |= 1 << i;
11998                 else
11999                         intel_state->active_crtcs &= ~(1 << i);
12000
12001                 if (old_crtc_state->active != new_crtc_state->active)
12002                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12003         }
12004
12005         /*
12006          * See if the config requires any additional preparation, e.g.
12007          * to adjust global state with pipes off.  We need to do this
12008          * here so we can get the modeset_pipe updated config for the new
12009          * mode set on this crtc.  For other crtcs we need to use the
12010          * adjusted_mode bits in the crtc directly.
12011          */
12012         if (dev_priv->display.modeset_calc_cdclk) {
12013                 ret = dev_priv->display.modeset_calc_cdclk(state);
12014                 if (ret < 0)
12015                         return ret;
12016
12017                 /*
12018                  * Writes to dev_priv->cdclk.logical must protected by
12019                  * holding all the crtc locks, even if we don't end up
12020                  * touching the hardware
12021                  */
12022                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12023                                         &intel_state->cdclk.logical)) {
12024                         ret = intel_lock_all_pipes(state);
12025                         if (ret < 0)
12026                                 return ret;
12027                 }
12028
12029                 /* All pipes must be switched off while we change the cdclk. */
12030                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12031                                               &intel_state->cdclk.actual)) {
12032                         ret = intel_modeset_all_pipes(state);
12033                         if (ret < 0)
12034                                 return ret;
12035                 }
12036
12037                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12038                               intel_state->cdclk.logical.cdclk,
12039                               intel_state->cdclk.actual.cdclk);
12040                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12041                               intel_state->cdclk.logical.voltage_level,
12042                               intel_state->cdclk.actual.voltage_level);
12043         } else {
12044                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12045         }
12046
12047         intel_modeset_clear_plls(state);
12048
12049         if (IS_HASWELL(dev_priv))
12050                 return haswell_mode_set_planes_workaround(state);
12051
12052         return 0;
12053 }
12054
12055 /*
12056  * Handle calculation of various watermark data at the end of the atomic check
12057  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12058  * handlers to ensure that all derived state has been updated.
12059  */
12060 static int calc_watermark_data(struct drm_atomic_state *state)
12061 {
12062         struct drm_device *dev = state->dev;
12063         struct drm_i915_private *dev_priv = to_i915(dev);
12064
12065         /* Is there platform-specific watermark information to calculate? */
12066         if (dev_priv->display.compute_global_watermarks)
12067                 return dev_priv->display.compute_global_watermarks(state);
12068
12069         return 0;
12070 }
12071
12072 /**
12073  * intel_atomic_check - validate state object
12074  * @dev: drm device
12075  * @state: state to validate
12076  */
12077 static int intel_atomic_check(struct drm_device *dev,
12078                               struct drm_atomic_state *state)
12079 {
12080         struct drm_i915_private *dev_priv = to_i915(dev);
12081         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12082         struct drm_crtc *crtc;
12083         struct drm_crtc_state *old_crtc_state, *crtc_state;
12084         int ret, i;
12085         bool any_ms = false;
12086
12087         /* Catch I915_MODE_FLAG_INHERITED */
12088         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12089                                       crtc_state, i) {
12090                 if (crtc_state->mode.private_flags !=
12091                     old_crtc_state->mode.private_flags)
12092                         crtc_state->mode_changed = true;
12093         }
12094
12095         ret = drm_atomic_helper_check_modeset(dev, state);
12096         if (ret)
12097                 return ret;
12098
12099         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12100                 struct intel_crtc_state *pipe_config =
12101                         to_intel_crtc_state(crtc_state);
12102
12103                 if (!needs_modeset(crtc_state))
12104                         continue;
12105
12106                 if (!crtc_state->enable) {
12107                         any_ms = true;
12108                         continue;
12109                 }
12110
12111                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12112                 if (ret) {
12113                         intel_dump_pipe_config(to_intel_crtc(crtc),
12114                                                pipe_config, "[failed]");
12115                         return ret;
12116                 }
12117
12118                 if (i915_modparams.fastboot &&
12119                     intel_pipe_config_compare(dev_priv,
12120                                         to_intel_crtc_state(old_crtc_state),
12121                                         pipe_config, true)) {
12122                         crtc_state->mode_changed = false;
12123                         pipe_config->update_pipe = true;
12124                 }
12125
12126                 if (needs_modeset(crtc_state))
12127                         any_ms = true;
12128
12129                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12130                                        needs_modeset(crtc_state) ?
12131                                        "[modeset]" : "[fastset]");
12132         }
12133
12134         if (any_ms) {
12135                 ret = intel_modeset_checks(state);
12136
12137                 if (ret)
12138                         return ret;
12139         } else {
12140                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12141         }
12142
12143         ret = drm_atomic_helper_check_planes(dev, state);
12144         if (ret)
12145                 return ret;
12146
12147         intel_fbc_choose_crtc(dev_priv, intel_state);
12148         return calc_watermark_data(state);
12149 }
12150
12151 static int intel_atomic_prepare_commit(struct drm_device *dev,
12152                                        struct drm_atomic_state *state)
12153 {
12154         return drm_atomic_helper_prepare_planes(dev, state);
12155 }
12156
12157 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12158 {
12159         struct drm_device *dev = crtc->base.dev;
12160
12161         if (!dev->max_vblank_count)
12162                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12163
12164         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12165 }
12166
12167 static void intel_update_crtc(struct drm_crtc *crtc,
12168                               struct drm_atomic_state *state,
12169                               struct drm_crtc_state *old_crtc_state,
12170                               struct drm_crtc_state *new_crtc_state)
12171 {
12172         struct drm_device *dev = crtc->dev;
12173         struct drm_i915_private *dev_priv = to_i915(dev);
12174         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12175         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12176         bool modeset = needs_modeset(new_crtc_state);
12177
12178         if (modeset) {
12179                 update_scanline_offset(intel_crtc);
12180                 dev_priv->display.crtc_enable(pipe_config, state);
12181
12182                 /* vblanks work again, re-enable pipe CRC. */
12183                 intel_crtc_enable_pipe_crc(intel_crtc);
12184         } else {
12185                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12186                                        pipe_config);
12187         }
12188
12189         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12190                 intel_fbc_enable(
12191                     intel_crtc, pipe_config,
12192                     to_intel_plane_state(crtc->primary->state));
12193         }
12194
12195         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12196 }
12197
12198 static void intel_update_crtcs(struct drm_atomic_state *state)
12199 {
12200         struct drm_crtc *crtc;
12201         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12202         int i;
12203
12204         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12205                 if (!new_crtc_state->active)
12206                         continue;
12207
12208                 intel_update_crtc(crtc, state, old_crtc_state,
12209                                   new_crtc_state);
12210         }
12211 }
12212
12213 static void skl_update_crtcs(struct drm_atomic_state *state)
12214 {
12215         struct drm_i915_private *dev_priv = to_i915(state->dev);
12216         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12217         struct drm_crtc *crtc;
12218         struct intel_crtc *intel_crtc;
12219         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12220         struct intel_crtc_state *cstate;
12221         unsigned int updated = 0;
12222         bool progress;
12223         enum pipe pipe;
12224         int i;
12225
12226         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12227
12228         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12229                 /* ignore allocations for crtc's that have been turned off. */
12230                 if (new_crtc_state->active)
12231                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12232
12233         /*
12234          * Whenever the number of active pipes changes, we need to make sure we
12235          * update the pipes in the right order so that their ddb allocations
12236          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12237          * cause pipe underruns and other bad stuff.
12238          */
12239         do {
12240                 progress = false;
12241
12242                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12243                         bool vbl_wait = false;
12244                         unsigned int cmask = drm_crtc_mask(crtc);
12245
12246                         intel_crtc = to_intel_crtc(crtc);
12247                         cstate = to_intel_crtc_state(new_crtc_state);
12248                         pipe = intel_crtc->pipe;
12249
12250                         if (updated & cmask || !cstate->base.active)
12251                                 continue;
12252
12253                         if (skl_ddb_allocation_overlaps(dev_priv,
12254                                                         entries,
12255                                                         &cstate->wm.skl.ddb,
12256                                                         i))
12257                                 continue;
12258
12259                         updated |= cmask;
12260                         entries[i] = &cstate->wm.skl.ddb;
12261
12262                         /*
12263                          * If this is an already active pipe, it's DDB changed,
12264                          * and this isn't the last pipe that needs updating
12265                          * then we need to wait for a vblank to pass for the
12266                          * new ddb allocation to take effect.
12267                          */
12268                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12269                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12270                             !new_crtc_state->active_changed &&
12271                             intel_state->wm_results.dirty_pipes != updated)
12272                                 vbl_wait = true;
12273
12274                         intel_update_crtc(crtc, state, old_crtc_state,
12275                                           new_crtc_state);
12276
12277                         if (vbl_wait)
12278                                 intel_wait_for_vblank(dev_priv, pipe);
12279
12280                         progress = true;
12281                 }
12282         } while (progress);
12283 }
12284
12285 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12286 {
12287         struct intel_atomic_state *state, *next;
12288         struct llist_node *freed;
12289
12290         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12291         llist_for_each_entry_safe(state, next, freed, freed)
12292                 drm_atomic_state_put(&state->base);
12293 }
12294
12295 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12296 {
12297         struct drm_i915_private *dev_priv =
12298                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12299
12300         intel_atomic_helper_free_state(dev_priv);
12301 }
12302
12303 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12304 {
12305         struct wait_queue_entry wait_fence, wait_reset;
12306         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12307
12308         init_wait_entry(&wait_fence, 0);
12309         init_wait_entry(&wait_reset, 0);
12310         for (;;) {
12311                 prepare_to_wait(&intel_state->commit_ready.wait,
12312                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12313                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12314                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12315
12316
12317                 if (i915_sw_fence_done(&intel_state->commit_ready)
12318                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12319                         break;
12320
12321                 schedule();
12322         }
12323         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12324         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12325 }
12326
12327 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12328 {
12329         struct drm_device *dev = state->dev;
12330         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12331         struct drm_i915_private *dev_priv = to_i915(dev);
12332         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12333         struct drm_crtc *crtc;
12334         struct intel_crtc_state *intel_cstate;
12335         u64 put_domains[I915_MAX_PIPES] = {};
12336         int i;
12337
12338         intel_atomic_commit_fence_wait(intel_state);
12339
12340         drm_atomic_helper_wait_for_dependencies(state);
12341
12342         if (intel_state->modeset)
12343                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12344
12345         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12346                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12347
12348                 if (needs_modeset(new_crtc_state) ||
12349                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12350
12351                         put_domains[to_intel_crtc(crtc)->pipe] =
12352                                 modeset_get_crtc_power_domains(crtc,
12353                                         to_intel_crtc_state(new_crtc_state));
12354                 }
12355
12356                 if (!needs_modeset(new_crtc_state))
12357                         continue;
12358
12359                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12360                                        to_intel_crtc_state(new_crtc_state));
12361
12362                 if (old_crtc_state->active) {
12363                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12364
12365                         /*
12366                          * We need to disable pipe CRC before disabling the pipe,
12367                          * or we race against vblank off.
12368                          */
12369                         intel_crtc_disable_pipe_crc(intel_crtc);
12370
12371                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12372                         intel_crtc->active = false;
12373                         intel_fbc_disable(intel_crtc);
12374                         intel_disable_shared_dpll(intel_crtc);
12375
12376                         /*
12377                          * Underruns don't always raise
12378                          * interrupts, so check manually.
12379                          */
12380                         intel_check_cpu_fifo_underruns(dev_priv);
12381                         intel_check_pch_fifo_underruns(dev_priv);
12382
12383                         if (!new_crtc_state->active) {
12384                                 /*
12385                                  * Make sure we don't call initial_watermarks
12386                                  * for ILK-style watermark updates.
12387                                  *
12388                                  * No clue what this is supposed to achieve.
12389                                  */
12390                                 if (INTEL_GEN(dev_priv) >= 9)
12391                                         dev_priv->display.initial_watermarks(intel_state,
12392                                                                              to_intel_crtc_state(new_crtc_state));
12393                         }
12394                 }
12395         }
12396
12397         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12398         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12399                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12400
12401         if (intel_state->modeset) {
12402                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12403
12404                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12405
12406                 /*
12407                  * SKL workaround: bspec recommends we disable the SAGV when we
12408                  * have more then one pipe enabled
12409                  */
12410                 if (!intel_can_enable_sagv(state))
12411                         intel_disable_sagv(dev_priv);
12412
12413                 intel_modeset_verify_disabled(dev, state);
12414         }
12415
12416         /* Complete the events for pipes that have now been disabled */
12417         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12418                 bool modeset = needs_modeset(new_crtc_state);
12419
12420                 /* Complete events for now disable pipes here. */
12421                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12422                         spin_lock_irq(&dev->event_lock);
12423                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12424                         spin_unlock_irq(&dev->event_lock);
12425
12426                         new_crtc_state->event = NULL;
12427                 }
12428         }
12429
12430         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12431         dev_priv->display.update_crtcs(state);
12432
12433         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12434          * already, but still need the state for the delayed optimization. To
12435          * fix this:
12436          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12437          * - schedule that vblank worker _before_ calling hw_done
12438          * - at the start of commit_tail, cancel it _synchrously
12439          * - switch over to the vblank wait helper in the core after that since
12440          *   we don't need out special handling any more.
12441          */
12442         drm_atomic_helper_wait_for_flip_done(dev, state);
12443
12444         /*
12445          * Now that the vblank has passed, we can go ahead and program the
12446          * optimal watermarks on platforms that need two-step watermark
12447          * programming.
12448          *
12449          * TODO: Move this (and other cleanup) to an async worker eventually.
12450          */
12451         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12452                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12453
12454                 if (dev_priv->display.optimize_watermarks)
12455                         dev_priv->display.optimize_watermarks(intel_state,
12456                                                               intel_cstate);
12457         }
12458
12459         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12460                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12461
12462                 if (put_domains[i])
12463                         modeset_put_power_domains(dev_priv, put_domains[i]);
12464
12465                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12466         }
12467
12468         if (intel_state->modeset)
12469                 intel_verify_planes(intel_state);
12470
12471         if (intel_state->modeset && intel_can_enable_sagv(state))
12472                 intel_enable_sagv(dev_priv);
12473
12474         drm_atomic_helper_commit_hw_done(state);
12475
12476         if (intel_state->modeset) {
12477                 /* As one of the primary mmio accessors, KMS has a high
12478                  * likelihood of triggering bugs in unclaimed access. After we
12479                  * finish modesetting, see if an error has been flagged, and if
12480                  * so enable debugging for the next modeset - and hope we catch
12481                  * the culprit.
12482                  */
12483                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12484                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12485         }
12486
12487         drm_atomic_helper_cleanup_planes(dev, state);
12488
12489         drm_atomic_helper_commit_cleanup_done(state);
12490
12491         drm_atomic_state_put(state);
12492
12493         intel_atomic_helper_free_state(dev_priv);
12494 }
12495
12496 static void intel_atomic_commit_work(struct work_struct *work)
12497 {
12498         struct drm_atomic_state *state =
12499                 container_of(work, struct drm_atomic_state, commit_work);
12500
12501         intel_atomic_commit_tail(state);
12502 }
12503
12504 static int __i915_sw_fence_call
12505 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12506                           enum i915_sw_fence_notify notify)
12507 {
12508         struct intel_atomic_state *state =
12509                 container_of(fence, struct intel_atomic_state, commit_ready);
12510
12511         switch (notify) {
12512         case FENCE_COMPLETE:
12513                 /* we do blocking waits in the worker, nothing to do here */
12514                 break;
12515         case FENCE_FREE:
12516                 {
12517                         struct intel_atomic_helper *helper =
12518                                 &to_i915(state->base.dev)->atomic_helper;
12519
12520                         if (llist_add(&state->freed, &helper->free_list))
12521                                 schedule_work(&helper->free_work);
12522                         break;
12523                 }
12524         }
12525
12526         return NOTIFY_DONE;
12527 }
12528
12529 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12530 {
12531         struct drm_plane_state *old_plane_state, *new_plane_state;
12532         struct drm_plane *plane;
12533         int i;
12534
12535         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12536                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12537                                   intel_fb_obj(new_plane_state->fb),
12538                                   to_intel_plane(plane)->frontbuffer_bit);
12539 }
12540
12541 /**
12542  * intel_atomic_commit - commit validated state object
12543  * @dev: DRM device
12544  * @state: the top-level driver state object
12545  * @nonblock: nonblocking commit
12546  *
12547  * This function commits a top-level state object that has been validated
12548  * with drm_atomic_helper_check().
12549  *
12550  * RETURNS
12551  * Zero for success or -errno.
12552  */
12553 static int intel_atomic_commit(struct drm_device *dev,
12554                                struct drm_atomic_state *state,
12555                                bool nonblock)
12556 {
12557         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12558         struct drm_i915_private *dev_priv = to_i915(dev);
12559         int ret = 0;
12560
12561         drm_atomic_state_get(state);
12562         i915_sw_fence_init(&intel_state->commit_ready,
12563                            intel_atomic_commit_ready);
12564
12565         /*
12566          * The intel_legacy_cursor_update() fast path takes care
12567          * of avoiding the vblank waits for simple cursor
12568          * movement and flips. For cursor on/off and size changes,
12569          * we want to perform the vblank waits so that watermark
12570          * updates happen during the correct frames. Gen9+ have
12571          * double buffered watermarks and so shouldn't need this.
12572          *
12573          * Unset state->legacy_cursor_update before the call to
12574          * drm_atomic_helper_setup_commit() because otherwise
12575          * drm_atomic_helper_wait_for_flip_done() is a noop and
12576          * we get FIFO underruns because we didn't wait
12577          * for vblank.
12578          *
12579          * FIXME doing watermarks and fb cleanup from a vblank worker
12580          * (assuming we had any) would solve these problems.
12581          */
12582         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12583                 struct intel_crtc_state *new_crtc_state;
12584                 struct intel_crtc *crtc;
12585                 int i;
12586
12587                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12588                         if (new_crtc_state->wm.need_postvbl_update ||
12589                             new_crtc_state->update_wm_post)
12590                                 state->legacy_cursor_update = false;
12591         }
12592
12593         ret = intel_atomic_prepare_commit(dev, state);
12594         if (ret) {
12595                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12596                 i915_sw_fence_commit(&intel_state->commit_ready);
12597                 return ret;
12598         }
12599
12600         ret = drm_atomic_helper_setup_commit(state, nonblock);
12601         if (!ret)
12602                 ret = drm_atomic_helper_swap_state(state, true);
12603
12604         if (ret) {
12605                 i915_sw_fence_commit(&intel_state->commit_ready);
12606
12607                 drm_atomic_helper_cleanup_planes(dev, state);
12608                 return ret;
12609         }
12610         dev_priv->wm.distrust_bios_wm = false;
12611         intel_shared_dpll_swap_state(state);
12612         intel_atomic_track_fbs(state);
12613
12614         if (intel_state->modeset) {
12615                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12616                        sizeof(intel_state->min_cdclk));
12617                 memcpy(dev_priv->min_voltage_level,
12618                        intel_state->min_voltage_level,
12619                        sizeof(intel_state->min_voltage_level));
12620                 dev_priv->active_crtcs = intel_state->active_crtcs;
12621                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12622                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12623         }
12624
12625         drm_atomic_state_get(state);
12626         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12627
12628         i915_sw_fence_commit(&intel_state->commit_ready);
12629         if (nonblock && intel_state->modeset) {
12630                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12631         } else if (nonblock) {
12632                 queue_work(system_unbound_wq, &state->commit_work);
12633         } else {
12634                 if (intel_state->modeset)
12635                         flush_workqueue(dev_priv->modeset_wq);
12636                 intel_atomic_commit_tail(state);
12637         }
12638
12639         return 0;
12640 }
12641
12642 static const struct drm_crtc_funcs intel_crtc_funcs = {
12643         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12644         .set_config = drm_atomic_helper_set_config,
12645         .destroy = intel_crtc_destroy,
12646         .page_flip = drm_atomic_helper_page_flip,
12647         .atomic_duplicate_state = intel_crtc_duplicate_state,
12648         .atomic_destroy_state = intel_crtc_destroy_state,
12649         .set_crc_source = intel_crtc_set_crc_source,
12650 };
12651
12652 struct wait_rps_boost {
12653         struct wait_queue_entry wait;
12654
12655         struct drm_crtc *crtc;
12656         struct i915_request *request;
12657 };
12658
12659 static int do_rps_boost(struct wait_queue_entry *_wait,
12660                         unsigned mode, int sync, void *key)
12661 {
12662         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12663         struct i915_request *rq = wait->request;
12664
12665         /*
12666          * If we missed the vblank, but the request is already running it
12667          * is reasonable to assume that it will complete before the next
12668          * vblank without our intervention, so leave RPS alone.
12669          */
12670         if (!i915_request_started(rq))
12671                 gen6_rps_boost(rq, NULL);
12672         i915_request_put(rq);
12673
12674         drm_crtc_vblank_put(wait->crtc);
12675
12676         list_del(&wait->wait.entry);
12677         kfree(wait);
12678         return 1;
12679 }
12680
12681 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12682                                        struct dma_fence *fence)
12683 {
12684         struct wait_rps_boost *wait;
12685
12686         if (!dma_fence_is_i915(fence))
12687                 return;
12688
12689         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12690                 return;
12691
12692         if (drm_crtc_vblank_get(crtc))
12693                 return;
12694
12695         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12696         if (!wait) {
12697                 drm_crtc_vblank_put(crtc);
12698                 return;
12699         }
12700
12701         wait->request = to_request(dma_fence_get(fence));
12702         wait->crtc = crtc;
12703
12704         wait->wait.func = do_rps_boost;
12705         wait->wait.flags = 0;
12706
12707         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12708 }
12709
12710 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
12711 {
12712         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
12713         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12714         struct drm_framebuffer *fb = plane_state->base.fb;
12715         struct i915_vma *vma;
12716
12717         if (plane->id == PLANE_CURSOR &&
12718             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12719                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12720                 const int align = intel_cursor_alignment(dev_priv);
12721
12722                 return i915_gem_object_attach_phys(obj, align);
12723         }
12724
12725         vma = intel_pin_and_fence_fb_obj(fb,
12726                                          plane_state->base.rotation,
12727                                          intel_plane_uses_fence(plane_state),
12728                                          &plane_state->flags);
12729         if (IS_ERR(vma))
12730                 return PTR_ERR(vma);
12731
12732         plane_state->vma = vma;
12733
12734         return 0;
12735 }
12736
12737 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
12738 {
12739         struct i915_vma *vma;
12740
12741         vma = fetch_and_zero(&old_plane_state->vma);
12742         if (vma)
12743                 intel_unpin_fb_vma(vma, old_plane_state->flags);
12744 }
12745
12746 /**
12747  * intel_prepare_plane_fb - Prepare fb for usage on plane
12748  * @plane: drm plane to prepare for
12749  * @new_state: the plane state being prepared
12750  *
12751  * Prepares a framebuffer for usage on a display plane.  Generally this
12752  * involves pinning the underlying object and updating the frontbuffer tracking
12753  * bits.  Some older platforms need special physical address handling for
12754  * cursor planes.
12755  *
12756  * Must be called with struct_mutex held.
12757  *
12758  * Returns 0 on success, negative error code on failure.
12759  */
12760 int
12761 intel_prepare_plane_fb(struct drm_plane *plane,
12762                        struct drm_plane_state *new_state)
12763 {
12764         struct intel_atomic_state *intel_state =
12765                 to_intel_atomic_state(new_state->state);
12766         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12767         struct drm_framebuffer *fb = new_state->fb;
12768         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12769         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
12770         int ret;
12771
12772         if (old_obj) {
12773                 struct drm_crtc_state *crtc_state =
12774                         drm_atomic_get_existing_crtc_state(new_state->state,
12775                                                            plane->state->crtc);
12776
12777                 /* Big Hammer, we also need to ensure that any pending
12778                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
12779                  * current scanout is retired before unpinning the old
12780                  * framebuffer. Note that we rely on userspace rendering
12781                  * into the buffer attached to the pipe they are waiting
12782                  * on. If not, userspace generates a GPU hang with IPEHR
12783                  * point to the MI_WAIT_FOR_EVENT.
12784                  *
12785                  * This should only fail upon a hung GPU, in which case we
12786                  * can safely continue.
12787                  */
12788                 if (needs_modeset(crtc_state)) {
12789                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12790                                                               old_obj->resv, NULL,
12791                                                               false, 0,
12792                                                               GFP_KERNEL);
12793                         if (ret < 0)
12794                                 return ret;
12795                 }
12796         }
12797
12798         if (new_state->fence) { /* explicit fencing */
12799                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
12800                                                     new_state->fence,
12801                                                     I915_FENCE_TIMEOUT,
12802                                                     GFP_KERNEL);
12803                 if (ret < 0)
12804                         return ret;
12805         }
12806
12807         if (!obj)
12808                 return 0;
12809
12810         ret = i915_gem_object_pin_pages(obj);
12811         if (ret)
12812                 return ret;
12813
12814         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
12815         if (ret) {
12816                 i915_gem_object_unpin_pages(obj);
12817                 return ret;
12818         }
12819
12820         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
12821
12822         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12823
12824         mutex_unlock(&dev_priv->drm.struct_mutex);
12825         i915_gem_object_unpin_pages(obj);
12826         if (ret)
12827                 return ret;
12828
12829         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
12830
12831         if (!new_state->fence) { /* implicit fencing */
12832                 struct dma_fence *fence;
12833
12834                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12835                                                       obj->resv, NULL,
12836                                                       false, I915_FENCE_TIMEOUT,
12837                                                       GFP_KERNEL);
12838                 if (ret < 0)
12839                         return ret;
12840
12841                 fence = reservation_object_get_excl_rcu(obj->resv);
12842                 if (fence) {
12843                         add_rps_boost_after_vblank(new_state->crtc, fence);
12844                         dma_fence_put(fence);
12845                 }
12846         } else {
12847                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
12848         }
12849
12850         return 0;
12851 }
12852
12853 /**
12854  * intel_cleanup_plane_fb - Cleans up an fb after plane use
12855  * @plane: drm plane to clean up for
12856  * @old_state: the state from the previous modeset
12857  *
12858  * Cleans up a framebuffer that has just been removed from a plane.
12859  *
12860  * Must be called with struct_mutex held.
12861  */
12862 void
12863 intel_cleanup_plane_fb(struct drm_plane *plane,
12864                        struct drm_plane_state *old_state)
12865 {
12866         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12867
12868         /* Should only be called after a successful intel_prepare_plane_fb()! */
12869         mutex_lock(&dev_priv->drm.struct_mutex);
12870         intel_plane_unpin_fb(to_intel_plane_state(old_state));
12871         mutex_unlock(&dev_priv->drm.struct_mutex);
12872 }
12873
12874 int
12875 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
12876 {
12877         struct drm_i915_private *dev_priv;
12878         int max_scale;
12879         int crtc_clock, max_dotclk;
12880
12881         if (!intel_crtc || !crtc_state->base.enable)
12882                 return DRM_PLANE_HELPER_NO_SCALING;
12883
12884         dev_priv = to_i915(intel_crtc->base.dev);
12885
12886         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
12887         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
12888
12889         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
12890                 max_dotclk *= 2;
12891
12892         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
12893                 return DRM_PLANE_HELPER_NO_SCALING;
12894
12895         /*
12896          * skl max scale is lower of:
12897          *    close to 3 but not 3, -1 is for that purpose
12898          *            or
12899          *    cdclk/crtc_clock
12900          */
12901         max_scale = min((1 << 16) * 3 - 1,
12902                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
12903
12904         return max_scale;
12905 }
12906
12907 static int
12908 intel_check_primary_plane(struct intel_plane *plane,
12909                           struct intel_crtc_state *crtc_state,
12910                           struct intel_plane_state *state)
12911 {
12912         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12913         struct drm_crtc *crtc = state->base.crtc;
12914         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
12915         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
12916         bool can_position = false;
12917         int ret;
12918
12919         if (INTEL_GEN(dev_priv) >= 9) {
12920                 /* use scaler when colorkey is not required */
12921                 if (!state->ckey.flags) {
12922                         min_scale = 1;
12923                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
12924                 }
12925                 can_position = true;
12926         }
12927
12928         ret = drm_atomic_helper_check_plane_state(&state->base,
12929                                                   &crtc_state->base,
12930                                                   min_scale, max_scale,
12931                                                   can_position, true);
12932         if (ret)
12933                 return ret;
12934
12935         if (!state->base.fb)
12936                 return 0;
12937
12938         if (INTEL_GEN(dev_priv) >= 9) {
12939                 ret = skl_check_plane_surface(crtc_state, state);
12940                 if (ret)
12941                         return ret;
12942
12943                 state->ctl = skl_plane_ctl(crtc_state, state);
12944         } else {
12945                 ret = i9xx_check_plane_surface(state);
12946                 if (ret)
12947                         return ret;
12948
12949                 state->ctl = i9xx_plane_ctl(crtc_state, state);
12950         }
12951
12952         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
12953                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
12954
12955         return 0;
12956 }
12957
12958 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
12959                                     struct drm_crtc_state *old_crtc_state)
12960 {
12961         struct drm_device *dev = crtc->dev;
12962         struct drm_i915_private *dev_priv = to_i915(dev);
12963         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12964         struct intel_crtc_state *old_intel_cstate =
12965                 to_intel_crtc_state(old_crtc_state);
12966         struct intel_atomic_state *old_intel_state =
12967                 to_intel_atomic_state(old_crtc_state->state);
12968         struct intel_crtc_state *intel_cstate =
12969                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12970         bool modeset = needs_modeset(&intel_cstate->base);
12971
12972         if (!modeset &&
12973             (intel_cstate->base.color_mgmt_changed ||
12974              intel_cstate->update_pipe)) {
12975                 intel_color_set_csc(&intel_cstate->base);
12976                 intel_color_load_luts(&intel_cstate->base);
12977         }
12978
12979         /* Perform vblank evasion around commit operation */
12980         intel_pipe_update_start(intel_cstate);
12981
12982         if (modeset)
12983                 goto out;
12984
12985         if (intel_cstate->update_pipe)
12986                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
12987         else if (INTEL_GEN(dev_priv) >= 9)
12988                 skl_detach_scalers(intel_crtc);
12989
12990 out:
12991         if (dev_priv->display.atomic_update_watermarks)
12992                 dev_priv->display.atomic_update_watermarks(old_intel_state,
12993                                                            intel_cstate);
12994 }
12995
12996 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
12997                                      struct drm_crtc_state *old_crtc_state)
12998 {
12999         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13000         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13001         struct intel_atomic_state *old_intel_state =
13002                 to_intel_atomic_state(old_crtc_state->state);
13003         struct intel_crtc_state *new_crtc_state =
13004                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13005
13006         intel_pipe_update_end(new_crtc_state);
13007
13008         if (new_crtc_state->update_pipe &&
13009             !needs_modeset(&new_crtc_state->base) &&
13010             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED) {
13011                 if (!IS_GEN2(dev_priv))
13012                         intel_set_cpu_fifo_underrun_reporting(dev_priv, intel_crtc->pipe, true);
13013
13014                 if (new_crtc_state->has_pch_encoder) {
13015                         enum pipe pch_transcoder =
13016                                 intel_crtc_pch_transcoder(intel_crtc);
13017
13018                         intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13019                 }
13020         }
13021 }
13022
13023 /**
13024  * intel_plane_destroy - destroy a plane
13025  * @plane: plane to destroy
13026  *
13027  * Common destruction function for all types of planes (primary, cursor,
13028  * sprite).
13029  */
13030 void intel_plane_destroy(struct drm_plane *plane)
13031 {
13032         drm_plane_cleanup(plane);
13033         kfree(to_intel_plane(plane));
13034 }
13035
13036 static bool i8xx_mod_supported(uint32_t format, uint64_t modifier)
13037 {
13038         switch (format) {
13039         case DRM_FORMAT_C8:
13040         case DRM_FORMAT_RGB565:
13041         case DRM_FORMAT_XRGB1555:
13042         case DRM_FORMAT_XRGB8888:
13043                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13044                         modifier == I915_FORMAT_MOD_X_TILED;
13045         default:
13046                 return false;
13047         }
13048 }
13049
13050 static bool i965_mod_supported(uint32_t format, uint64_t modifier)
13051 {
13052         switch (format) {
13053         case DRM_FORMAT_C8:
13054         case DRM_FORMAT_RGB565:
13055         case DRM_FORMAT_XRGB8888:
13056         case DRM_FORMAT_XBGR8888:
13057         case DRM_FORMAT_XRGB2101010:
13058         case DRM_FORMAT_XBGR2101010:
13059                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13060                         modifier == I915_FORMAT_MOD_X_TILED;
13061         default:
13062                 return false;
13063         }
13064 }
13065
13066 static bool skl_mod_supported(uint32_t format, uint64_t modifier)
13067 {
13068         switch (format) {
13069         case DRM_FORMAT_XRGB8888:
13070         case DRM_FORMAT_XBGR8888:
13071         case DRM_FORMAT_ARGB8888:
13072         case DRM_FORMAT_ABGR8888:
13073                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
13074                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
13075                         return true;
13076                 /* fall through */
13077         case DRM_FORMAT_RGB565:
13078         case DRM_FORMAT_XRGB2101010:
13079         case DRM_FORMAT_XBGR2101010:
13080         case DRM_FORMAT_YUYV:
13081         case DRM_FORMAT_YVYU:
13082         case DRM_FORMAT_UYVY:
13083         case DRM_FORMAT_VYUY:
13084                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13085                         return true;
13086                 /* fall through */
13087         case DRM_FORMAT_C8:
13088                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13089                     modifier == I915_FORMAT_MOD_X_TILED ||
13090                     modifier == I915_FORMAT_MOD_Y_TILED)
13091                         return true;
13092                 /* fall through */
13093         default:
13094                 return false;
13095         }
13096 }
13097
13098 static bool intel_primary_plane_format_mod_supported(struct drm_plane *plane,
13099                                                      uint32_t format,
13100                                                      uint64_t modifier)
13101 {
13102         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13103
13104         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13105                 return false;
13106
13107         if ((modifier >> 56) != DRM_FORMAT_MOD_VENDOR_INTEL &&
13108             modifier != DRM_FORMAT_MOD_LINEAR)
13109                 return false;
13110
13111         if (INTEL_GEN(dev_priv) >= 9)
13112                 return skl_mod_supported(format, modifier);
13113         else if (INTEL_GEN(dev_priv) >= 4)
13114                 return i965_mod_supported(format, modifier);
13115         else
13116                 return i8xx_mod_supported(format, modifier);
13117 }
13118
13119 static bool intel_cursor_plane_format_mod_supported(struct drm_plane *plane,
13120                                                     uint32_t format,
13121                                                     uint64_t modifier)
13122 {
13123         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13124                 return false;
13125
13126         return modifier == DRM_FORMAT_MOD_LINEAR && format == DRM_FORMAT_ARGB8888;
13127 }
13128
13129 static struct drm_plane_funcs intel_plane_funcs = {
13130         .update_plane = drm_atomic_helper_update_plane,
13131         .disable_plane = drm_atomic_helper_disable_plane,
13132         .destroy = intel_plane_destroy,
13133         .atomic_get_property = intel_plane_atomic_get_property,
13134         .atomic_set_property = intel_plane_atomic_set_property,
13135         .atomic_duplicate_state = intel_plane_duplicate_state,
13136         .atomic_destroy_state = intel_plane_destroy_state,
13137         .format_mod_supported = intel_primary_plane_format_mod_supported,
13138 };
13139
13140 static int
13141 intel_legacy_cursor_update(struct drm_plane *plane,
13142                            struct drm_crtc *crtc,
13143                            struct drm_framebuffer *fb,
13144                            int crtc_x, int crtc_y,
13145                            unsigned int crtc_w, unsigned int crtc_h,
13146                            uint32_t src_x, uint32_t src_y,
13147                            uint32_t src_w, uint32_t src_h,
13148                            struct drm_modeset_acquire_ctx *ctx)
13149 {
13150         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13151         int ret;
13152         struct drm_plane_state *old_plane_state, *new_plane_state;
13153         struct intel_plane *intel_plane = to_intel_plane(plane);
13154         struct drm_framebuffer *old_fb;
13155         struct drm_crtc_state *crtc_state = crtc->state;
13156
13157         /*
13158          * When crtc is inactive or there is a modeset pending,
13159          * wait for it to complete in the slowpath
13160          */
13161         if (!crtc_state->active || needs_modeset(crtc_state) ||
13162             to_intel_crtc_state(crtc_state)->update_pipe)
13163                 goto slow;
13164
13165         old_plane_state = plane->state;
13166         /*
13167          * Don't do an async update if there is an outstanding commit modifying
13168          * the plane.  This prevents our async update's changes from getting
13169          * overridden by a previous synchronous update's state.
13170          */
13171         if (old_plane_state->commit &&
13172             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13173                 goto slow;
13174
13175         /*
13176          * If any parameters change that may affect watermarks,
13177          * take the slowpath. Only changing fb or position should be
13178          * in the fastpath.
13179          */
13180         if (old_plane_state->crtc != crtc ||
13181             old_plane_state->src_w != src_w ||
13182             old_plane_state->src_h != src_h ||
13183             old_plane_state->crtc_w != crtc_w ||
13184             old_plane_state->crtc_h != crtc_h ||
13185             !old_plane_state->fb != !fb)
13186                 goto slow;
13187
13188         new_plane_state = intel_plane_duplicate_state(plane);
13189         if (!new_plane_state)
13190                 return -ENOMEM;
13191
13192         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13193
13194         new_plane_state->src_x = src_x;
13195         new_plane_state->src_y = src_y;
13196         new_plane_state->src_w = src_w;
13197         new_plane_state->src_h = src_h;
13198         new_plane_state->crtc_x = crtc_x;
13199         new_plane_state->crtc_y = crtc_y;
13200         new_plane_state->crtc_w = crtc_w;
13201         new_plane_state->crtc_h = crtc_h;
13202
13203         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13204                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13205                                                   to_intel_plane_state(plane->state),
13206                                                   to_intel_plane_state(new_plane_state));
13207         if (ret)
13208                 goto out_free;
13209
13210         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13211         if (ret)
13212                 goto out_free;
13213
13214         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13215         if (ret)
13216                 goto out_unlock;
13217
13218         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13219
13220         old_fb = old_plane_state->fb;
13221         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13222                           intel_plane->frontbuffer_bit);
13223
13224         /* Swap plane state */
13225         plane->state = new_plane_state;
13226
13227         if (plane->state->visible) {
13228                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13229                 intel_plane->update_plane(intel_plane,
13230                                           to_intel_crtc_state(crtc->state),
13231                                           to_intel_plane_state(plane->state));
13232         } else {
13233                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13234                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13235         }
13236
13237         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13238
13239 out_unlock:
13240         mutex_unlock(&dev_priv->drm.struct_mutex);
13241 out_free:
13242         if (ret)
13243                 intel_plane_destroy_state(plane, new_plane_state);
13244         else
13245                 intel_plane_destroy_state(plane, old_plane_state);
13246         return ret;
13247
13248 slow:
13249         return drm_atomic_helper_update_plane(plane, crtc, fb,
13250                                               crtc_x, crtc_y, crtc_w, crtc_h,
13251                                               src_x, src_y, src_w, src_h, ctx);
13252 }
13253
13254 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13255         .update_plane = intel_legacy_cursor_update,
13256         .disable_plane = drm_atomic_helper_disable_plane,
13257         .destroy = intel_plane_destroy,
13258         .atomic_get_property = intel_plane_atomic_get_property,
13259         .atomic_set_property = intel_plane_atomic_set_property,
13260         .atomic_duplicate_state = intel_plane_duplicate_state,
13261         .atomic_destroy_state = intel_plane_destroy_state,
13262         .format_mod_supported = intel_cursor_plane_format_mod_supported,
13263 };
13264
13265 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13266                                enum i9xx_plane_id i9xx_plane)
13267 {
13268         if (!HAS_FBC(dev_priv))
13269                 return false;
13270
13271         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13272                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13273         else if (IS_IVYBRIDGE(dev_priv))
13274                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13275                         i9xx_plane == PLANE_C;
13276         else if (INTEL_GEN(dev_priv) >= 4)
13277                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13278         else
13279                 return i9xx_plane == PLANE_A;
13280 }
13281
13282 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13283                               enum pipe pipe, enum plane_id plane_id)
13284 {
13285         if (!HAS_FBC(dev_priv))
13286                 return false;
13287
13288         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13289 }
13290
13291 static struct intel_plane *
13292 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13293 {
13294         struct intel_plane *primary = NULL;
13295         struct intel_plane_state *state = NULL;
13296         const uint32_t *intel_primary_formats;
13297         unsigned int supported_rotations;
13298         unsigned int num_formats;
13299         const uint64_t *modifiers;
13300         int ret;
13301
13302         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13303         if (!primary) {
13304                 ret = -ENOMEM;
13305                 goto fail;
13306         }
13307
13308         state = intel_create_plane_state(&primary->base);
13309         if (!state) {
13310                 ret = -ENOMEM;
13311                 goto fail;
13312         }
13313
13314         primary->base.state = &state->base;
13315
13316         primary->can_scale = false;
13317         primary->max_downscale = 1;
13318         if (INTEL_GEN(dev_priv) >= 9) {
13319                 primary->can_scale = true;
13320                 state->scaler_id = -1;
13321         }
13322         primary->pipe = pipe;
13323         /*
13324          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13325          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13326          */
13327         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13328                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13329         else
13330                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13331         primary->id = PLANE_PRIMARY;
13332         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13333
13334         if (INTEL_GEN(dev_priv) >= 9)
13335                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13336                                                      primary->pipe,
13337                                                      primary->id);
13338         else
13339                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13340                                                       primary->i9xx_plane);
13341
13342         if (primary->has_fbc) {
13343                 struct intel_fbc *fbc = &dev_priv->fbc;
13344
13345                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13346         }
13347
13348         primary->check_plane = intel_check_primary_plane;
13349
13350         if (INTEL_GEN(dev_priv) >= 9) {
13351                 intel_primary_formats = skl_primary_formats;
13352                 num_formats = ARRAY_SIZE(skl_primary_formats);
13353
13354                 if (skl_plane_has_ccs(dev_priv, pipe, PLANE_PRIMARY))
13355                         modifiers = skl_format_modifiers_ccs;
13356                 else
13357                         modifiers = skl_format_modifiers_noccs;
13358
13359                 primary->update_plane = skl_update_plane;
13360                 primary->disable_plane = skl_disable_plane;
13361                 primary->get_hw_state = skl_plane_get_hw_state;
13362         } else if (INTEL_GEN(dev_priv) >= 4) {
13363                 intel_primary_formats = i965_primary_formats;
13364                 num_formats = ARRAY_SIZE(i965_primary_formats);
13365                 modifiers = i9xx_format_modifiers;
13366
13367                 primary->update_plane = i9xx_update_plane;
13368                 primary->disable_plane = i9xx_disable_plane;
13369                 primary->get_hw_state = i9xx_plane_get_hw_state;
13370         } else {
13371                 intel_primary_formats = i8xx_primary_formats;
13372                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13373                 modifiers = i9xx_format_modifiers;
13374
13375                 primary->update_plane = i9xx_update_plane;
13376                 primary->disable_plane = i9xx_disable_plane;
13377                 primary->get_hw_state = i9xx_plane_get_hw_state;
13378         }
13379
13380         if (INTEL_GEN(dev_priv) >= 9)
13381                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13382                                                0, &intel_plane_funcs,
13383                                                intel_primary_formats, num_formats,
13384                                                modifiers,
13385                                                DRM_PLANE_TYPE_PRIMARY,
13386                                                "plane 1%c", pipe_name(pipe));
13387         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13388                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13389                                                0, &intel_plane_funcs,
13390                                                intel_primary_formats, num_formats,
13391                                                modifiers,
13392                                                DRM_PLANE_TYPE_PRIMARY,
13393                                                "primary %c", pipe_name(pipe));
13394         else
13395                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13396                                                0, &intel_plane_funcs,
13397                                                intel_primary_formats, num_formats,
13398                                                modifiers,
13399                                                DRM_PLANE_TYPE_PRIMARY,
13400                                                "plane %c",
13401                                                plane_name(primary->i9xx_plane));
13402         if (ret)
13403                 goto fail;
13404
13405         if (INTEL_GEN(dev_priv) >= 10) {
13406                 supported_rotations =
13407                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13408                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13409                         DRM_MODE_REFLECT_X;
13410         } else if (INTEL_GEN(dev_priv) >= 9) {
13411                 supported_rotations =
13412                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13413                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13414         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13415                 supported_rotations =
13416                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13417                         DRM_MODE_REFLECT_X;
13418         } else if (INTEL_GEN(dev_priv) >= 4) {
13419                 supported_rotations =
13420                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13421         } else {
13422                 supported_rotations = DRM_MODE_ROTATE_0;
13423         }
13424
13425         if (INTEL_GEN(dev_priv) >= 4)
13426                 drm_plane_create_rotation_property(&primary->base,
13427                                                    DRM_MODE_ROTATE_0,
13428                                                    supported_rotations);
13429
13430         if (INTEL_GEN(dev_priv) >= 9)
13431                 drm_plane_create_color_properties(&primary->base,
13432                                                   BIT(DRM_COLOR_YCBCR_BT601) |
13433                                                   BIT(DRM_COLOR_YCBCR_BT709),
13434                                                   BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
13435                                                   BIT(DRM_COLOR_YCBCR_FULL_RANGE),
13436                                                   DRM_COLOR_YCBCR_BT709,
13437                                                   DRM_COLOR_YCBCR_LIMITED_RANGE);
13438
13439         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13440
13441         return primary;
13442
13443 fail:
13444         kfree(state);
13445         kfree(primary);
13446
13447         return ERR_PTR(ret);
13448 }
13449
13450 static struct intel_plane *
13451 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13452                           enum pipe pipe)
13453 {
13454         struct intel_plane *cursor = NULL;
13455         struct intel_plane_state *state = NULL;
13456         int ret;
13457
13458         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13459         if (!cursor) {
13460                 ret = -ENOMEM;
13461                 goto fail;
13462         }
13463
13464         state = intel_create_plane_state(&cursor->base);
13465         if (!state) {
13466                 ret = -ENOMEM;
13467                 goto fail;
13468         }
13469
13470         cursor->base.state = &state->base;
13471
13472         cursor->can_scale = false;
13473         cursor->max_downscale = 1;
13474         cursor->pipe = pipe;
13475         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13476         cursor->id = PLANE_CURSOR;
13477         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13478
13479         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13480                 cursor->update_plane = i845_update_cursor;
13481                 cursor->disable_plane = i845_disable_cursor;
13482                 cursor->get_hw_state = i845_cursor_get_hw_state;
13483                 cursor->check_plane = i845_check_cursor;
13484         } else {
13485                 cursor->update_plane = i9xx_update_cursor;
13486                 cursor->disable_plane = i9xx_disable_cursor;
13487                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13488                 cursor->check_plane = i9xx_check_cursor;
13489         }
13490
13491         cursor->cursor.base = ~0;
13492         cursor->cursor.cntl = ~0;
13493
13494         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13495                 cursor->cursor.size = ~0;
13496
13497         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13498                                        0, &intel_cursor_plane_funcs,
13499                                        intel_cursor_formats,
13500                                        ARRAY_SIZE(intel_cursor_formats),
13501                                        cursor_format_modifiers,
13502                                        DRM_PLANE_TYPE_CURSOR,
13503                                        "cursor %c", pipe_name(pipe));
13504         if (ret)
13505                 goto fail;
13506
13507         if (INTEL_GEN(dev_priv) >= 4)
13508                 drm_plane_create_rotation_property(&cursor->base,
13509                                                    DRM_MODE_ROTATE_0,
13510                                                    DRM_MODE_ROTATE_0 |
13511                                                    DRM_MODE_ROTATE_180);
13512
13513         if (INTEL_GEN(dev_priv) >= 9)
13514                 state->scaler_id = -1;
13515
13516         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13517
13518         return cursor;
13519
13520 fail:
13521         kfree(state);
13522         kfree(cursor);
13523
13524         return ERR_PTR(ret);
13525 }
13526
13527 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13528                                     struct intel_crtc_state *crtc_state)
13529 {
13530         struct intel_crtc_scaler_state *scaler_state =
13531                 &crtc_state->scaler_state;
13532         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13533         int i;
13534
13535         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13536         if (!crtc->num_scalers)
13537                 return;
13538
13539         for (i = 0; i < crtc->num_scalers; i++) {
13540                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13541
13542                 scaler->in_use = 0;
13543                 scaler->mode = PS_SCALER_MODE_DYN;
13544         }
13545
13546         scaler_state->scaler_id = -1;
13547 }
13548
13549 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13550 {
13551         struct intel_crtc *intel_crtc;
13552         struct intel_crtc_state *crtc_state = NULL;
13553         struct intel_plane *primary = NULL;
13554         struct intel_plane *cursor = NULL;
13555         int sprite, ret;
13556
13557         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13558         if (!intel_crtc)
13559                 return -ENOMEM;
13560
13561         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13562         if (!crtc_state) {
13563                 ret = -ENOMEM;
13564                 goto fail;
13565         }
13566         intel_crtc->config = crtc_state;
13567         intel_crtc->base.state = &crtc_state->base;
13568         crtc_state->base.crtc = &intel_crtc->base;
13569
13570         primary = intel_primary_plane_create(dev_priv, pipe);
13571         if (IS_ERR(primary)) {
13572                 ret = PTR_ERR(primary);
13573                 goto fail;
13574         }
13575         intel_crtc->plane_ids_mask |= BIT(primary->id);
13576
13577         for_each_sprite(dev_priv, pipe, sprite) {
13578                 struct intel_plane *plane;
13579
13580                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13581                 if (IS_ERR(plane)) {
13582                         ret = PTR_ERR(plane);
13583                         goto fail;
13584                 }
13585                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13586         }
13587
13588         cursor = intel_cursor_plane_create(dev_priv, pipe);
13589         if (IS_ERR(cursor)) {
13590                 ret = PTR_ERR(cursor);
13591                 goto fail;
13592         }
13593         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13594
13595         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13596                                         &primary->base, &cursor->base,
13597                                         &intel_crtc_funcs,
13598                                         "pipe %c", pipe_name(pipe));
13599         if (ret)
13600                 goto fail;
13601
13602         intel_crtc->pipe = pipe;
13603
13604         /* initialize shared scalers */
13605         intel_crtc_init_scalers(intel_crtc, crtc_state);
13606
13607         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
13608                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
13609         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
13610
13611         if (INTEL_GEN(dev_priv) < 9) {
13612                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
13613
13614                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13615                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
13616                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
13617         }
13618
13619         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13620
13621         intel_color_init(&intel_crtc->base);
13622
13623         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13624
13625         return 0;
13626
13627 fail:
13628         /*
13629          * drm_mode_config_cleanup() will free up any
13630          * crtcs/planes already initialized.
13631          */
13632         kfree(crtc_state);
13633         kfree(intel_crtc);
13634
13635         return ret;
13636 }
13637
13638 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13639 {
13640         struct drm_device *dev = connector->base.dev;
13641
13642         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13643
13644         if (!connector->base.state->crtc)
13645                 return INVALID_PIPE;
13646
13647         return to_intel_crtc(connector->base.state->crtc)->pipe;
13648 }
13649
13650 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
13651                                       struct drm_file *file)
13652 {
13653         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13654         struct drm_crtc *drmmode_crtc;
13655         struct intel_crtc *crtc;
13656
13657         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13658         if (!drmmode_crtc)
13659                 return -ENOENT;
13660
13661         crtc = to_intel_crtc(drmmode_crtc);
13662         pipe_from_crtc_id->pipe = crtc->pipe;
13663
13664         return 0;
13665 }
13666
13667 static int intel_encoder_clones(struct intel_encoder *encoder)
13668 {
13669         struct drm_device *dev = encoder->base.dev;
13670         struct intel_encoder *source_encoder;
13671         int index_mask = 0;
13672         int entry = 0;
13673
13674         for_each_intel_encoder(dev, source_encoder) {
13675                 if (encoders_cloneable(encoder, source_encoder))
13676                         index_mask |= (1 << entry);
13677
13678                 entry++;
13679         }
13680
13681         return index_mask;
13682 }
13683
13684 static bool has_edp_a(struct drm_i915_private *dev_priv)
13685 {
13686         if (!IS_MOBILE(dev_priv))
13687                 return false;
13688
13689         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13690                 return false;
13691
13692         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13693                 return false;
13694
13695         return true;
13696 }
13697
13698 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13699 {
13700         if (INTEL_GEN(dev_priv) >= 9)
13701                 return false;
13702
13703         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13704                 return false;
13705
13706         if (IS_CHERRYVIEW(dev_priv))
13707                 return false;
13708
13709         if (HAS_PCH_LPT_H(dev_priv) &&
13710             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13711                 return false;
13712
13713         /* DDI E can't be used if DDI A requires 4 lanes */
13714         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13715                 return false;
13716
13717         if (!dev_priv->vbt.int_crt_support)
13718                 return false;
13719
13720         return true;
13721 }
13722
13723 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13724 {
13725         int pps_num;
13726         int pps_idx;
13727
13728         if (HAS_DDI(dev_priv))
13729                 return;
13730         /*
13731          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13732          * everywhere where registers can be write protected.
13733          */
13734         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13735                 pps_num = 2;
13736         else
13737                 pps_num = 1;
13738
13739         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13740                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13741
13742                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13743                 I915_WRITE(PP_CONTROL(pps_idx), val);
13744         }
13745 }
13746
13747 static void intel_pps_init(struct drm_i915_private *dev_priv)
13748 {
13749         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13750                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13751         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13752                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13753         else
13754                 dev_priv->pps_mmio_base = PPS_BASE;
13755
13756         intel_pps_unlock_regs_wa(dev_priv);
13757 }
13758
13759 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13760 {
13761         struct intel_encoder *encoder;
13762         bool dpd_is_edp = false;
13763
13764         intel_pps_init(dev_priv);
13765
13766         /*
13767          * intel_edp_init_connector() depends on this completing first, to
13768          * prevent the registeration of both eDP and LVDS and the incorrect
13769          * sharing of the PPS.
13770          */
13771         intel_lvds_init(dev_priv);
13772
13773         if (intel_crt_present(dev_priv))
13774                 intel_crt_init(dev_priv);
13775
13776         if (IS_GEN9_LP(dev_priv)) {
13777                 /*
13778                  * FIXME: Broxton doesn't support port detection via the
13779                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13780                  * detect the ports.
13781                  */
13782                 intel_ddi_init(dev_priv, PORT_A);
13783                 intel_ddi_init(dev_priv, PORT_B);
13784                 intel_ddi_init(dev_priv, PORT_C);
13785
13786                 intel_dsi_init(dev_priv);
13787         } else if (HAS_DDI(dev_priv)) {
13788                 int found;
13789
13790                 /*
13791                  * Haswell uses DDI functions to detect digital outputs.
13792                  * On SKL pre-D0 the strap isn't connected, so we assume
13793                  * it's there.
13794                  */
13795                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13796                 /* WaIgnoreDDIAStrap: skl */
13797                 if (found || IS_GEN9_BC(dev_priv))
13798                         intel_ddi_init(dev_priv, PORT_A);
13799
13800                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
13801                  * register */
13802                 found = I915_READ(SFUSE_STRAP);
13803
13804                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13805                         intel_ddi_init(dev_priv, PORT_B);
13806                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13807                         intel_ddi_init(dev_priv, PORT_C);
13808                 if (found & SFUSE_STRAP_DDID_DETECTED)
13809                         intel_ddi_init(dev_priv, PORT_D);
13810                 if (found & SFUSE_STRAP_DDIF_DETECTED)
13811                         intel_ddi_init(dev_priv, PORT_F);
13812                 /*
13813                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13814                  */
13815                 if (IS_GEN9_BC(dev_priv) &&
13816                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13817                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13818                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13819                         intel_ddi_init(dev_priv, PORT_E);
13820
13821         } else if (HAS_PCH_SPLIT(dev_priv)) {
13822                 int found;
13823                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
13824
13825                 if (has_edp_a(dev_priv))
13826                         intel_dp_init(dev_priv, DP_A, PORT_A);
13827
13828                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13829                         /* PCH SDVOB multiplex with HDMIB */
13830                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
13831                         if (!found)
13832                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
13833                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13834                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
13835                 }
13836
13837                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13838                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
13839
13840                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13841                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
13842
13843                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13844                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
13845
13846                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13847                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
13848         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
13849                 bool has_edp, has_port;
13850
13851                 /*
13852                  * The DP_DETECTED bit is the latched state of the DDC
13853                  * SDA pin at boot. However since eDP doesn't require DDC
13854                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13855                  * eDP ports may have been muxed to an alternate function.
13856                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13857                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13858                  * detect eDP ports.
13859                  *
13860                  * Sadly the straps seem to be missing sometimes even for HDMI
13861                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
13862                  * and VBT for the presence of the port. Additionally we can't
13863                  * trust the port type the VBT declares as we've seen at least
13864                  * HDMI ports that the VBT claim are DP or eDP.
13865                  */
13866                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
13867                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
13868                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
13869                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
13870                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
13871                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
13872
13873                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
13874                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
13875                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
13876                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
13877                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
13878                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
13879
13880                 if (IS_CHERRYVIEW(dev_priv)) {
13881                         /*
13882                          * eDP not supported on port D,
13883                          * so no need to worry about it
13884                          */
13885                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
13886                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
13887                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
13888                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
13889                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
13890                 }
13891
13892                 intel_dsi_init(dev_priv);
13893         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
13894                 bool found = false;
13895
13896                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13897                         DRM_DEBUG_KMS("probing SDVOB\n");
13898                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
13899                         if (!found && IS_G4X(dev_priv)) {
13900                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13901                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
13902                         }
13903
13904                         if (!found && IS_G4X(dev_priv))
13905                                 intel_dp_init(dev_priv, DP_B, PORT_B);
13906                 }
13907
13908                 /* Before G4X SDVOC doesn't have its own detect register */
13909
13910                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13911                         DRM_DEBUG_KMS("probing SDVOC\n");
13912                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
13913                 }
13914
13915                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13916
13917                         if (IS_G4X(dev_priv)) {
13918                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13919                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
13920                         }
13921                         if (IS_G4X(dev_priv))
13922                                 intel_dp_init(dev_priv, DP_C, PORT_C);
13923                 }
13924
13925                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
13926                         intel_dp_init(dev_priv, DP_D, PORT_D);
13927         } else if (IS_GEN2(dev_priv))
13928                 intel_dvo_init(dev_priv);
13929
13930         if (SUPPORTS_TV(dev_priv))
13931                 intel_tv_init(dev_priv);
13932
13933         intel_psr_init(dev_priv);
13934
13935         for_each_intel_encoder(&dev_priv->drm, encoder) {
13936                 encoder->base.possible_crtcs = encoder->crtc_mask;
13937                 encoder->base.possible_clones =
13938                         intel_encoder_clones(encoder);
13939         }
13940
13941         intel_init_pch_refclk(dev_priv);
13942
13943         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
13944 }
13945
13946 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13947 {
13948         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13949
13950         drm_framebuffer_cleanup(fb);
13951
13952         i915_gem_object_lock(intel_fb->obj);
13953         WARN_ON(!intel_fb->obj->framebuffer_references--);
13954         i915_gem_object_unlock(intel_fb->obj);
13955
13956         i915_gem_object_put(intel_fb->obj);
13957
13958         kfree(intel_fb);
13959 }
13960
13961 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13962                                                 struct drm_file *file,
13963                                                 unsigned int *handle)
13964 {
13965         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13966         struct drm_i915_gem_object *obj = intel_fb->obj;
13967
13968         if (obj->userptr.mm) {
13969                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
13970                 return -EINVAL;
13971         }
13972
13973         return drm_gem_handle_create(file, &obj->base, handle);
13974 }
13975
13976 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
13977                                         struct drm_file *file,
13978                                         unsigned flags, unsigned color,
13979                                         struct drm_clip_rect *clips,
13980                                         unsigned num_clips)
13981 {
13982         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13983
13984         i915_gem_object_flush_if_display(obj);
13985         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13986
13987         return 0;
13988 }
13989
13990 static const struct drm_framebuffer_funcs intel_fb_funcs = {
13991         .destroy = intel_user_framebuffer_destroy,
13992         .create_handle = intel_user_framebuffer_create_handle,
13993         .dirty = intel_user_framebuffer_dirty,
13994 };
13995
13996 static
13997 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
13998                          uint64_t fb_modifier, uint32_t pixel_format)
13999 {
14000         u32 gen = INTEL_GEN(dev_priv);
14001
14002         if (gen >= 9) {
14003                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14004
14005                 /* "The stride in bytes must not exceed the of the size of 8K
14006                  *  pixels and 32K bytes."
14007                  */
14008                 return min(8192 * cpp, 32768);
14009         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
14010                 return 32*1024;
14011         } else if (gen >= 4) {
14012                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14013                         return 16*1024;
14014                 else
14015                         return 32*1024;
14016         } else if (gen >= 3) {
14017                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14018                         return 8*1024;
14019                 else
14020                         return 16*1024;
14021         } else {
14022                 /* XXX DSPC is limited to 4k tiled */
14023                 return 8*1024;
14024         }
14025 }
14026
14027 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14028                                   struct drm_i915_gem_object *obj,
14029                                   struct drm_mode_fb_cmd2 *mode_cmd)
14030 {
14031         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14032         struct drm_framebuffer *fb = &intel_fb->base;
14033         struct drm_format_name_buf format_name;
14034         u32 pitch_limit;
14035         unsigned int tiling, stride;
14036         int ret = -EINVAL;
14037         int i;
14038
14039         i915_gem_object_lock(obj);
14040         obj->framebuffer_references++;
14041         tiling = i915_gem_object_get_tiling(obj);
14042         stride = i915_gem_object_get_stride(obj);
14043         i915_gem_object_unlock(obj);
14044
14045         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14046                 /*
14047                  * If there's a fence, enforce that
14048                  * the fb modifier and tiling mode match.
14049                  */
14050                 if (tiling != I915_TILING_NONE &&
14051                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14052                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14053                         goto err;
14054                 }
14055         } else {
14056                 if (tiling == I915_TILING_X) {
14057                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14058                 } else if (tiling == I915_TILING_Y) {
14059                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14060                         goto err;
14061                 }
14062         }
14063
14064         /* Passed in modifier sanity checking. */
14065         switch (mode_cmd->modifier[0]) {
14066         case I915_FORMAT_MOD_Y_TILED_CCS:
14067         case I915_FORMAT_MOD_Yf_TILED_CCS:
14068                 switch (mode_cmd->pixel_format) {
14069                 case DRM_FORMAT_XBGR8888:
14070                 case DRM_FORMAT_ABGR8888:
14071                 case DRM_FORMAT_XRGB8888:
14072                 case DRM_FORMAT_ARGB8888:
14073                         break;
14074                 default:
14075                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14076                         goto err;
14077                 }
14078                 /* fall through */
14079         case I915_FORMAT_MOD_Y_TILED:
14080         case I915_FORMAT_MOD_Yf_TILED:
14081                 if (INTEL_GEN(dev_priv) < 9) {
14082                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14083                                       mode_cmd->modifier[0]);
14084                         goto err;
14085                 }
14086         case DRM_FORMAT_MOD_LINEAR:
14087         case I915_FORMAT_MOD_X_TILED:
14088                 break;
14089         default:
14090                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14091                               mode_cmd->modifier[0]);
14092                 goto err;
14093         }
14094
14095         /*
14096          * gen2/3 display engine uses the fence if present,
14097          * so the tiling mode must match the fb modifier exactly.
14098          */
14099         if (INTEL_GEN(dev_priv) < 4 &&
14100             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14101                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14102                 goto err;
14103         }
14104
14105         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14106                                            mode_cmd->pixel_format);
14107         if (mode_cmd->pitches[0] > pitch_limit) {
14108                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14109                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14110                               "tiled" : "linear",
14111                               mode_cmd->pitches[0], pitch_limit);
14112                 goto err;
14113         }
14114
14115         /*
14116          * If there's a fence, enforce that
14117          * the fb pitch and fence stride match.
14118          */
14119         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14120                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14121                               mode_cmd->pitches[0], stride);
14122                 goto err;
14123         }
14124
14125         /* Reject formats not supported by any plane early. */
14126         switch (mode_cmd->pixel_format) {
14127         case DRM_FORMAT_C8:
14128         case DRM_FORMAT_RGB565:
14129         case DRM_FORMAT_XRGB8888:
14130         case DRM_FORMAT_ARGB8888:
14131                 break;
14132         case DRM_FORMAT_XRGB1555:
14133                 if (INTEL_GEN(dev_priv) > 3) {
14134                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14135                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14136                         goto err;
14137                 }
14138                 break;
14139         case DRM_FORMAT_ABGR8888:
14140                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14141                     INTEL_GEN(dev_priv) < 9) {
14142                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14143                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14144                         goto err;
14145                 }
14146                 break;
14147         case DRM_FORMAT_XBGR8888:
14148         case DRM_FORMAT_XRGB2101010:
14149         case DRM_FORMAT_XBGR2101010:
14150                 if (INTEL_GEN(dev_priv) < 4) {
14151                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14152                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14153                         goto err;
14154                 }
14155                 break;
14156         case DRM_FORMAT_ABGR2101010:
14157                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14158                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14159                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14160                         goto err;
14161                 }
14162                 break;
14163         case DRM_FORMAT_YUYV:
14164         case DRM_FORMAT_UYVY:
14165         case DRM_FORMAT_YVYU:
14166         case DRM_FORMAT_VYUY:
14167                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14168                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14169                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14170                         goto err;
14171                 }
14172                 break;
14173         default:
14174                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14175                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14176                 goto err;
14177         }
14178
14179         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14180         if (mode_cmd->offsets[0] != 0)
14181                 goto err;
14182
14183         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14184
14185         for (i = 0; i < fb->format->num_planes; i++) {
14186                 u32 stride_alignment;
14187
14188                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14189                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14190                         goto err;
14191                 }
14192
14193                 stride_alignment = intel_fb_stride_alignment(fb, i);
14194
14195                 /*
14196                  * Display WA #0531: skl,bxt,kbl,glk
14197                  *
14198                  * Render decompression and plane width > 3840
14199                  * combined with horizontal panning requires the
14200                  * plane stride to be a multiple of 4. We'll just
14201                  * require the entire fb to accommodate that to avoid
14202                  * potential runtime errors at plane configuration time.
14203                  */
14204                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14205                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14206                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14207                         stride_alignment *= 4;
14208
14209                 if (fb->pitches[i] & (stride_alignment - 1)) {
14210                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14211                                       i, fb->pitches[i], stride_alignment);
14212                         goto err;
14213                 }
14214         }
14215
14216         intel_fb->obj = obj;
14217
14218         ret = intel_fill_fb_info(dev_priv, fb);
14219         if (ret)
14220                 goto err;
14221
14222         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14223         if (ret) {
14224                 DRM_ERROR("framebuffer init failed %d\n", ret);
14225                 goto err;
14226         }
14227
14228         return 0;
14229
14230 err:
14231         i915_gem_object_lock(obj);
14232         obj->framebuffer_references--;
14233         i915_gem_object_unlock(obj);
14234         return ret;
14235 }
14236
14237 static struct drm_framebuffer *
14238 intel_user_framebuffer_create(struct drm_device *dev,
14239                               struct drm_file *filp,
14240                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14241 {
14242         struct drm_framebuffer *fb;
14243         struct drm_i915_gem_object *obj;
14244         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14245
14246         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14247         if (!obj)
14248                 return ERR_PTR(-ENOENT);
14249
14250         fb = intel_framebuffer_create(obj, &mode_cmd);
14251         if (IS_ERR(fb))
14252                 i915_gem_object_put(obj);
14253
14254         return fb;
14255 }
14256
14257 static void intel_atomic_state_free(struct drm_atomic_state *state)
14258 {
14259         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14260
14261         drm_atomic_state_default_release(state);
14262
14263         i915_sw_fence_fini(&intel_state->commit_ready);
14264
14265         kfree(state);
14266 }
14267
14268 static enum drm_mode_status
14269 intel_mode_valid(struct drm_device *dev,
14270                  const struct drm_display_mode *mode)
14271 {
14272         if (mode->vscan > 1)
14273                 return MODE_NO_VSCAN;
14274
14275         if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
14276                 return MODE_NO_DBLESCAN;
14277
14278         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14279                 return MODE_H_ILLEGAL;
14280
14281         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14282                            DRM_MODE_FLAG_NCSYNC |
14283                            DRM_MODE_FLAG_PCSYNC))
14284                 return MODE_HSYNC;
14285
14286         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14287                            DRM_MODE_FLAG_PIXMUX |
14288                            DRM_MODE_FLAG_CLKDIV2))
14289                 return MODE_BAD;
14290
14291         return MODE_OK;
14292 }
14293
14294 static const struct drm_mode_config_funcs intel_mode_funcs = {
14295         .fb_create = intel_user_framebuffer_create,
14296         .get_format_info = intel_get_format_info,
14297         .output_poll_changed = intel_fbdev_output_poll_changed,
14298         .mode_valid = intel_mode_valid,
14299         .atomic_check = intel_atomic_check,
14300         .atomic_commit = intel_atomic_commit,
14301         .atomic_state_alloc = intel_atomic_state_alloc,
14302         .atomic_state_clear = intel_atomic_state_clear,
14303         .atomic_state_free = intel_atomic_state_free,
14304 };
14305
14306 /**
14307  * intel_init_display_hooks - initialize the display modesetting hooks
14308  * @dev_priv: device private
14309  */
14310 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14311 {
14312         intel_init_cdclk_hooks(dev_priv);
14313
14314         if (INTEL_GEN(dev_priv) >= 9) {
14315                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14316                 dev_priv->display.get_initial_plane_config =
14317                         skylake_get_initial_plane_config;
14318                 dev_priv->display.crtc_compute_clock =
14319                         haswell_crtc_compute_clock;
14320                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14321                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14322         } else if (HAS_DDI(dev_priv)) {
14323                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14324                 dev_priv->display.get_initial_plane_config =
14325                         i9xx_get_initial_plane_config;
14326                 dev_priv->display.crtc_compute_clock =
14327                         haswell_crtc_compute_clock;
14328                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14329                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14330         } else if (HAS_PCH_SPLIT(dev_priv)) {
14331                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14332                 dev_priv->display.get_initial_plane_config =
14333                         i9xx_get_initial_plane_config;
14334                 dev_priv->display.crtc_compute_clock =
14335                         ironlake_crtc_compute_clock;
14336                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14337                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14338         } else if (IS_CHERRYVIEW(dev_priv)) {
14339                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14340                 dev_priv->display.get_initial_plane_config =
14341                         i9xx_get_initial_plane_config;
14342                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14343                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14344                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14345         } else if (IS_VALLEYVIEW(dev_priv)) {
14346                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14347                 dev_priv->display.get_initial_plane_config =
14348                         i9xx_get_initial_plane_config;
14349                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14350                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14351                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14352         } else if (IS_G4X(dev_priv)) {
14353                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14354                 dev_priv->display.get_initial_plane_config =
14355                         i9xx_get_initial_plane_config;
14356                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14357                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14358                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14359         } else if (IS_PINEVIEW(dev_priv)) {
14360                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14361                 dev_priv->display.get_initial_plane_config =
14362                         i9xx_get_initial_plane_config;
14363                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14364                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14365                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14366         } else if (!IS_GEN2(dev_priv)) {
14367                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14368                 dev_priv->display.get_initial_plane_config =
14369                         i9xx_get_initial_plane_config;
14370                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14371                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14372                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14373         } else {
14374                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14375                 dev_priv->display.get_initial_plane_config =
14376                         i9xx_get_initial_plane_config;
14377                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14378                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14379                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14380         }
14381
14382         if (IS_GEN5(dev_priv)) {
14383                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14384         } else if (IS_GEN6(dev_priv)) {
14385                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14386         } else if (IS_IVYBRIDGE(dev_priv)) {
14387                 /* FIXME: detect B0+ stepping and use auto training */
14388                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14389         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14390                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14391         }
14392
14393         if (INTEL_GEN(dev_priv) >= 9)
14394                 dev_priv->display.update_crtcs = skl_update_crtcs;
14395         else
14396                 dev_priv->display.update_crtcs = intel_update_crtcs;
14397 }
14398
14399 /*
14400  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14401  */
14402 static void quirk_ssc_force_disable(struct drm_device *dev)
14403 {
14404         struct drm_i915_private *dev_priv = to_i915(dev);
14405         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14406         DRM_INFO("applying lvds SSC disable quirk\n");
14407 }
14408
14409 /*
14410  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14411  * brightness value
14412  */
14413 static void quirk_invert_brightness(struct drm_device *dev)
14414 {
14415         struct drm_i915_private *dev_priv = to_i915(dev);
14416         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14417         DRM_INFO("applying inverted panel brightness quirk\n");
14418 }
14419
14420 /* Some VBT's incorrectly indicate no backlight is present */
14421 static void quirk_backlight_present(struct drm_device *dev)
14422 {
14423         struct drm_i915_private *dev_priv = to_i915(dev);
14424         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14425         DRM_INFO("applying backlight present quirk\n");
14426 }
14427
14428 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14429  * which is 300 ms greater than eDP spec T12 min.
14430  */
14431 static void quirk_increase_t12_delay(struct drm_device *dev)
14432 {
14433         struct drm_i915_private *dev_priv = to_i915(dev);
14434
14435         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14436         DRM_INFO("Applying T12 delay quirk\n");
14437 }
14438
14439 struct intel_quirk {
14440         int device;
14441         int subsystem_vendor;
14442         int subsystem_device;
14443         void (*hook)(struct drm_device *dev);
14444 };
14445
14446 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14447 struct intel_dmi_quirk {
14448         void (*hook)(struct drm_device *dev);
14449         const struct dmi_system_id (*dmi_id_list)[];
14450 };
14451
14452 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14453 {
14454         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14455         return 1;
14456 }
14457
14458 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14459         {
14460                 .dmi_id_list = &(const struct dmi_system_id[]) {
14461                         {
14462                                 .callback = intel_dmi_reverse_brightness,
14463                                 .ident = "NCR Corporation",
14464                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14465                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14466                                 },
14467                         },
14468                         { }  /* terminating entry */
14469                 },
14470                 .hook = quirk_invert_brightness,
14471         },
14472 };
14473
14474 static struct intel_quirk intel_quirks[] = {
14475         /* Lenovo U160 cannot use SSC on LVDS */
14476         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14477
14478         /* Sony Vaio Y cannot use SSC on LVDS */
14479         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14480
14481         /* Acer Aspire 5734Z must invert backlight brightness */
14482         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14483
14484         /* Acer/eMachines G725 */
14485         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14486
14487         /* Acer/eMachines e725 */
14488         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14489
14490         /* Acer/Packard Bell NCL20 */
14491         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14492
14493         /* Acer Aspire 4736Z */
14494         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14495
14496         /* Acer Aspire 5336 */
14497         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14498
14499         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14500         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14501
14502         /* Acer C720 Chromebook (Core i3 4005U) */
14503         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14504
14505         /* Apple Macbook 2,1 (Core 2 T7400) */
14506         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14507
14508         /* Apple Macbook 4,1 */
14509         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14510
14511         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14512         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14513
14514         /* HP Chromebook 14 (Celeron 2955U) */
14515         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14516
14517         /* Dell Chromebook 11 */
14518         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14519
14520         /* Dell Chromebook 11 (2015 version) */
14521         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14522
14523         /* Toshiba Satellite P50-C-18C */
14524         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14525 };
14526
14527 static void intel_init_quirks(struct drm_device *dev)
14528 {
14529         struct pci_dev *d = dev->pdev;
14530         int i;
14531
14532         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14533                 struct intel_quirk *q = &intel_quirks[i];
14534
14535                 if (d->device == q->device &&
14536                     (d->subsystem_vendor == q->subsystem_vendor ||
14537                      q->subsystem_vendor == PCI_ANY_ID) &&
14538                     (d->subsystem_device == q->subsystem_device ||
14539                      q->subsystem_device == PCI_ANY_ID))
14540                         q->hook(dev);
14541         }
14542         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14543                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14544                         intel_dmi_quirks[i].hook(dev);
14545         }
14546 }
14547
14548 /* Disable the VGA plane that we never use */
14549 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14550 {
14551         struct pci_dev *pdev = dev_priv->drm.pdev;
14552         u8 sr1;
14553         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14554
14555         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14556         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14557         outb(SR01, VGA_SR_INDEX);
14558         sr1 = inb(VGA_SR_DATA);
14559         outb(sr1 | 1<<5, VGA_SR_DATA);
14560         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14561         udelay(300);
14562
14563         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14564         POSTING_READ(vga_reg);
14565 }
14566
14567 void intel_modeset_init_hw(struct drm_device *dev)
14568 {
14569         struct drm_i915_private *dev_priv = to_i915(dev);
14570
14571         intel_update_cdclk(dev_priv);
14572         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14573         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14574 }
14575
14576 /*
14577  * Calculate what we think the watermarks should be for the state we've read
14578  * out of the hardware and then immediately program those watermarks so that
14579  * we ensure the hardware settings match our internal state.
14580  *
14581  * We can calculate what we think WM's should be by creating a duplicate of the
14582  * current state (which was constructed during hardware readout) and running it
14583  * through the atomic check code to calculate new watermark values in the
14584  * state object.
14585  */
14586 static void sanitize_watermarks(struct drm_device *dev)
14587 {
14588         struct drm_i915_private *dev_priv = to_i915(dev);
14589         struct drm_atomic_state *state;
14590         struct intel_atomic_state *intel_state;
14591         struct drm_crtc *crtc;
14592         struct drm_crtc_state *cstate;
14593         struct drm_modeset_acquire_ctx ctx;
14594         int ret;
14595         int i;
14596
14597         /* Only supported on platforms that use atomic watermark design */
14598         if (!dev_priv->display.optimize_watermarks)
14599                 return;
14600
14601         /*
14602          * We need to hold connection_mutex before calling duplicate_state so
14603          * that the connector loop is protected.
14604          */
14605         drm_modeset_acquire_init(&ctx, 0);
14606 retry:
14607         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14608         if (ret == -EDEADLK) {
14609                 drm_modeset_backoff(&ctx);
14610                 goto retry;
14611         } else if (WARN_ON(ret)) {
14612                 goto fail;
14613         }
14614
14615         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14616         if (WARN_ON(IS_ERR(state)))
14617                 goto fail;
14618
14619         intel_state = to_intel_atomic_state(state);
14620
14621         /*
14622          * Hardware readout is the only time we don't want to calculate
14623          * intermediate watermarks (since we don't trust the current
14624          * watermarks).
14625          */
14626         if (!HAS_GMCH_DISPLAY(dev_priv))
14627                 intel_state->skip_intermediate_wm = true;
14628
14629         ret = intel_atomic_check(dev, state);
14630         if (ret) {
14631                 /*
14632                  * If we fail here, it means that the hardware appears to be
14633                  * programmed in a way that shouldn't be possible, given our
14634                  * understanding of watermark requirements.  This might mean a
14635                  * mistake in the hardware readout code or a mistake in the
14636                  * watermark calculations for a given platform.  Raise a WARN
14637                  * so that this is noticeable.
14638                  *
14639                  * If this actually happens, we'll have to just leave the
14640                  * BIOS-programmed watermarks untouched and hope for the best.
14641                  */
14642                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14643                 goto put_state;
14644         }
14645
14646         /* Write calculated watermark values back */
14647         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14648                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14649
14650                 cs->wm.need_postvbl_update = true;
14651                 dev_priv->display.optimize_watermarks(intel_state, cs);
14652
14653                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14654         }
14655
14656 put_state:
14657         drm_atomic_state_put(state);
14658 fail:
14659         drm_modeset_drop_locks(&ctx);
14660         drm_modeset_acquire_fini(&ctx);
14661 }
14662
14663 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14664 {
14665         if (IS_GEN5(dev_priv)) {
14666                 u32 fdi_pll_clk =
14667                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14668
14669                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14670         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14671                 dev_priv->fdi_pll_freq = 270000;
14672         } else {
14673                 return;
14674         }
14675
14676         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14677 }
14678
14679 int intel_modeset_init(struct drm_device *dev)
14680 {
14681         struct drm_i915_private *dev_priv = to_i915(dev);
14682         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14683         enum pipe pipe;
14684         struct intel_crtc *crtc;
14685
14686         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
14687
14688         drm_mode_config_init(dev);
14689
14690         dev->mode_config.min_width = 0;
14691         dev->mode_config.min_height = 0;
14692
14693         dev->mode_config.preferred_depth = 24;
14694         dev->mode_config.prefer_shadow = 1;
14695
14696         dev->mode_config.allow_fb_modifiers = true;
14697
14698         dev->mode_config.funcs = &intel_mode_funcs;
14699
14700         init_llist_head(&dev_priv->atomic_helper.free_list);
14701         INIT_WORK(&dev_priv->atomic_helper.free_work,
14702                   intel_atomic_helper_free_state_worker);
14703
14704         intel_init_quirks(dev);
14705
14706         intel_init_pm(dev_priv);
14707
14708         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14709                 return 0;
14710
14711         /*
14712          * There may be no VBT; and if the BIOS enabled SSC we can
14713          * just keep using it to avoid unnecessary flicker.  Whereas if the
14714          * BIOS isn't using it, don't assume it will work even if the VBT
14715          * indicates as much.
14716          */
14717         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
14718                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14719                                             DREF_SSC1_ENABLE);
14720
14721                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14722                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14723                                      bios_lvds_use_ssc ? "en" : "dis",
14724                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14725                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14726                 }
14727         }
14728
14729         if (IS_GEN2(dev_priv)) {
14730                 dev->mode_config.max_width = 2048;
14731                 dev->mode_config.max_height = 2048;
14732         } else if (IS_GEN3(dev_priv)) {
14733                 dev->mode_config.max_width = 4096;
14734                 dev->mode_config.max_height = 4096;
14735         } else {
14736                 dev->mode_config.max_width = 8192;
14737                 dev->mode_config.max_height = 8192;
14738         }
14739
14740         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14741                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
14742                 dev->mode_config.cursor_height = 1023;
14743         } else if (IS_GEN2(dev_priv)) {
14744                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14745                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14746         } else {
14747                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14748                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14749         }
14750
14751         dev->mode_config.fb_base = ggtt->gmadr.start;
14752
14753         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14754                       INTEL_INFO(dev_priv)->num_pipes,
14755                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
14756
14757         for_each_pipe(dev_priv, pipe) {
14758                 int ret;
14759
14760                 ret = intel_crtc_init(dev_priv, pipe);
14761                 if (ret) {
14762                         drm_mode_config_cleanup(dev);
14763                         return ret;
14764                 }
14765         }
14766
14767         intel_shared_dpll_init(dev);
14768         intel_update_fdi_pll_freq(dev_priv);
14769
14770         intel_update_czclk(dev_priv);
14771         intel_modeset_init_hw(dev);
14772
14773         if (dev_priv->max_cdclk_freq == 0)
14774                 intel_update_max_cdclk(dev_priv);
14775
14776         /* Just disable it once at startup */
14777         i915_disable_vga(dev_priv);
14778         intel_setup_outputs(dev_priv);
14779
14780         drm_modeset_lock_all(dev);
14781         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
14782         drm_modeset_unlock_all(dev);
14783
14784         for_each_intel_crtc(dev, crtc) {
14785                 struct intel_initial_plane_config plane_config = {};
14786
14787                 if (!crtc->active)
14788                         continue;
14789
14790                 /*
14791                  * Note that reserving the BIOS fb up front prevents us
14792                  * from stuffing other stolen allocations like the ring
14793                  * on top.  This prevents some ugliness at boot time, and
14794                  * can even allow for smooth boot transitions if the BIOS
14795                  * fb is large enough for the active pipe configuration.
14796                  */
14797                 dev_priv->display.get_initial_plane_config(crtc,
14798                                                            &plane_config);
14799
14800                 /*
14801                  * If the fb is shared between multiple heads, we'll
14802                  * just get the first one.
14803                  */
14804                 intel_find_initial_plane_obj(crtc, &plane_config);
14805         }
14806
14807         /*
14808          * Make sure hardware watermarks really match the state we read out.
14809          * Note that we need to do this after reconstructing the BIOS fb's
14810          * since the watermark calculation done here will use pstate->fb.
14811          */
14812         if (!HAS_GMCH_DISPLAY(dev_priv))
14813                 sanitize_watermarks(dev);
14814
14815         return 0;
14816 }
14817
14818 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14819 {
14820         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14821         /* 640x480@60Hz, ~25175 kHz */
14822         struct dpll clock = {
14823                 .m1 = 18,
14824                 .m2 = 7,
14825                 .p1 = 13,
14826                 .p2 = 4,
14827                 .n = 2,
14828         };
14829         u32 dpll, fp;
14830         int i;
14831
14832         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
14833
14834         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
14835                       pipe_name(pipe), clock.vco, clock.dot);
14836
14837         fp = i9xx_dpll_compute_fp(&clock);
14838         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
14839                 DPLL_VGA_MODE_DIS |
14840                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
14841                 PLL_P2_DIVIDE_BY_4 |
14842                 PLL_REF_INPUT_DREFCLK |
14843                 DPLL_VCO_ENABLE;
14844
14845         I915_WRITE(FP0(pipe), fp);
14846         I915_WRITE(FP1(pipe), fp);
14847
14848         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
14849         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
14850         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
14851         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
14852         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
14853         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
14854         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
14855
14856         /*
14857          * Apparently we need to have VGA mode enabled prior to changing
14858          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
14859          * dividers, even though the register value does change.
14860          */
14861         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
14862         I915_WRITE(DPLL(pipe), dpll);
14863
14864         /* Wait for the clocks to stabilize. */
14865         POSTING_READ(DPLL(pipe));
14866         udelay(150);
14867
14868         /* The pixel multiplier can only be updated once the
14869          * DPLL is enabled and the clocks are stable.
14870          *
14871          * So write it again.
14872          */
14873         I915_WRITE(DPLL(pipe), dpll);
14874
14875         /* We do this three times for luck */
14876         for (i = 0; i < 3 ; i++) {
14877                 I915_WRITE(DPLL(pipe), dpll);
14878                 POSTING_READ(DPLL(pipe));
14879                 udelay(150); /* wait for warmup */
14880         }
14881
14882         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
14883         POSTING_READ(PIPECONF(pipe));
14884
14885         intel_wait_for_pipe_scanline_moving(crtc);
14886 }
14887
14888 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14889 {
14890         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14891
14892         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
14893                       pipe_name(pipe));
14894
14895         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
14896         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
14897         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
14898         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & CURSOR_MODE);
14899         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & CURSOR_MODE);
14900
14901         I915_WRITE(PIPECONF(pipe), 0);
14902         POSTING_READ(PIPECONF(pipe));
14903
14904         intel_wait_for_pipe_scanline_stopped(crtc);
14905
14906         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
14907         POSTING_READ(DPLL(pipe));
14908 }
14909
14910 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
14911                                    struct intel_plane *plane)
14912 {
14913         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14914         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
14915         u32 val = I915_READ(DSPCNTR(i9xx_plane));
14916
14917         return (val & DISPLAY_PLANE_ENABLE) == 0 ||
14918                 (val & DISPPLANE_SEL_PIPE_MASK) == DISPPLANE_SEL_PIPE(crtc->pipe);
14919 }
14920
14921 static void
14922 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
14923 {
14924         struct intel_crtc *crtc;
14925
14926         if (INTEL_GEN(dev_priv) >= 4)
14927                 return;
14928
14929         for_each_intel_crtc(&dev_priv->drm, crtc) {
14930                 struct intel_plane *plane =
14931                         to_intel_plane(crtc->base.primary);
14932
14933                 if (intel_plane_mapping_ok(crtc, plane))
14934                         continue;
14935
14936                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
14937                               plane->base.name);
14938                 intel_plane_disable_noatomic(crtc, plane);
14939         }
14940 }
14941
14942 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14943 {
14944         struct drm_device *dev = crtc->base.dev;
14945         struct intel_encoder *encoder;
14946
14947         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14948                 return true;
14949
14950         return false;
14951 }
14952
14953 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
14954 {
14955         struct drm_device *dev = encoder->base.dev;
14956         struct intel_connector *connector;
14957
14958         for_each_connector_on_encoder(dev, &encoder->base, connector)
14959                 return connector;
14960
14961         return NULL;
14962 }
14963
14964 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
14965                               enum pipe pch_transcoder)
14966 {
14967         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
14968                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
14969 }
14970
14971 static void intel_sanitize_crtc(struct intel_crtc *crtc,
14972                                 struct drm_modeset_acquire_ctx *ctx)
14973 {
14974         struct drm_device *dev = crtc->base.dev;
14975         struct drm_i915_private *dev_priv = to_i915(dev);
14976         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
14977
14978         /* Clear any frame start delays used for debugging left by the BIOS */
14979         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
14980                 i915_reg_t reg = PIPECONF(cpu_transcoder);
14981
14982                 I915_WRITE(reg,
14983                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14984         }
14985
14986         /* restore vblank interrupts to correct state */
14987         drm_crtc_vblank_reset(&crtc->base);
14988         if (crtc->active) {
14989                 struct intel_plane *plane;
14990
14991                 drm_crtc_vblank_on(&crtc->base);
14992
14993                 /* Disable everything but the primary plane */
14994                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
14995                         const struct intel_plane_state *plane_state =
14996                                 to_intel_plane_state(plane->base.state);
14997
14998                         if (plane_state->base.visible &&
14999                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15000                                 intel_plane_disable_noatomic(crtc, plane);
15001                 }
15002         }
15003
15004         /* Adjust the state of the output pipe according to whether we
15005          * have active connectors/encoders. */
15006         if (crtc->active && !intel_crtc_has_encoders(crtc))
15007                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15008
15009         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15010                 /*
15011                  * We start out with underrun reporting disabled to avoid races.
15012                  * For correct bookkeeping mark this on active crtcs.
15013                  *
15014                  * Also on gmch platforms we dont have any hardware bits to
15015                  * disable the underrun reporting. Which means we need to start
15016                  * out with underrun reporting disabled also on inactive pipes,
15017                  * since otherwise we'll complain about the garbage we read when
15018                  * e.g. coming up after runtime pm.
15019                  *
15020                  * No protection against concurrent access is required - at
15021                  * worst a fifo underrun happens which also sets this to false.
15022                  */
15023                 crtc->cpu_fifo_underrun_disabled = true;
15024                 /*
15025                  * We track the PCH trancoder underrun reporting state
15026                  * within the crtc. With crtc for pipe A housing the underrun
15027                  * reporting state for PCH transcoder A, crtc for pipe B housing
15028                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15029                  * and marking underrun reporting as disabled for the non-existing
15030                  * PCH transcoders B and C would prevent enabling the south
15031                  * error interrupt (see cpt_can_enable_serr_int()).
15032                  */
15033                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15034                         crtc->pch_fifo_underrun_disabled = true;
15035         }
15036 }
15037
15038 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15039 {
15040         struct intel_connector *connector;
15041
15042         /* We need to check both for a crtc link (meaning that the
15043          * encoder is active and trying to read from a pipe) and the
15044          * pipe itself being active. */
15045         bool has_active_crtc = encoder->base.crtc &&
15046                 to_intel_crtc(encoder->base.crtc)->active;
15047
15048         connector = intel_encoder_find_connector(encoder);
15049         if (connector && !has_active_crtc) {
15050                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15051                               encoder->base.base.id,
15052                               encoder->base.name);
15053
15054                 /* Connector is active, but has no active pipe. This is
15055                  * fallout from our resume register restoring. Disable
15056                  * the encoder manually again. */
15057                 if (encoder->base.crtc) {
15058                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15059
15060                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15061                                       encoder->base.base.id,
15062                                       encoder->base.name);
15063                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15064                         if (encoder->post_disable)
15065                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15066                 }
15067                 encoder->base.crtc = NULL;
15068
15069                 /* Inconsistent output/port/pipe state happens presumably due to
15070                  * a bug in one of the get_hw_state functions. Or someplace else
15071                  * in our code, like the register restore mess on resume. Clamp
15072                  * things to off as a safer default. */
15073
15074                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15075                 connector->base.encoder = NULL;
15076         }
15077 }
15078
15079 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15080 {
15081         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15082
15083         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15084                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15085                 i915_disable_vga(dev_priv);
15086         }
15087 }
15088
15089 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15090 {
15091         /* This function can be called both from intel_modeset_setup_hw_state or
15092          * at a very early point in our resume sequence, where the power well
15093          * structures are not yet restored. Since this function is at a very
15094          * paranoid "someone might have enabled VGA while we were not looking"
15095          * level, just check if the power well is enabled instead of trying to
15096          * follow the "don't touch the power well if we don't need it" policy
15097          * the rest of the driver uses. */
15098         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15099                 return;
15100
15101         i915_redisable_vga_power_on(dev_priv);
15102
15103         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15104 }
15105
15106 /* FIXME read out full plane state for all planes */
15107 static void readout_plane_state(struct intel_crtc *crtc)
15108 {
15109         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15110         struct intel_crtc_state *crtc_state =
15111                 to_intel_crtc_state(crtc->base.state);
15112         struct intel_plane *plane;
15113
15114         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
15115                 struct intel_plane_state *plane_state =
15116                         to_intel_plane_state(plane->base.state);
15117                 bool visible = plane->get_hw_state(plane);
15118
15119                 intel_set_plane_visible(crtc_state, plane_state, visible);
15120         }
15121 }
15122
15123 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15124 {
15125         struct drm_i915_private *dev_priv = to_i915(dev);
15126         enum pipe pipe;
15127         struct intel_crtc *crtc;
15128         struct intel_encoder *encoder;
15129         struct intel_connector *connector;
15130         struct drm_connector_list_iter conn_iter;
15131         int i;
15132
15133         dev_priv->active_crtcs = 0;
15134
15135         for_each_intel_crtc(dev, crtc) {
15136                 struct intel_crtc_state *crtc_state =
15137                         to_intel_crtc_state(crtc->base.state);
15138
15139                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15140                 memset(crtc_state, 0, sizeof(*crtc_state));
15141                 crtc_state->base.crtc = &crtc->base;
15142
15143                 crtc_state->base.active = crtc_state->base.enable =
15144                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15145
15146                 crtc->base.enabled = crtc_state->base.enable;
15147                 crtc->active = crtc_state->base.active;
15148
15149                 if (crtc_state->base.active)
15150                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15151
15152                 readout_plane_state(crtc);
15153
15154                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15155                               crtc->base.base.id, crtc->base.name,
15156                               enableddisabled(crtc_state->base.active));
15157         }
15158
15159         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15160                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15161
15162                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15163                                                         &pll->state.hw_state);
15164                 pll->state.crtc_mask = 0;
15165                 for_each_intel_crtc(dev, crtc) {
15166                         struct intel_crtc_state *crtc_state =
15167                                 to_intel_crtc_state(crtc->base.state);
15168
15169                         if (crtc_state->base.active &&
15170                             crtc_state->shared_dpll == pll)
15171                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15172                 }
15173                 pll->active_mask = pll->state.crtc_mask;
15174
15175                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15176                               pll->info->name, pll->state.crtc_mask, pll->on);
15177         }
15178
15179         for_each_intel_encoder(dev, encoder) {
15180                 pipe = 0;
15181
15182                 if (encoder->get_hw_state(encoder, &pipe)) {
15183                         struct intel_crtc_state *crtc_state;
15184
15185                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15186                         crtc_state = to_intel_crtc_state(crtc->base.state);
15187
15188                         encoder->base.crtc = &crtc->base;
15189                         encoder->get_config(encoder, crtc_state);
15190                 } else {
15191                         encoder->base.crtc = NULL;
15192                 }
15193
15194                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15195                               encoder->base.base.id, encoder->base.name,
15196                               enableddisabled(encoder->base.crtc),
15197                               pipe_name(pipe));
15198         }
15199
15200         drm_connector_list_iter_begin(dev, &conn_iter);
15201         for_each_intel_connector_iter(connector, &conn_iter) {
15202                 if (connector->get_hw_state(connector)) {
15203                         connector->base.dpms = DRM_MODE_DPMS_ON;
15204
15205                         encoder = connector->encoder;
15206                         connector->base.encoder = &encoder->base;
15207
15208                         if (encoder->base.crtc &&
15209                             encoder->base.crtc->state->active) {
15210                                 /*
15211                                  * This has to be done during hardware readout
15212                                  * because anything calling .crtc_disable may
15213                                  * rely on the connector_mask being accurate.
15214                                  */
15215                                 encoder->base.crtc->state->connector_mask |=
15216                                         1 << drm_connector_index(&connector->base);
15217                                 encoder->base.crtc->state->encoder_mask |=
15218                                         1 << drm_encoder_index(&encoder->base);
15219                         }
15220
15221                 } else {
15222                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15223                         connector->base.encoder = NULL;
15224                 }
15225                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15226                               connector->base.base.id, connector->base.name,
15227                               enableddisabled(connector->base.encoder));
15228         }
15229         drm_connector_list_iter_end(&conn_iter);
15230
15231         for_each_intel_crtc(dev, crtc) {
15232                 struct intel_crtc_state *crtc_state =
15233                         to_intel_crtc_state(crtc->base.state);
15234                 int min_cdclk = 0;
15235
15236                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15237                 if (crtc_state->base.active) {
15238                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15239                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15240                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15241
15242                         /*
15243                          * The initial mode needs to be set in order to keep
15244                          * the atomic core happy. It wants a valid mode if the
15245                          * crtc's enabled, so we do the above call.
15246                          *
15247                          * But we don't set all the derived state fully, hence
15248                          * set a flag to indicate that a full recalculation is
15249                          * needed on the next commit.
15250                          */
15251                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15252
15253                         intel_crtc_compute_pixel_rate(crtc_state);
15254
15255                         if (dev_priv->display.modeset_calc_cdclk) {
15256                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15257                                 if (WARN_ON(min_cdclk < 0))
15258                                         min_cdclk = 0;
15259                         }
15260
15261                         drm_calc_timestamping_constants(&crtc->base,
15262                                                         &crtc_state->base.adjusted_mode);
15263                         update_scanline_offset(crtc);
15264                 }
15265
15266                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15267                 dev_priv->min_voltage_level[crtc->pipe] =
15268                         crtc_state->min_voltage_level;
15269
15270                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15271         }
15272 }
15273
15274 static void
15275 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15276 {
15277         struct intel_encoder *encoder;
15278
15279         for_each_intel_encoder(&dev_priv->drm, encoder) {
15280                 u64 get_domains;
15281                 enum intel_display_power_domain domain;
15282
15283                 if (!encoder->get_power_domains)
15284                         continue;
15285
15286                 get_domains = encoder->get_power_domains(encoder);
15287                 for_each_power_domain(domain, get_domains)
15288                         intel_display_power_get(dev_priv, domain);
15289         }
15290 }
15291
15292 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15293 {
15294         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15295         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15296                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15297                            DARBF_GATING_DIS);
15298
15299         if (IS_HASWELL(dev_priv)) {
15300                 /*
15301                  * WaRsPkgCStateDisplayPMReq:hsw
15302                  * System hang if this isn't done before disabling all planes!
15303                  */
15304                 I915_WRITE(CHICKEN_PAR1_1,
15305                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15306         }
15307 }
15308
15309 /* Scan out the current hw modeset state,
15310  * and sanitizes it to the current state
15311  */
15312 static void
15313 intel_modeset_setup_hw_state(struct drm_device *dev,
15314                              struct drm_modeset_acquire_ctx *ctx)
15315 {
15316         struct drm_i915_private *dev_priv = to_i915(dev);
15317         enum pipe pipe;
15318         struct intel_crtc *crtc;
15319         struct intel_encoder *encoder;
15320         int i;
15321
15322         intel_early_display_was(dev_priv);
15323         intel_modeset_readout_hw_state(dev);
15324
15325         /* HW state is read out, now we need to sanitize this mess. */
15326         get_encoder_power_domains(dev_priv);
15327
15328         intel_sanitize_plane_mapping(dev_priv);
15329
15330         for_each_intel_encoder(dev, encoder) {
15331                 intel_sanitize_encoder(encoder);
15332         }
15333
15334         for_each_pipe(dev_priv, pipe) {
15335                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15336
15337                 intel_sanitize_crtc(crtc, ctx);
15338                 intel_dump_pipe_config(crtc, crtc->config,
15339                                        "[setup_hw_state]");
15340         }
15341
15342         intel_modeset_update_connector_atomic_state(dev);
15343
15344         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15345                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15346
15347                 if (!pll->on || pll->active_mask)
15348                         continue;
15349
15350                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15351                               pll->info->name);
15352
15353                 pll->info->funcs->disable(dev_priv, pll);
15354                 pll->on = false;
15355         }
15356
15357         if (IS_G4X(dev_priv)) {
15358                 g4x_wm_get_hw_state(dev);
15359                 g4x_wm_sanitize(dev_priv);
15360         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15361                 vlv_wm_get_hw_state(dev);
15362                 vlv_wm_sanitize(dev_priv);
15363         } else if (INTEL_GEN(dev_priv) >= 9) {
15364                 skl_wm_get_hw_state(dev);
15365         } else if (HAS_PCH_SPLIT(dev_priv)) {
15366                 ilk_wm_get_hw_state(dev);
15367         }
15368
15369         for_each_intel_crtc(dev, crtc) {
15370                 u64 put_domains;
15371
15372                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15373                 if (WARN_ON(put_domains))
15374                         modeset_put_power_domains(dev_priv, put_domains);
15375         }
15376         intel_display_set_init_power(dev_priv, false);
15377
15378         intel_power_domains_verify_state(dev_priv);
15379
15380         intel_fbc_init_pipe_state(dev_priv);
15381 }
15382
15383 void intel_display_resume(struct drm_device *dev)
15384 {
15385         struct drm_i915_private *dev_priv = to_i915(dev);
15386         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15387         struct drm_modeset_acquire_ctx ctx;
15388         int ret;
15389
15390         dev_priv->modeset_restore_state = NULL;
15391         if (state)
15392                 state->acquire_ctx = &ctx;
15393
15394         drm_modeset_acquire_init(&ctx, 0);
15395
15396         while (1) {
15397                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15398                 if (ret != -EDEADLK)
15399                         break;
15400
15401                 drm_modeset_backoff(&ctx);
15402         }
15403
15404         if (!ret)
15405                 ret = __intel_display_resume(dev, state, &ctx);
15406
15407         intel_enable_ipc(dev_priv);
15408         drm_modeset_drop_locks(&ctx);
15409         drm_modeset_acquire_fini(&ctx);
15410
15411         if (ret)
15412                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15413         if (state)
15414                 drm_atomic_state_put(state);
15415 }
15416
15417 int intel_connector_register(struct drm_connector *connector)
15418 {
15419         struct intel_connector *intel_connector = to_intel_connector(connector);
15420         int ret;
15421
15422         ret = intel_backlight_device_register(intel_connector);
15423         if (ret)
15424                 goto err;
15425
15426         return 0;
15427
15428 err:
15429         return ret;
15430 }
15431
15432 void intel_connector_unregister(struct drm_connector *connector)
15433 {
15434         struct intel_connector *intel_connector = to_intel_connector(connector);
15435
15436         intel_backlight_device_unregister(intel_connector);
15437         intel_panel_destroy_backlight(connector);
15438 }
15439
15440 static void intel_hpd_poll_fini(struct drm_device *dev)
15441 {
15442         struct intel_connector *connector;
15443         struct drm_connector_list_iter conn_iter;
15444
15445         /* Kill all the work that may have been queued by hpd. */
15446         drm_connector_list_iter_begin(dev, &conn_iter);
15447         for_each_intel_connector_iter(connector, &conn_iter) {
15448                 if (connector->modeset_retry_work.func)
15449                         cancel_work_sync(&connector->modeset_retry_work);
15450                 if (connector->hdcp_shim) {
15451                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15452                         cancel_work_sync(&connector->hdcp_prop_work);
15453                 }
15454         }
15455         drm_connector_list_iter_end(&conn_iter);
15456 }
15457
15458 void intel_modeset_cleanup(struct drm_device *dev)
15459 {
15460         struct drm_i915_private *dev_priv = to_i915(dev);
15461
15462         flush_work(&dev_priv->atomic_helper.free_work);
15463         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15464
15465         intel_disable_gt_powersave(dev_priv);
15466
15467         /*
15468          * Interrupts and polling as the first thing to avoid creating havoc.
15469          * Too much stuff here (turning of connectors, ...) would
15470          * experience fancy races otherwise.
15471          */
15472         intel_irq_uninstall(dev_priv);
15473
15474         /*
15475          * Due to the hpd irq storm handling the hotplug work can re-arm the
15476          * poll handlers. Hence disable polling after hpd handling is shut down.
15477          */
15478         intel_hpd_poll_fini(dev);
15479
15480         /* poll work can call into fbdev, hence clean that up afterwards */
15481         intel_fbdev_fini(dev_priv);
15482
15483         intel_unregister_dsm_handler();
15484
15485         intel_fbc_global_disable(dev_priv);
15486
15487         /* flush any delayed tasks or pending work */
15488         flush_scheduled_work();
15489
15490         drm_mode_config_cleanup(dev);
15491
15492         intel_cleanup_overlay(dev_priv);
15493
15494         intel_cleanup_gt_powersave(dev_priv);
15495
15496         intel_teardown_gmbus(dev_priv);
15497
15498         destroy_workqueue(dev_priv->modeset_wq);
15499 }
15500
15501 void intel_connector_attach_encoder(struct intel_connector *connector,
15502                                     struct intel_encoder *encoder)
15503 {
15504         connector->encoder = encoder;
15505         drm_mode_connector_attach_encoder(&connector->base,
15506                                           &encoder->base);
15507 }
15508
15509 /*
15510  * set vga decode state - true == enable VGA decode
15511  */
15512 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15513 {
15514         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15515         u16 gmch_ctrl;
15516
15517         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15518                 DRM_ERROR("failed to read control word\n");
15519                 return -EIO;
15520         }
15521
15522         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15523                 return 0;
15524
15525         if (state)
15526                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15527         else
15528                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15529
15530         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15531                 DRM_ERROR("failed to write control word\n");
15532                 return -EIO;
15533         }
15534
15535         return 0;
15536 }
15537
15538 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15539
15540 struct intel_display_error_state {
15541
15542         u32 power_well_driver;
15543
15544         int num_transcoders;
15545
15546         struct intel_cursor_error_state {
15547                 u32 control;
15548                 u32 position;
15549                 u32 base;
15550                 u32 size;
15551         } cursor[I915_MAX_PIPES];
15552
15553         struct intel_pipe_error_state {
15554                 bool power_domain_on;
15555                 u32 source;
15556                 u32 stat;
15557         } pipe[I915_MAX_PIPES];
15558
15559         struct intel_plane_error_state {
15560                 u32 control;
15561                 u32 stride;
15562                 u32 size;
15563                 u32 pos;
15564                 u32 addr;
15565                 u32 surface;
15566                 u32 tile_offset;
15567         } plane[I915_MAX_PIPES];
15568
15569         struct intel_transcoder_error_state {
15570                 bool power_domain_on;
15571                 enum transcoder cpu_transcoder;
15572
15573                 u32 conf;
15574
15575                 u32 htotal;
15576                 u32 hblank;
15577                 u32 hsync;
15578                 u32 vtotal;
15579                 u32 vblank;
15580                 u32 vsync;
15581         } transcoder[4];
15582 };
15583
15584 struct intel_display_error_state *
15585 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15586 {
15587         struct intel_display_error_state *error;
15588         int transcoders[] = {
15589                 TRANSCODER_A,
15590                 TRANSCODER_B,
15591                 TRANSCODER_C,
15592                 TRANSCODER_EDP,
15593         };
15594         int i;
15595
15596         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15597                 return NULL;
15598
15599         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15600         if (error == NULL)
15601                 return NULL;
15602
15603         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15604                 error->power_well_driver =
15605                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
15606
15607         for_each_pipe(dev_priv, i) {
15608                 error->pipe[i].power_domain_on =
15609                         __intel_display_power_is_enabled(dev_priv,
15610                                                          POWER_DOMAIN_PIPE(i));
15611                 if (!error->pipe[i].power_domain_on)
15612                         continue;
15613
15614                 error->cursor[i].control = I915_READ(CURCNTR(i));
15615                 error->cursor[i].position = I915_READ(CURPOS(i));
15616                 error->cursor[i].base = I915_READ(CURBASE(i));
15617
15618                 error->plane[i].control = I915_READ(DSPCNTR(i));
15619                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15620                 if (INTEL_GEN(dev_priv) <= 3) {
15621                         error->plane[i].size = I915_READ(DSPSIZE(i));
15622                         error->plane[i].pos = I915_READ(DSPPOS(i));
15623                 }
15624                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15625                         error->plane[i].addr = I915_READ(DSPADDR(i));
15626                 if (INTEL_GEN(dev_priv) >= 4) {
15627                         error->plane[i].surface = I915_READ(DSPSURF(i));
15628                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15629                 }
15630
15631                 error->pipe[i].source = I915_READ(PIPESRC(i));
15632
15633                 if (HAS_GMCH_DISPLAY(dev_priv))
15634                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15635         }
15636
15637         /* Note: this does not include DSI transcoders. */
15638         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15639         if (HAS_DDI(dev_priv))
15640                 error->num_transcoders++; /* Account for eDP. */
15641
15642         for (i = 0; i < error->num_transcoders; i++) {
15643                 enum transcoder cpu_transcoder = transcoders[i];
15644
15645                 error->transcoder[i].power_domain_on =
15646                         __intel_display_power_is_enabled(dev_priv,
15647                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15648                 if (!error->transcoder[i].power_domain_on)
15649                         continue;
15650
15651                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15652
15653                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15654                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15655                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15656                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15657                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15658                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15659                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15660         }
15661
15662         return error;
15663 }
15664
15665 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15666
15667 void
15668 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15669                                 struct intel_display_error_state *error)
15670 {
15671         struct drm_i915_private *dev_priv = m->i915;
15672         int i;
15673
15674         if (!error)
15675                 return;
15676
15677         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15678         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15679                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15680                            error->power_well_driver);
15681         for_each_pipe(dev_priv, i) {
15682                 err_printf(m, "Pipe [%d]:\n", i);
15683                 err_printf(m, "  Power: %s\n",
15684                            onoff(error->pipe[i].power_domain_on));
15685                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15686                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15687
15688                 err_printf(m, "Plane [%d]:\n", i);
15689                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15690                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15691                 if (INTEL_GEN(dev_priv) <= 3) {
15692                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15693                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15694                 }
15695                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15696                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15697                 if (INTEL_GEN(dev_priv) >= 4) {
15698                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15699                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15700                 }
15701
15702                 err_printf(m, "Cursor [%d]:\n", i);
15703                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15704                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15705                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15706         }
15707
15708         for (i = 0; i < error->num_transcoders; i++) {
15709                 err_printf(m, "CPU transcoder: %s\n",
15710                            transcoder_name(error->transcoder[i].cpu_transcoder));
15711                 err_printf(m, "  Power: %s\n",
15712                            onoff(error->transcoder[i].power_domain_on));
15713                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15714                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15715                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15716                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15717                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15718                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15719                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15720         }
15721 }
15722
15723 #endif