Merge tag 'drm-intel-next-2018-04-13' of git://anongit.freedesktop.org/drm/drm-intel...
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/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 = state->base.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         case DRM_FORMAT_NV12:
3487                 return PLANE_CTL_FORMAT_NV12;
3488         default:
3489                 MISSING_CASE(pixel_format);
3490         }
3491
3492         return 0;
3493 }
3494
3495 /*
3496  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3497  * to be already pre-multiplied. We need to add a knob (or a different
3498  * DRM_FORMAT) for user-space to configure that.
3499  */
3500 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3501 {
3502         switch (pixel_format) {
3503         case DRM_FORMAT_ABGR8888:
3504         case DRM_FORMAT_ARGB8888:
3505                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3506         default:
3507                 return PLANE_CTL_ALPHA_DISABLE;
3508         }
3509 }
3510
3511 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3512 {
3513         switch (pixel_format) {
3514         case DRM_FORMAT_ABGR8888:
3515         case DRM_FORMAT_ARGB8888:
3516                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3517         default:
3518                 return PLANE_COLOR_ALPHA_DISABLE;
3519         }
3520 }
3521
3522 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3523 {
3524         switch (fb_modifier) {
3525         case DRM_FORMAT_MOD_LINEAR:
3526                 break;
3527         case I915_FORMAT_MOD_X_TILED:
3528                 return PLANE_CTL_TILED_X;
3529         case I915_FORMAT_MOD_Y_TILED:
3530                 return PLANE_CTL_TILED_Y;
3531         case I915_FORMAT_MOD_Y_TILED_CCS:
3532                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3533         case I915_FORMAT_MOD_Yf_TILED:
3534                 return PLANE_CTL_TILED_YF;
3535         case I915_FORMAT_MOD_Yf_TILED_CCS:
3536                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3537         default:
3538                 MISSING_CASE(fb_modifier);
3539         }
3540
3541         return 0;
3542 }
3543
3544 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3545 {
3546         switch (rotate) {
3547         case DRM_MODE_ROTATE_0:
3548                 break;
3549         /*
3550          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3551          * while i915 HW rotation is clockwise, thats why this swapping.
3552          */
3553         case DRM_MODE_ROTATE_90:
3554                 return PLANE_CTL_ROTATE_270;
3555         case DRM_MODE_ROTATE_180:
3556                 return PLANE_CTL_ROTATE_180;
3557         case DRM_MODE_ROTATE_270:
3558                 return PLANE_CTL_ROTATE_90;
3559         default:
3560                 MISSING_CASE(rotate);
3561         }
3562
3563         return 0;
3564 }
3565
3566 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3567 {
3568         switch (reflect) {
3569         case 0:
3570                 break;
3571         case DRM_MODE_REFLECT_X:
3572                 return PLANE_CTL_FLIP_HORIZONTAL;
3573         case DRM_MODE_REFLECT_Y:
3574         default:
3575                 MISSING_CASE(reflect);
3576         }
3577
3578         return 0;
3579 }
3580
3581 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3582                   const struct intel_plane_state *plane_state)
3583 {
3584         struct drm_i915_private *dev_priv =
3585                 to_i915(plane_state->base.plane->dev);
3586         const struct drm_framebuffer *fb = plane_state->base.fb;
3587         unsigned int rotation = plane_state->base.rotation;
3588         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3589         u32 plane_ctl;
3590
3591         plane_ctl = PLANE_CTL_ENABLE;
3592
3593         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3594                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3595                 plane_ctl |=
3596                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3597                         PLANE_CTL_PIPE_CSC_ENABLE |
3598                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3599
3600                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3601                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3602
3603                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3604                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3605         }
3606
3607         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3608         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3609         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3610
3611         if (INTEL_GEN(dev_priv) >= 10)
3612                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3613                                                 DRM_MODE_REFLECT_MASK);
3614
3615         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3616                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3617         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3618                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3619
3620         return plane_ctl;
3621 }
3622
3623 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3624                         const struct intel_plane_state *plane_state)
3625 {
3626         const struct drm_framebuffer *fb = plane_state->base.fb;
3627         u32 plane_color_ctl = 0;
3628
3629         plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3630         plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3631         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3632         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3633
3634         if (intel_format_is_yuv(fb->format->format)) {
3635                 if (fb->format->format == DRM_FORMAT_NV12) {
3636                         plane_color_ctl |=
3637                                 PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3638                         goto out;
3639                 }
3640                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3641                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3642                 else
3643                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3644
3645                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3646                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3647         }
3648 out:
3649         return plane_color_ctl;
3650 }
3651
3652 static int
3653 __intel_display_resume(struct drm_device *dev,
3654                        struct drm_atomic_state *state,
3655                        struct drm_modeset_acquire_ctx *ctx)
3656 {
3657         struct drm_crtc_state *crtc_state;
3658         struct drm_crtc *crtc;
3659         int i, ret;
3660
3661         intel_modeset_setup_hw_state(dev, ctx);
3662         i915_redisable_vga(to_i915(dev));
3663
3664         if (!state)
3665                 return 0;
3666
3667         /*
3668          * We've duplicated the state, pointers to the old state are invalid.
3669          *
3670          * Don't attempt to use the old state until we commit the duplicated state.
3671          */
3672         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3673                 /*
3674                  * Force recalculation even if we restore
3675                  * current state. With fast modeset this may not result
3676                  * in a modeset when the state is compatible.
3677                  */
3678                 crtc_state->mode_changed = true;
3679         }
3680
3681         /* ignore any reset values/BIOS leftovers in the WM registers */
3682         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3683                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3684
3685         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3686
3687         WARN_ON(ret == -EDEADLK);
3688         return ret;
3689 }
3690
3691 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3692 {
3693         return intel_has_gpu_reset(dev_priv) &&
3694                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3695 }
3696
3697 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3698 {
3699         struct drm_device *dev = &dev_priv->drm;
3700         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3701         struct drm_atomic_state *state;
3702         int ret;
3703
3704         /* reset doesn't touch the display */
3705         if (!i915_modparams.force_reset_modeset_test &&
3706             !gpu_reset_clobbers_display(dev_priv))
3707                 return;
3708
3709         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3710         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3711         wake_up_all(&dev_priv->gpu_error.wait_queue);
3712
3713         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3714                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3715                 i915_gem_set_wedged(dev_priv);
3716         }
3717
3718         /*
3719          * Need mode_config.mutex so that we don't
3720          * trample ongoing ->detect() and whatnot.
3721          */
3722         mutex_lock(&dev->mode_config.mutex);
3723         drm_modeset_acquire_init(ctx, 0);
3724         while (1) {
3725                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3726                 if (ret != -EDEADLK)
3727                         break;
3728
3729                 drm_modeset_backoff(ctx);
3730         }
3731         /*
3732          * Disabling the crtcs gracefully seems nicer. Also the
3733          * g33 docs say we should at least disable all the planes.
3734          */
3735         state = drm_atomic_helper_duplicate_state(dev, ctx);
3736         if (IS_ERR(state)) {
3737                 ret = PTR_ERR(state);
3738                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3739                 return;
3740         }
3741
3742         ret = drm_atomic_helper_disable_all(dev, ctx);
3743         if (ret) {
3744                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3745                 drm_atomic_state_put(state);
3746                 return;
3747         }
3748
3749         dev_priv->modeset_restore_state = state;
3750         state->acquire_ctx = ctx;
3751 }
3752
3753 void intel_finish_reset(struct drm_i915_private *dev_priv)
3754 {
3755         struct drm_device *dev = &dev_priv->drm;
3756         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3757         struct drm_atomic_state *state;
3758         int ret;
3759
3760         /* reset doesn't touch the display */
3761         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3762                 return;
3763
3764         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3765         if (!state)
3766                 goto unlock;
3767
3768         /* reset doesn't touch the display */
3769         if (!gpu_reset_clobbers_display(dev_priv)) {
3770                 /* for testing only restore the display */
3771                 ret = __intel_display_resume(dev, state, ctx);
3772                 if (ret)
3773                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3774         } else {
3775                 /*
3776                  * The display has been reset as well,
3777                  * so need a full re-initialization.
3778                  */
3779                 intel_runtime_pm_disable_interrupts(dev_priv);
3780                 intel_runtime_pm_enable_interrupts(dev_priv);
3781
3782                 intel_pps_unlock_regs_wa(dev_priv);
3783                 intel_modeset_init_hw(dev);
3784                 intel_init_clock_gating(dev_priv);
3785
3786                 spin_lock_irq(&dev_priv->irq_lock);
3787                 if (dev_priv->display.hpd_irq_setup)
3788                         dev_priv->display.hpd_irq_setup(dev_priv);
3789                 spin_unlock_irq(&dev_priv->irq_lock);
3790
3791                 ret = __intel_display_resume(dev, state, ctx);
3792                 if (ret)
3793                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3794
3795                 intel_hpd_init(dev_priv);
3796         }
3797
3798         drm_atomic_state_put(state);
3799 unlock:
3800         drm_modeset_drop_locks(ctx);
3801         drm_modeset_acquire_fini(ctx);
3802         mutex_unlock(&dev->mode_config.mutex);
3803
3804         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3805 }
3806
3807 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3808                                      const struct intel_crtc_state *new_crtc_state)
3809 {
3810         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3811         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3812
3813         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3814         crtc->base.mode = new_crtc_state->base.mode;
3815
3816         /*
3817          * Update pipe size and adjust fitter if needed: the reason for this is
3818          * that in compute_mode_changes we check the native mode (not the pfit
3819          * mode) to see if we can flip rather than do a full mode set. In the
3820          * fastboot case, we'll flip, but if we don't update the pipesrc and
3821          * pfit state, we'll end up with a big fb scanned out into the wrong
3822          * sized surface.
3823          */
3824
3825         I915_WRITE(PIPESRC(crtc->pipe),
3826                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3827                    (new_crtc_state->pipe_src_h - 1));
3828
3829         /* on skylake this is done by detaching scalers */
3830         if (INTEL_GEN(dev_priv) >= 9) {
3831                 skl_detach_scalers(crtc);
3832
3833                 if (new_crtc_state->pch_pfit.enabled)
3834                         skylake_pfit_enable(crtc);
3835         } else if (HAS_PCH_SPLIT(dev_priv)) {
3836                 if (new_crtc_state->pch_pfit.enabled)
3837                         ironlake_pfit_enable(crtc);
3838                 else if (old_crtc_state->pch_pfit.enabled)
3839                         ironlake_pfit_disable(crtc, true);
3840         }
3841 }
3842
3843 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3844 {
3845         struct drm_device *dev = crtc->base.dev;
3846         struct drm_i915_private *dev_priv = to_i915(dev);
3847         int pipe = crtc->pipe;
3848         i915_reg_t reg;
3849         u32 temp;
3850
3851         /* enable normal train */
3852         reg = FDI_TX_CTL(pipe);
3853         temp = I915_READ(reg);
3854         if (IS_IVYBRIDGE(dev_priv)) {
3855                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3856                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3857         } else {
3858                 temp &= ~FDI_LINK_TRAIN_NONE;
3859                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3860         }
3861         I915_WRITE(reg, temp);
3862
3863         reg = FDI_RX_CTL(pipe);
3864         temp = I915_READ(reg);
3865         if (HAS_PCH_CPT(dev_priv)) {
3866                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3867                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3868         } else {
3869                 temp &= ~FDI_LINK_TRAIN_NONE;
3870                 temp |= FDI_LINK_TRAIN_NONE;
3871         }
3872         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3873
3874         /* wait one idle pattern time */
3875         POSTING_READ(reg);
3876         udelay(1000);
3877
3878         /* IVB wants error correction enabled */
3879         if (IS_IVYBRIDGE(dev_priv))
3880                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3881                            FDI_FE_ERRC_ENABLE);
3882 }
3883
3884 /* The FDI link training functions for ILK/Ibexpeak. */
3885 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3886                                     const struct intel_crtc_state *crtc_state)
3887 {
3888         struct drm_device *dev = crtc->base.dev;
3889         struct drm_i915_private *dev_priv = to_i915(dev);
3890         int pipe = crtc->pipe;
3891         i915_reg_t reg;
3892         u32 temp, tries;
3893
3894         /* FDI needs bits from pipe first */
3895         assert_pipe_enabled(dev_priv, pipe);
3896
3897         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3898            for train result */
3899         reg = FDI_RX_IMR(pipe);
3900         temp = I915_READ(reg);
3901         temp &= ~FDI_RX_SYMBOL_LOCK;
3902         temp &= ~FDI_RX_BIT_LOCK;
3903         I915_WRITE(reg, temp);
3904         I915_READ(reg);
3905         udelay(150);
3906
3907         /* enable CPU FDI TX and PCH FDI RX */
3908         reg = FDI_TX_CTL(pipe);
3909         temp = I915_READ(reg);
3910         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3911         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3912         temp &= ~FDI_LINK_TRAIN_NONE;
3913         temp |= FDI_LINK_TRAIN_PATTERN_1;
3914         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3915
3916         reg = FDI_RX_CTL(pipe);
3917         temp = I915_READ(reg);
3918         temp &= ~FDI_LINK_TRAIN_NONE;
3919         temp |= FDI_LINK_TRAIN_PATTERN_1;
3920         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3921
3922         POSTING_READ(reg);
3923         udelay(150);
3924
3925         /* Ironlake workaround, enable clock pointer after FDI enable*/
3926         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3927         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3928                    FDI_RX_PHASE_SYNC_POINTER_EN);
3929
3930         reg = FDI_RX_IIR(pipe);
3931         for (tries = 0; tries < 5; tries++) {
3932                 temp = I915_READ(reg);
3933                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3934
3935                 if ((temp & FDI_RX_BIT_LOCK)) {
3936                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3937                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3938                         break;
3939                 }
3940         }
3941         if (tries == 5)
3942                 DRM_ERROR("FDI train 1 fail!\n");
3943
3944         /* Train 2 */
3945         reg = FDI_TX_CTL(pipe);
3946         temp = I915_READ(reg);
3947         temp &= ~FDI_LINK_TRAIN_NONE;
3948         temp |= FDI_LINK_TRAIN_PATTERN_2;
3949         I915_WRITE(reg, temp);
3950
3951         reg = FDI_RX_CTL(pipe);
3952         temp = I915_READ(reg);
3953         temp &= ~FDI_LINK_TRAIN_NONE;
3954         temp |= FDI_LINK_TRAIN_PATTERN_2;
3955         I915_WRITE(reg, temp);
3956
3957         POSTING_READ(reg);
3958         udelay(150);
3959
3960         reg = FDI_RX_IIR(pipe);
3961         for (tries = 0; tries < 5; tries++) {
3962                 temp = I915_READ(reg);
3963                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3964
3965                 if (temp & FDI_RX_SYMBOL_LOCK) {
3966                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3967                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3968                         break;
3969                 }
3970         }
3971         if (tries == 5)
3972                 DRM_ERROR("FDI train 2 fail!\n");
3973
3974         DRM_DEBUG_KMS("FDI train done\n");
3975
3976 }
3977
3978 static const int snb_b_fdi_train_param[] = {
3979         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3980         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3981         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3982         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3983 };
3984
3985 /* The FDI link training functions for SNB/Cougarpoint. */
3986 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3987                                 const struct intel_crtc_state *crtc_state)
3988 {
3989         struct drm_device *dev = crtc->base.dev;
3990         struct drm_i915_private *dev_priv = to_i915(dev);
3991         int pipe = crtc->pipe;
3992         i915_reg_t reg;
3993         u32 temp, i, retry;
3994
3995         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3996            for train result */
3997         reg = FDI_RX_IMR(pipe);
3998         temp = I915_READ(reg);
3999         temp &= ~FDI_RX_SYMBOL_LOCK;
4000         temp &= ~FDI_RX_BIT_LOCK;
4001         I915_WRITE(reg, temp);
4002
4003         POSTING_READ(reg);
4004         udelay(150);
4005
4006         /* enable CPU FDI TX and PCH FDI RX */
4007         reg = FDI_TX_CTL(pipe);
4008         temp = I915_READ(reg);
4009         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4010         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4011         temp &= ~FDI_LINK_TRAIN_NONE;
4012         temp |= FDI_LINK_TRAIN_PATTERN_1;
4013         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4014         /* SNB-B */
4015         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4016         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4017
4018         I915_WRITE(FDI_RX_MISC(pipe),
4019                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4020
4021         reg = FDI_RX_CTL(pipe);
4022         temp = I915_READ(reg);
4023         if (HAS_PCH_CPT(dev_priv)) {
4024                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4025                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4026         } else {
4027                 temp &= ~FDI_LINK_TRAIN_NONE;
4028                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4029         }
4030         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4031
4032         POSTING_READ(reg);
4033         udelay(150);
4034
4035         for (i = 0; i < 4; i++) {
4036                 reg = FDI_TX_CTL(pipe);
4037                 temp = I915_READ(reg);
4038                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4039                 temp |= snb_b_fdi_train_param[i];
4040                 I915_WRITE(reg, temp);
4041
4042                 POSTING_READ(reg);
4043                 udelay(500);
4044
4045                 for (retry = 0; retry < 5; retry++) {
4046                         reg = FDI_RX_IIR(pipe);
4047                         temp = I915_READ(reg);
4048                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4049                         if (temp & FDI_RX_BIT_LOCK) {
4050                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4051                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4052                                 break;
4053                         }
4054                         udelay(50);
4055                 }
4056                 if (retry < 5)
4057                         break;
4058         }
4059         if (i == 4)
4060                 DRM_ERROR("FDI train 1 fail!\n");
4061
4062         /* Train 2 */
4063         reg = FDI_TX_CTL(pipe);
4064         temp = I915_READ(reg);
4065         temp &= ~FDI_LINK_TRAIN_NONE;
4066         temp |= FDI_LINK_TRAIN_PATTERN_2;
4067         if (IS_GEN6(dev_priv)) {
4068                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4069                 /* SNB-B */
4070                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4071         }
4072         I915_WRITE(reg, temp);
4073
4074         reg = FDI_RX_CTL(pipe);
4075         temp = I915_READ(reg);
4076         if (HAS_PCH_CPT(dev_priv)) {
4077                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4078                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4079         } else {
4080                 temp &= ~FDI_LINK_TRAIN_NONE;
4081                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4082         }
4083         I915_WRITE(reg, temp);
4084
4085         POSTING_READ(reg);
4086         udelay(150);
4087
4088         for (i = 0; i < 4; i++) {
4089                 reg = FDI_TX_CTL(pipe);
4090                 temp = I915_READ(reg);
4091                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4092                 temp |= snb_b_fdi_train_param[i];
4093                 I915_WRITE(reg, temp);
4094
4095                 POSTING_READ(reg);
4096                 udelay(500);
4097
4098                 for (retry = 0; retry < 5; retry++) {
4099                         reg = FDI_RX_IIR(pipe);
4100                         temp = I915_READ(reg);
4101                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4102                         if (temp & FDI_RX_SYMBOL_LOCK) {
4103                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4104                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4105                                 break;
4106                         }
4107                         udelay(50);
4108                 }
4109                 if (retry < 5)
4110                         break;
4111         }
4112         if (i == 4)
4113                 DRM_ERROR("FDI train 2 fail!\n");
4114
4115         DRM_DEBUG_KMS("FDI train done.\n");
4116 }
4117
4118 /* Manual link training for Ivy Bridge A0 parts */
4119 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4120                                       const struct intel_crtc_state *crtc_state)
4121 {
4122         struct drm_device *dev = crtc->base.dev;
4123         struct drm_i915_private *dev_priv = to_i915(dev);
4124         int pipe = crtc->pipe;
4125         i915_reg_t reg;
4126         u32 temp, i, j;
4127
4128         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4129            for train result */
4130         reg = FDI_RX_IMR(pipe);
4131         temp = I915_READ(reg);
4132         temp &= ~FDI_RX_SYMBOL_LOCK;
4133         temp &= ~FDI_RX_BIT_LOCK;
4134         I915_WRITE(reg, temp);
4135
4136         POSTING_READ(reg);
4137         udelay(150);
4138
4139         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4140                       I915_READ(FDI_RX_IIR(pipe)));
4141
4142         /* Try each vswing and preemphasis setting twice before moving on */
4143         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4144                 /* disable first in case we need to retry */
4145                 reg = FDI_TX_CTL(pipe);
4146                 temp = I915_READ(reg);
4147                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4148                 temp &= ~FDI_TX_ENABLE;
4149                 I915_WRITE(reg, temp);
4150
4151                 reg = FDI_RX_CTL(pipe);
4152                 temp = I915_READ(reg);
4153                 temp &= ~FDI_LINK_TRAIN_AUTO;
4154                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4155                 temp &= ~FDI_RX_ENABLE;
4156                 I915_WRITE(reg, temp);
4157
4158                 /* enable CPU FDI TX and PCH FDI RX */
4159                 reg = FDI_TX_CTL(pipe);
4160                 temp = I915_READ(reg);
4161                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4162                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4163                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4164                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4165                 temp |= snb_b_fdi_train_param[j/2];
4166                 temp |= FDI_COMPOSITE_SYNC;
4167                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4168
4169                 I915_WRITE(FDI_RX_MISC(pipe),
4170                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4171
4172                 reg = FDI_RX_CTL(pipe);
4173                 temp = I915_READ(reg);
4174                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4175                 temp |= FDI_COMPOSITE_SYNC;
4176                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4177
4178                 POSTING_READ(reg);
4179                 udelay(1); /* should be 0.5us */
4180
4181                 for (i = 0; i < 4; i++) {
4182                         reg = FDI_RX_IIR(pipe);
4183                         temp = I915_READ(reg);
4184                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4185
4186                         if (temp & FDI_RX_BIT_LOCK ||
4187                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4188                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4189                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4190                                               i);
4191                                 break;
4192                         }
4193                         udelay(1); /* should be 0.5us */
4194                 }
4195                 if (i == 4) {
4196                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4197                         continue;
4198                 }
4199
4200                 /* Train 2 */
4201                 reg = FDI_TX_CTL(pipe);
4202                 temp = I915_READ(reg);
4203                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4204                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4205                 I915_WRITE(reg, temp);
4206
4207                 reg = FDI_RX_CTL(pipe);
4208                 temp = I915_READ(reg);
4209                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4210                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4211                 I915_WRITE(reg, temp);
4212
4213                 POSTING_READ(reg);
4214                 udelay(2); /* should be 1.5us */
4215
4216                 for (i = 0; i < 4; i++) {
4217                         reg = FDI_RX_IIR(pipe);
4218                         temp = I915_READ(reg);
4219                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4220
4221                         if (temp & FDI_RX_SYMBOL_LOCK ||
4222                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4223                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4224                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4225                                               i);
4226                                 goto train_done;
4227                         }
4228                         udelay(2); /* should be 1.5us */
4229                 }
4230                 if (i == 4)
4231                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4232         }
4233
4234 train_done:
4235         DRM_DEBUG_KMS("FDI train done.\n");
4236 }
4237
4238 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4239 {
4240         struct drm_device *dev = intel_crtc->base.dev;
4241         struct drm_i915_private *dev_priv = to_i915(dev);
4242         int pipe = intel_crtc->pipe;
4243         i915_reg_t reg;
4244         u32 temp;
4245
4246         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4247         reg = FDI_RX_CTL(pipe);
4248         temp = I915_READ(reg);
4249         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4250         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4251         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4252         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4253
4254         POSTING_READ(reg);
4255         udelay(200);
4256
4257         /* Switch from Rawclk to PCDclk */
4258         temp = I915_READ(reg);
4259         I915_WRITE(reg, temp | FDI_PCDCLK);
4260
4261         POSTING_READ(reg);
4262         udelay(200);
4263
4264         /* Enable CPU FDI TX PLL, always on for Ironlake */
4265         reg = FDI_TX_CTL(pipe);
4266         temp = I915_READ(reg);
4267         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4268                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4269
4270                 POSTING_READ(reg);
4271                 udelay(100);
4272         }
4273 }
4274
4275 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4276 {
4277         struct drm_device *dev = intel_crtc->base.dev;
4278         struct drm_i915_private *dev_priv = to_i915(dev);
4279         int pipe = intel_crtc->pipe;
4280         i915_reg_t reg;
4281         u32 temp;
4282
4283         /* Switch from PCDclk to Rawclk */
4284         reg = FDI_RX_CTL(pipe);
4285         temp = I915_READ(reg);
4286         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4287
4288         /* Disable CPU FDI TX PLL */
4289         reg = FDI_TX_CTL(pipe);
4290         temp = I915_READ(reg);
4291         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4292
4293         POSTING_READ(reg);
4294         udelay(100);
4295
4296         reg = FDI_RX_CTL(pipe);
4297         temp = I915_READ(reg);
4298         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4299
4300         /* Wait for the clocks to turn off. */
4301         POSTING_READ(reg);
4302         udelay(100);
4303 }
4304
4305 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4306 {
4307         struct drm_device *dev = crtc->dev;
4308         struct drm_i915_private *dev_priv = to_i915(dev);
4309         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4310         int pipe = intel_crtc->pipe;
4311         i915_reg_t reg;
4312         u32 temp;
4313
4314         /* disable CPU FDI tx and PCH FDI rx */
4315         reg = FDI_TX_CTL(pipe);
4316         temp = I915_READ(reg);
4317         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4318         POSTING_READ(reg);
4319
4320         reg = FDI_RX_CTL(pipe);
4321         temp = I915_READ(reg);
4322         temp &= ~(0x7 << 16);
4323         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4324         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4325
4326         POSTING_READ(reg);
4327         udelay(100);
4328
4329         /* Ironlake workaround, disable clock pointer after downing FDI */
4330         if (HAS_PCH_IBX(dev_priv))
4331                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4332
4333         /* still set train pattern 1 */
4334         reg = FDI_TX_CTL(pipe);
4335         temp = I915_READ(reg);
4336         temp &= ~FDI_LINK_TRAIN_NONE;
4337         temp |= FDI_LINK_TRAIN_PATTERN_1;
4338         I915_WRITE(reg, temp);
4339
4340         reg = FDI_RX_CTL(pipe);
4341         temp = I915_READ(reg);
4342         if (HAS_PCH_CPT(dev_priv)) {
4343                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4344                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4345         } else {
4346                 temp &= ~FDI_LINK_TRAIN_NONE;
4347                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4348         }
4349         /* BPC in FDI rx is consistent with that in PIPECONF */
4350         temp &= ~(0x07 << 16);
4351         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4352         I915_WRITE(reg, temp);
4353
4354         POSTING_READ(reg);
4355         udelay(100);
4356 }
4357
4358 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4359 {
4360         struct drm_crtc *crtc;
4361         bool cleanup_done;
4362
4363         drm_for_each_crtc(crtc, &dev_priv->drm) {
4364                 struct drm_crtc_commit *commit;
4365                 spin_lock(&crtc->commit_lock);
4366                 commit = list_first_entry_or_null(&crtc->commit_list,
4367                                                   struct drm_crtc_commit, commit_entry);
4368                 cleanup_done = commit ?
4369                         try_wait_for_completion(&commit->cleanup_done) : true;
4370                 spin_unlock(&crtc->commit_lock);
4371
4372                 if (cleanup_done)
4373                         continue;
4374
4375                 drm_crtc_wait_one_vblank(crtc);
4376
4377                 return true;
4378         }
4379
4380         return false;
4381 }
4382
4383 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4384 {
4385         u32 temp;
4386
4387         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4388
4389         mutex_lock(&dev_priv->sb_lock);
4390
4391         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4392         temp |= SBI_SSCCTL_DISABLE;
4393         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4394
4395         mutex_unlock(&dev_priv->sb_lock);
4396 }
4397
4398 /* Program iCLKIP clock to the desired frequency */
4399 static void lpt_program_iclkip(struct intel_crtc *crtc)
4400 {
4401         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4402         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4403         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4404         u32 temp;
4405
4406         lpt_disable_iclkip(dev_priv);
4407
4408         /* The iCLK virtual clock root frequency is in MHz,
4409          * but the adjusted_mode->crtc_clock in in KHz. To get the
4410          * divisors, it is necessary to divide one by another, so we
4411          * convert the virtual clock precision to KHz here for higher
4412          * precision.
4413          */
4414         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4415                 u32 iclk_virtual_root_freq = 172800 * 1000;
4416                 u32 iclk_pi_range = 64;
4417                 u32 desired_divisor;
4418
4419                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4420                                                     clock << auxdiv);
4421                 divsel = (desired_divisor / iclk_pi_range) - 2;
4422                 phaseinc = desired_divisor % iclk_pi_range;
4423
4424                 /*
4425                  * Near 20MHz is a corner case which is
4426                  * out of range for the 7-bit divisor
4427                  */
4428                 if (divsel <= 0x7f)
4429                         break;
4430         }
4431
4432         /* This should not happen with any sane values */
4433         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4434                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4435         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4436                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4437
4438         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4439                         clock,
4440                         auxdiv,
4441                         divsel,
4442                         phasedir,
4443                         phaseinc);
4444
4445         mutex_lock(&dev_priv->sb_lock);
4446
4447         /* Program SSCDIVINTPHASE6 */
4448         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4449         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4450         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4451         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4452         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4453         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4454         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4455         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4456
4457         /* Program SSCAUXDIV */
4458         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4459         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4460         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4461         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4462
4463         /* Enable modulator and associated divider */
4464         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4465         temp &= ~SBI_SSCCTL_DISABLE;
4466         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4467
4468         mutex_unlock(&dev_priv->sb_lock);
4469
4470         /* Wait for initialization time */
4471         udelay(24);
4472
4473         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4474 }
4475
4476 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4477 {
4478         u32 divsel, phaseinc, auxdiv;
4479         u32 iclk_virtual_root_freq = 172800 * 1000;
4480         u32 iclk_pi_range = 64;
4481         u32 desired_divisor;
4482         u32 temp;
4483
4484         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4485                 return 0;
4486
4487         mutex_lock(&dev_priv->sb_lock);
4488
4489         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4490         if (temp & SBI_SSCCTL_DISABLE) {
4491                 mutex_unlock(&dev_priv->sb_lock);
4492                 return 0;
4493         }
4494
4495         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4496         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4497                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4498         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4499                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4500
4501         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4502         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4503                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4504
4505         mutex_unlock(&dev_priv->sb_lock);
4506
4507         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4508
4509         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4510                                  desired_divisor << auxdiv);
4511 }
4512
4513 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4514                                                 enum pipe pch_transcoder)
4515 {
4516         struct drm_device *dev = crtc->base.dev;
4517         struct drm_i915_private *dev_priv = to_i915(dev);
4518         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4519
4520         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4521                    I915_READ(HTOTAL(cpu_transcoder)));
4522         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4523                    I915_READ(HBLANK(cpu_transcoder)));
4524         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4525                    I915_READ(HSYNC(cpu_transcoder)));
4526
4527         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4528                    I915_READ(VTOTAL(cpu_transcoder)));
4529         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4530                    I915_READ(VBLANK(cpu_transcoder)));
4531         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4532                    I915_READ(VSYNC(cpu_transcoder)));
4533         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4534                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4535 }
4536
4537 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4538 {
4539         struct drm_i915_private *dev_priv = to_i915(dev);
4540         uint32_t temp;
4541
4542         temp = I915_READ(SOUTH_CHICKEN1);
4543         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4544                 return;
4545
4546         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4547         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4548
4549         temp &= ~FDI_BC_BIFURCATION_SELECT;
4550         if (enable)
4551                 temp |= FDI_BC_BIFURCATION_SELECT;
4552
4553         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4554         I915_WRITE(SOUTH_CHICKEN1, temp);
4555         POSTING_READ(SOUTH_CHICKEN1);
4556 }
4557
4558 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4559 {
4560         struct drm_device *dev = intel_crtc->base.dev;
4561
4562         switch (intel_crtc->pipe) {
4563         case PIPE_A:
4564                 break;
4565         case PIPE_B:
4566                 if (intel_crtc->config->fdi_lanes > 2)
4567                         cpt_set_fdi_bc_bifurcation(dev, false);
4568                 else
4569                         cpt_set_fdi_bc_bifurcation(dev, true);
4570
4571                 break;
4572         case PIPE_C:
4573                 cpt_set_fdi_bc_bifurcation(dev, true);
4574
4575                 break;
4576         default:
4577                 BUG();
4578         }
4579 }
4580
4581 /* Return which DP Port should be selected for Transcoder DP control */
4582 static enum port
4583 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4584 {
4585         struct drm_device *dev = crtc->base.dev;
4586         struct intel_encoder *encoder;
4587
4588         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4589                 if (encoder->type == INTEL_OUTPUT_DP ||
4590                     encoder->type == INTEL_OUTPUT_EDP)
4591                         return encoder->port;
4592         }
4593
4594         return -1;
4595 }
4596
4597 /*
4598  * Enable PCH resources required for PCH ports:
4599  *   - PCH PLLs
4600  *   - FDI training & RX/TX
4601  *   - update transcoder timings
4602  *   - DP transcoding bits
4603  *   - transcoder
4604  */
4605 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4606 {
4607         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4608         struct drm_device *dev = crtc->base.dev;
4609         struct drm_i915_private *dev_priv = to_i915(dev);
4610         int pipe = crtc->pipe;
4611         u32 temp;
4612
4613         assert_pch_transcoder_disabled(dev_priv, pipe);
4614
4615         if (IS_IVYBRIDGE(dev_priv))
4616                 ivybridge_update_fdi_bc_bifurcation(crtc);
4617
4618         /* Write the TU size bits before fdi link training, so that error
4619          * detection works. */
4620         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4621                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4622
4623         /* For PCH output, training FDI link */
4624         dev_priv->display.fdi_link_train(crtc, crtc_state);
4625
4626         /* We need to program the right clock selection before writing the pixel
4627          * mutliplier into the DPLL. */
4628         if (HAS_PCH_CPT(dev_priv)) {
4629                 u32 sel;
4630
4631                 temp = I915_READ(PCH_DPLL_SEL);
4632                 temp |= TRANS_DPLL_ENABLE(pipe);
4633                 sel = TRANS_DPLLB_SEL(pipe);
4634                 if (crtc_state->shared_dpll ==
4635                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4636                         temp |= sel;
4637                 else
4638                         temp &= ~sel;
4639                 I915_WRITE(PCH_DPLL_SEL, temp);
4640         }
4641
4642         /* XXX: pch pll's can be enabled any time before we enable the PCH
4643          * transcoder, and we actually should do this to not upset any PCH
4644          * transcoder that already use the clock when we share it.
4645          *
4646          * Note that enable_shared_dpll tries to do the right thing, but
4647          * get_shared_dpll unconditionally resets the pll - we need that to have
4648          * the right LVDS enable sequence. */
4649         intel_enable_shared_dpll(crtc);
4650
4651         /* set transcoder timing, panel must allow it */
4652         assert_panel_unlocked(dev_priv, pipe);
4653         ironlake_pch_transcoder_set_timings(crtc, pipe);
4654
4655         intel_fdi_normal_train(crtc);
4656
4657         /* For PCH DP, enable TRANS_DP_CTL */
4658         if (HAS_PCH_CPT(dev_priv) &&
4659             intel_crtc_has_dp_encoder(crtc_state)) {
4660                 const struct drm_display_mode *adjusted_mode =
4661                         &crtc_state->base.adjusted_mode;
4662                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4663                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4664                 temp = I915_READ(reg);
4665                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4666                           TRANS_DP_SYNC_MASK |
4667                           TRANS_DP_BPC_MASK);
4668                 temp |= TRANS_DP_OUTPUT_ENABLE;
4669                 temp |= bpc << 9; /* same format but at 11:9 */
4670
4671                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4672                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4673                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4674                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4675
4676                 switch (intel_trans_dp_port_sel(crtc)) {
4677                 case PORT_B:
4678                         temp |= TRANS_DP_PORT_SEL_B;
4679                         break;
4680                 case PORT_C:
4681                         temp |= TRANS_DP_PORT_SEL_C;
4682                         break;
4683                 case PORT_D:
4684                         temp |= TRANS_DP_PORT_SEL_D;
4685                         break;
4686                 default:
4687                         BUG();
4688                 }
4689
4690                 I915_WRITE(reg, temp);
4691         }
4692
4693         ironlake_enable_pch_transcoder(dev_priv, pipe);
4694 }
4695
4696 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4697 {
4698         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4699         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4700         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4701
4702         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4703
4704         lpt_program_iclkip(crtc);
4705
4706         /* Set transcoder timing. */
4707         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4708
4709         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4710 }
4711
4712 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4713 {
4714         struct drm_i915_private *dev_priv = to_i915(dev);
4715         i915_reg_t dslreg = PIPEDSL(pipe);
4716         u32 temp;
4717
4718         temp = I915_READ(dslreg);
4719         udelay(500);
4720         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4721                 if (wait_for(I915_READ(dslreg) != temp, 5))
4722                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4723         }
4724 }
4725
4726 static int
4727 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4728                   unsigned int scaler_user, int *scaler_id,
4729                   int src_w, int src_h, int dst_w, int dst_h,
4730                   bool plane_scaler_check,
4731                   uint32_t pixel_format)
4732 {
4733         struct intel_crtc_scaler_state *scaler_state =
4734                 &crtc_state->scaler_state;
4735         struct intel_crtc *intel_crtc =
4736                 to_intel_crtc(crtc_state->base.crtc);
4737         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4738         const struct drm_display_mode *adjusted_mode =
4739                 &crtc_state->base.adjusted_mode;
4740         int need_scaling;
4741
4742         /*
4743          * Src coordinates are already rotated by 270 degrees for
4744          * the 90/270 degree plane rotation cases (to match the
4745          * GTT mapping), hence no need to account for rotation here.
4746          */
4747         need_scaling = src_w != dst_w || src_h != dst_h;
4748
4749         if (plane_scaler_check)
4750                 if (pixel_format == DRM_FORMAT_NV12)
4751                         need_scaling = true;
4752
4753         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4754                 need_scaling = true;
4755
4756         /*
4757          * Scaling/fitting not supported in IF-ID mode in GEN9+
4758          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4759          * Once NV12 is enabled, handle it here while allocating scaler
4760          * for NV12.
4761          */
4762         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4763             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4764                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4765                 return -EINVAL;
4766         }
4767
4768         /*
4769          * if plane is being disabled or scaler is no more required or force detach
4770          *  - free scaler binded to this plane/crtc
4771          *  - in order to do this, update crtc->scaler_usage
4772          *
4773          * Here scaler state in crtc_state is set free so that
4774          * scaler can be assigned to other user. Actual register
4775          * update to free the scaler is done in plane/panel-fit programming.
4776          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4777          */
4778         if (force_detach || !need_scaling) {
4779                 if (*scaler_id >= 0) {
4780                         scaler_state->scaler_users &= ~(1 << scaler_user);
4781                         scaler_state->scalers[*scaler_id].in_use = 0;
4782
4783                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4784                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4785                                 intel_crtc->pipe, scaler_user, *scaler_id,
4786                                 scaler_state->scaler_users);
4787                         *scaler_id = -1;
4788                 }
4789                 return 0;
4790         }
4791
4792         if (plane_scaler_check && pixel_format == DRM_FORMAT_NV12 &&
4793             (src_h < SKL_MIN_YUV_420_SRC_H || (src_w % 4) != 0 ||
4794              (src_h % 4) != 0)) {
4795                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4796                 return -EINVAL;
4797         }
4798
4799         /* range checks */
4800         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4801             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4802             (IS_GEN11(dev_priv) &&
4803              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4804               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4805             (!IS_GEN11(dev_priv) &&
4806              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4807               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4808                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4809                         "size is out of scaler range\n",
4810                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4811                 return -EINVAL;
4812         }
4813
4814         /* mark this plane as a scaler user in crtc_state */
4815         scaler_state->scaler_users |= (1 << scaler_user);
4816         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4817                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4818                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4819                 scaler_state->scaler_users);
4820
4821         return 0;
4822 }
4823
4824 /**
4825  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4826  *
4827  * @state: crtc's scaler state
4828  *
4829  * Return
4830  *     0 - scaler_usage updated successfully
4831  *    error - requested scaling cannot be supported or other error condition
4832  */
4833 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4834 {
4835         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4836
4837         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4838                                  &state->scaler_state.scaler_id,
4839                                  state->pipe_src_w, state->pipe_src_h,
4840                                  adjusted_mode->crtc_hdisplay,
4841                                  adjusted_mode->crtc_vdisplay, false, 0);
4842 }
4843
4844 /**
4845  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4846  * @crtc_state: crtc's scaler state
4847  * @plane_state: atomic plane state to update
4848  *
4849  * Return
4850  *     0 - scaler_usage updated successfully
4851  *    error - requested scaling cannot be supported or other error condition
4852  */
4853 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4854                                    struct intel_plane_state *plane_state)
4855 {
4856
4857         struct intel_plane *intel_plane =
4858                 to_intel_plane(plane_state->base.plane);
4859         struct drm_framebuffer *fb = plane_state->base.fb;
4860         int ret;
4861
4862         bool force_detach = !fb || !plane_state->base.visible;
4863
4864         ret = skl_update_scaler(crtc_state, force_detach,
4865                                 drm_plane_index(&intel_plane->base),
4866                                 &plane_state->scaler_id,
4867                                 drm_rect_width(&plane_state->base.src) >> 16,
4868                                 drm_rect_height(&plane_state->base.src) >> 16,
4869                                 drm_rect_width(&plane_state->base.dst),
4870                                 drm_rect_height(&plane_state->base.dst),
4871                                 fb ? true : false, fb ? fb->format->format : 0);
4872
4873         if (ret || plane_state->scaler_id < 0)
4874                 return ret;
4875
4876         /* check colorkey */
4877         if (plane_state->ckey.flags) {
4878                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4879                               intel_plane->base.base.id,
4880                               intel_plane->base.name);
4881                 return -EINVAL;
4882         }
4883
4884         /* Check src format */
4885         switch (fb->format->format) {
4886         case DRM_FORMAT_RGB565:
4887         case DRM_FORMAT_XBGR8888:
4888         case DRM_FORMAT_XRGB8888:
4889         case DRM_FORMAT_ABGR8888:
4890         case DRM_FORMAT_ARGB8888:
4891         case DRM_FORMAT_XRGB2101010:
4892         case DRM_FORMAT_XBGR2101010:
4893         case DRM_FORMAT_YUYV:
4894         case DRM_FORMAT_YVYU:
4895         case DRM_FORMAT_UYVY:
4896         case DRM_FORMAT_VYUY:
4897         case DRM_FORMAT_NV12:
4898                 break;
4899         default:
4900                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4901                               intel_plane->base.base.id, intel_plane->base.name,
4902                               fb->base.id, fb->format->format);
4903                 return -EINVAL;
4904         }
4905
4906         return 0;
4907 }
4908
4909 static void skylake_scaler_disable(struct intel_crtc *crtc)
4910 {
4911         int i;
4912
4913         for (i = 0; i < crtc->num_scalers; i++)
4914                 skl_detach_scaler(crtc, i);
4915 }
4916
4917 static void skylake_pfit_enable(struct intel_crtc *crtc)
4918 {
4919         struct drm_device *dev = crtc->base.dev;
4920         struct drm_i915_private *dev_priv = to_i915(dev);
4921         int pipe = crtc->pipe;
4922         struct intel_crtc_scaler_state *scaler_state =
4923                 &crtc->config->scaler_state;
4924
4925         if (crtc->config->pch_pfit.enabled) {
4926                 int id;
4927
4928                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4929                         return;
4930
4931                 id = scaler_state->scaler_id;
4932                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4933                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4934                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4935                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4936         }
4937 }
4938
4939 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4940 {
4941         struct drm_device *dev = crtc->base.dev;
4942         struct drm_i915_private *dev_priv = to_i915(dev);
4943         int pipe = crtc->pipe;
4944
4945         if (crtc->config->pch_pfit.enabled) {
4946                 /* Force use of hard-coded filter coefficients
4947                  * as some pre-programmed values are broken,
4948                  * e.g. x201.
4949                  */
4950                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4951                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4952                                                  PF_PIPE_SEL_IVB(pipe));
4953                 else
4954                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4955                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4956                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4957         }
4958 }
4959
4960 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
4961 {
4962         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4963         struct drm_device *dev = crtc->base.dev;
4964         struct drm_i915_private *dev_priv = to_i915(dev);
4965
4966         if (!crtc_state->ips_enabled)
4967                 return;
4968
4969         /*
4970          * We can only enable IPS after we enable a plane and wait for a vblank
4971          * This function is called from post_plane_update, which is run after
4972          * a vblank wait.
4973          */
4974         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
4975
4976         if (IS_BROADWELL(dev_priv)) {
4977                 mutex_lock(&dev_priv->pcu_lock);
4978                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
4979                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
4980                 mutex_unlock(&dev_priv->pcu_lock);
4981                 /* Quoting Art Runyan: "its not safe to expect any particular
4982                  * value in IPS_CTL bit 31 after enabling IPS through the
4983                  * mailbox." Moreover, the mailbox may return a bogus state,
4984                  * so we need to just enable it and continue on.
4985                  */
4986         } else {
4987                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4988                 /* The bit only becomes 1 in the next vblank, so this wait here
4989                  * is essentially intel_wait_for_vblank. If we don't have this
4990                  * and don't wait for vblanks until the end of crtc_enable, then
4991                  * the HW state readout code will complain that the expected
4992                  * IPS_CTL value is not the one we read. */
4993                 if (intel_wait_for_register(dev_priv,
4994                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4995                                             50))
4996                         DRM_ERROR("Timed out waiting for IPS enable\n");
4997         }
4998 }
4999
5000 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5001 {
5002         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5003         struct drm_device *dev = crtc->base.dev;
5004         struct drm_i915_private *dev_priv = to_i915(dev);
5005
5006         if (!crtc_state->ips_enabled)
5007                 return;
5008
5009         if (IS_BROADWELL(dev_priv)) {
5010                 mutex_lock(&dev_priv->pcu_lock);
5011                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5012                 mutex_unlock(&dev_priv->pcu_lock);
5013                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
5014                 if (intel_wait_for_register(dev_priv,
5015                                             IPS_CTL, IPS_ENABLE, 0,
5016                                             42))
5017                         DRM_ERROR("Timed out waiting for IPS disable\n");
5018         } else {
5019                 I915_WRITE(IPS_CTL, 0);
5020                 POSTING_READ(IPS_CTL);
5021         }
5022
5023         /* We need to wait for a vblank before we can disable the plane. */
5024         intel_wait_for_vblank(dev_priv, crtc->pipe);
5025 }
5026
5027 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5028 {
5029         if (intel_crtc->overlay) {
5030                 struct drm_device *dev = intel_crtc->base.dev;
5031
5032                 mutex_lock(&dev->struct_mutex);
5033                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5034                 mutex_unlock(&dev->struct_mutex);
5035         }
5036
5037         /* Let userspace switch the overlay on again. In most cases userspace
5038          * has to recompute where to put it anyway.
5039          */
5040 }
5041
5042 /**
5043  * intel_post_enable_primary - Perform operations after enabling primary plane
5044  * @crtc: the CRTC whose primary plane was just enabled
5045  * @new_crtc_state: the enabling state
5046  *
5047  * Performs potentially sleeping operations that must be done after the primary
5048  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5049  * called due to an explicit primary plane update, or due to an implicit
5050  * re-enable that is caused when a sprite plane is updated to no longer
5051  * completely hide the primary plane.
5052  */
5053 static void
5054 intel_post_enable_primary(struct drm_crtc *crtc,
5055                           const struct intel_crtc_state *new_crtc_state)
5056 {
5057         struct drm_device *dev = crtc->dev;
5058         struct drm_i915_private *dev_priv = to_i915(dev);
5059         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5060         int pipe = intel_crtc->pipe;
5061
5062         /*
5063          * Gen2 reports pipe underruns whenever all planes are disabled.
5064          * So don't enable underrun reporting before at least some planes
5065          * are enabled.
5066          * FIXME: Need to fix the logic to work when we turn off all planes
5067          * but leave the pipe running.
5068          */
5069         if (IS_GEN2(dev_priv))
5070                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5071
5072         /* Underruns don't always raise interrupts, so check manually. */
5073         intel_check_cpu_fifo_underruns(dev_priv);
5074         intel_check_pch_fifo_underruns(dev_priv);
5075 }
5076
5077 /* FIXME get rid of this and use pre_plane_update */
5078 static void
5079 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5080 {
5081         struct drm_device *dev = crtc->dev;
5082         struct drm_i915_private *dev_priv = to_i915(dev);
5083         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5084         int pipe = intel_crtc->pipe;
5085
5086         /*
5087          * Gen2 reports pipe underruns whenever all planes are disabled.
5088          * So disable underrun reporting before all the planes get disabled.
5089          */
5090         if (IS_GEN2(dev_priv))
5091                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5092
5093         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5094
5095         /*
5096          * Vblank time updates from the shadow to live plane control register
5097          * are blocked if the memory self-refresh mode is active at that
5098          * moment. So to make sure the plane gets truly disabled, disable
5099          * first the self-refresh mode. The self-refresh enable bit in turn
5100          * will be checked/applied by the HW only at the next frame start
5101          * event which is after the vblank start event, so we need to have a
5102          * wait-for-vblank between disabling the plane and the pipe.
5103          */
5104         if (HAS_GMCH_DISPLAY(dev_priv) &&
5105             intel_set_memory_cxsr(dev_priv, false))
5106                 intel_wait_for_vblank(dev_priv, pipe);
5107 }
5108
5109 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5110                                        const struct intel_crtc_state *new_crtc_state)
5111 {
5112         if (!old_crtc_state->ips_enabled)
5113                 return false;
5114
5115         if (needs_modeset(&new_crtc_state->base))
5116                 return true;
5117
5118         return !new_crtc_state->ips_enabled;
5119 }
5120
5121 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5122                                        const struct intel_crtc_state *new_crtc_state)
5123 {
5124         if (!new_crtc_state->ips_enabled)
5125                 return false;
5126
5127         if (needs_modeset(&new_crtc_state->base))
5128                 return true;
5129
5130         /*
5131          * We can't read out IPS on broadwell, assume the worst and
5132          * forcibly enable IPS on the first fastset.
5133          */
5134         if (new_crtc_state->update_pipe &&
5135             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5136                 return true;
5137
5138         return !old_crtc_state->ips_enabled;
5139 }
5140
5141 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5142 {
5143         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5144         struct drm_device *dev = crtc->base.dev;
5145         struct drm_i915_private *dev_priv = to_i915(dev);
5146         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5147         struct intel_crtc_state *pipe_config =
5148                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5149                                                 crtc);
5150         struct drm_plane *primary = crtc->base.primary;
5151         struct drm_plane_state *old_primary_state =
5152                 drm_atomic_get_old_plane_state(old_state, primary);
5153
5154         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5155
5156         if (pipe_config->update_wm_post && pipe_config->base.active)
5157                 intel_update_watermarks(crtc);
5158
5159         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5160                 hsw_enable_ips(pipe_config);
5161
5162         if (old_primary_state) {
5163                 struct drm_plane_state *new_primary_state =
5164                         drm_atomic_get_new_plane_state(old_state, primary);
5165                 struct drm_framebuffer *fb = new_primary_state->fb;
5166
5167                 intel_fbc_post_update(crtc);
5168
5169                 if (new_primary_state->visible &&
5170                     (needs_modeset(&pipe_config->base) ||
5171                      !old_primary_state->visible))
5172                         intel_post_enable_primary(&crtc->base, pipe_config);
5173
5174                 /* Display WA 827 */
5175                 if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5176                     IS_CANNONLAKE(dev_priv)) {
5177                         if (fb && fb->format->format == DRM_FORMAT_NV12)
5178                                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5179                 }
5180
5181         }
5182 }
5183
5184 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5185                                    struct intel_crtc_state *pipe_config)
5186 {
5187         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5188         struct drm_device *dev = crtc->base.dev;
5189         struct drm_i915_private *dev_priv = to_i915(dev);
5190         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5191         struct drm_plane *primary = crtc->base.primary;
5192         struct drm_plane_state *old_primary_state =
5193                 drm_atomic_get_old_plane_state(old_state, primary);
5194         bool modeset = needs_modeset(&pipe_config->base);
5195         struct intel_atomic_state *old_intel_state =
5196                 to_intel_atomic_state(old_state);
5197
5198         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5199                 hsw_disable_ips(old_crtc_state);
5200
5201         if (old_primary_state) {
5202                 struct intel_plane_state *new_primary_state =
5203                         intel_atomic_get_new_plane_state(old_intel_state,
5204                                                          to_intel_plane(primary));
5205                 struct drm_framebuffer *fb = new_primary_state->base.fb;
5206
5207                 /* Display WA 827 */
5208                 if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5209                     IS_CANNONLAKE(dev_priv)) {
5210                         if (fb && fb->format->format == DRM_FORMAT_NV12)
5211                                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5212                 }
5213
5214                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5215                 /*
5216                  * Gen2 reports pipe underruns whenever all planes are disabled.
5217                  * So disable underrun reporting before all the planes get disabled.
5218                  */
5219                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5220                     (modeset || !new_primary_state->base.visible))
5221                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5222         }
5223
5224         /*
5225          * Vblank time updates from the shadow to live plane control register
5226          * are blocked if the memory self-refresh mode is active at that
5227          * moment. So to make sure the plane gets truly disabled, disable
5228          * first the self-refresh mode. The self-refresh enable bit in turn
5229          * will be checked/applied by the HW only at the next frame start
5230          * event which is after the vblank start event, so we need to have a
5231          * wait-for-vblank between disabling the plane and the pipe.
5232          */
5233         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5234             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5235                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5236
5237         /*
5238          * IVB workaround: must disable low power watermarks for at least
5239          * one frame before enabling scaling.  LP watermarks can be re-enabled
5240          * when scaling is disabled.
5241          *
5242          * WaCxSRDisabledForSpriteScaling:ivb
5243          */
5244         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5245                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5246
5247         /*
5248          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5249          * watermark programming here.
5250          */
5251         if (needs_modeset(&pipe_config->base))
5252                 return;
5253
5254         /*
5255          * For platforms that support atomic watermarks, program the
5256          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5257          * will be the intermediate values that are safe for both pre- and
5258          * post- vblank; when vblank happens, the 'active' values will be set
5259          * to the final 'target' values and we'll do this again to get the
5260          * optimal watermarks.  For gen9+ platforms, the values we program here
5261          * will be the final target values which will get automatically latched
5262          * at vblank time; no further programming will be necessary.
5263          *
5264          * If a platform hasn't been transitioned to atomic watermarks yet,
5265          * we'll continue to update watermarks the old way, if flags tell
5266          * us to.
5267          */
5268         if (dev_priv->display.initial_watermarks != NULL)
5269                 dev_priv->display.initial_watermarks(old_intel_state,
5270                                                      pipe_config);
5271         else if (pipe_config->update_wm_pre)
5272                 intel_update_watermarks(crtc);
5273 }
5274
5275 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5276 {
5277         struct drm_device *dev = crtc->dev;
5278         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5279         struct drm_plane *p;
5280         int pipe = intel_crtc->pipe;
5281
5282         intel_crtc_dpms_overlay_disable(intel_crtc);
5283
5284         drm_for_each_plane_mask(p, dev, plane_mask)
5285                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5286
5287         /*
5288          * FIXME: Once we grow proper nuclear flip support out of this we need
5289          * to compute the mask of flip planes precisely. For the time being
5290          * consider this a flip to a NULL plane.
5291          */
5292         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5293 }
5294
5295 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5296                                           struct intel_crtc_state *crtc_state,
5297                                           struct drm_atomic_state *old_state)
5298 {
5299         struct drm_connector_state *conn_state;
5300         struct drm_connector *conn;
5301         int i;
5302
5303         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5304                 struct intel_encoder *encoder =
5305                         to_intel_encoder(conn_state->best_encoder);
5306
5307                 if (conn_state->crtc != crtc)
5308                         continue;
5309
5310                 if (encoder->pre_pll_enable)
5311                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5312         }
5313 }
5314
5315 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5316                                       struct intel_crtc_state *crtc_state,
5317                                       struct drm_atomic_state *old_state)
5318 {
5319         struct drm_connector_state *conn_state;
5320         struct drm_connector *conn;
5321         int i;
5322
5323         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5324                 struct intel_encoder *encoder =
5325                         to_intel_encoder(conn_state->best_encoder);
5326
5327                 if (conn_state->crtc != crtc)
5328                         continue;
5329
5330                 if (encoder->pre_enable)
5331                         encoder->pre_enable(encoder, crtc_state, conn_state);
5332         }
5333 }
5334
5335 static void intel_encoders_enable(struct drm_crtc *crtc,
5336                                   struct intel_crtc_state *crtc_state,
5337                                   struct drm_atomic_state *old_state)
5338 {
5339         struct drm_connector_state *conn_state;
5340         struct drm_connector *conn;
5341         int i;
5342
5343         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5344                 struct intel_encoder *encoder =
5345                         to_intel_encoder(conn_state->best_encoder);
5346
5347                 if (conn_state->crtc != crtc)
5348                         continue;
5349
5350                 encoder->enable(encoder, crtc_state, conn_state);
5351                 intel_opregion_notify_encoder(encoder, true);
5352         }
5353 }
5354
5355 static void intel_encoders_disable(struct drm_crtc *crtc,
5356                                    struct intel_crtc_state *old_crtc_state,
5357                                    struct drm_atomic_state *old_state)
5358 {
5359         struct drm_connector_state *old_conn_state;
5360         struct drm_connector *conn;
5361         int i;
5362
5363         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5364                 struct intel_encoder *encoder =
5365                         to_intel_encoder(old_conn_state->best_encoder);
5366
5367                 if (old_conn_state->crtc != crtc)
5368                         continue;
5369
5370                 intel_opregion_notify_encoder(encoder, false);
5371                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5372         }
5373 }
5374
5375 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5376                                         struct intel_crtc_state *old_crtc_state,
5377                                         struct drm_atomic_state *old_state)
5378 {
5379         struct drm_connector_state *old_conn_state;
5380         struct drm_connector *conn;
5381         int i;
5382
5383         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5384                 struct intel_encoder *encoder =
5385                         to_intel_encoder(old_conn_state->best_encoder);
5386
5387                 if (old_conn_state->crtc != crtc)
5388                         continue;
5389
5390                 if (encoder->post_disable)
5391                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5392         }
5393 }
5394
5395 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5396                                             struct intel_crtc_state *old_crtc_state,
5397                                             struct drm_atomic_state *old_state)
5398 {
5399         struct drm_connector_state *old_conn_state;
5400         struct drm_connector *conn;
5401         int i;
5402
5403         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5404                 struct intel_encoder *encoder =
5405                         to_intel_encoder(old_conn_state->best_encoder);
5406
5407                 if (old_conn_state->crtc != crtc)
5408                         continue;
5409
5410                 if (encoder->post_pll_disable)
5411                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5412         }
5413 }
5414
5415 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5416                                  struct drm_atomic_state *old_state)
5417 {
5418         struct drm_crtc *crtc = pipe_config->base.crtc;
5419         struct drm_device *dev = crtc->dev;
5420         struct drm_i915_private *dev_priv = to_i915(dev);
5421         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5422         int pipe = intel_crtc->pipe;
5423         struct intel_atomic_state *old_intel_state =
5424                 to_intel_atomic_state(old_state);
5425
5426         if (WARN_ON(intel_crtc->active))
5427                 return;
5428
5429         /*
5430          * Sometimes spurious CPU pipe underruns happen during FDI
5431          * training, at least with VGA+HDMI cloning. Suppress them.
5432          *
5433          * On ILK we get an occasional spurious CPU pipe underruns
5434          * between eDP port A enable and vdd enable. Also PCH port
5435          * enable seems to result in the occasional CPU pipe underrun.
5436          *
5437          * Spurious PCH underruns also occur during PCH enabling.
5438          */
5439         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5440                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5441         if (intel_crtc->config->has_pch_encoder)
5442                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5443
5444         if (intel_crtc->config->has_pch_encoder)
5445                 intel_prepare_shared_dpll(intel_crtc);
5446
5447         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5448                 intel_dp_set_m_n(intel_crtc, M1_N1);
5449
5450         intel_set_pipe_timings(intel_crtc);
5451         intel_set_pipe_src_size(intel_crtc);
5452
5453         if (intel_crtc->config->has_pch_encoder) {
5454                 intel_cpu_transcoder_set_m_n(intel_crtc,
5455                                      &intel_crtc->config->fdi_m_n, NULL);
5456         }
5457
5458         ironlake_set_pipeconf(crtc);
5459
5460         intel_crtc->active = true;
5461
5462         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5463
5464         if (intel_crtc->config->has_pch_encoder) {
5465                 /* Note: FDI PLL enabling _must_ be done before we enable the
5466                  * cpu pipes, hence this is separate from all the other fdi/pch
5467                  * enabling. */
5468                 ironlake_fdi_pll_enable(intel_crtc);
5469         } else {
5470                 assert_fdi_tx_disabled(dev_priv, pipe);
5471                 assert_fdi_rx_disabled(dev_priv, pipe);
5472         }
5473
5474         ironlake_pfit_enable(intel_crtc);
5475
5476         /*
5477          * On ILK+ LUT must be loaded before the pipe is running but with
5478          * clocks enabled
5479          */
5480         intel_color_load_luts(&pipe_config->base);
5481
5482         if (dev_priv->display.initial_watermarks != NULL)
5483                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5484         intel_enable_pipe(pipe_config);
5485
5486         if (intel_crtc->config->has_pch_encoder)
5487                 ironlake_pch_enable(pipe_config);
5488
5489         assert_vblank_disabled(crtc);
5490         drm_crtc_vblank_on(crtc);
5491
5492         intel_encoders_enable(crtc, pipe_config, old_state);
5493
5494         if (HAS_PCH_CPT(dev_priv))
5495                 cpt_verify_modeset(dev, intel_crtc->pipe);
5496
5497         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5498         if (intel_crtc->config->has_pch_encoder)
5499                 intel_wait_for_vblank(dev_priv, pipe);
5500         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5501         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5502 }
5503
5504 /* IPS only exists on ULT machines and is tied to pipe A. */
5505 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5506 {
5507         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5508 }
5509
5510 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5511                                             enum pipe pipe, bool apply)
5512 {
5513         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5514         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5515
5516         if (apply)
5517                 val |= mask;
5518         else
5519                 val &= ~mask;
5520
5521         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5522 }
5523
5524 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5525 {
5526         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5527         enum pipe pipe = crtc->pipe;
5528         uint32_t val;
5529
5530         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5531
5532         /* Program B credit equally to all pipes */
5533         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5534
5535         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5536 }
5537
5538 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5539                                 struct drm_atomic_state *old_state)
5540 {
5541         struct drm_crtc *crtc = pipe_config->base.crtc;
5542         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5543         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5544         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5545         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5546         struct intel_atomic_state *old_intel_state =
5547                 to_intel_atomic_state(old_state);
5548         bool psl_clkgate_wa;
5549
5550         if (WARN_ON(intel_crtc->active))
5551                 return;
5552
5553         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5554
5555         if (intel_crtc->config->shared_dpll)
5556                 intel_enable_shared_dpll(intel_crtc);
5557
5558         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5559                 intel_dp_set_m_n(intel_crtc, M1_N1);
5560
5561         if (!transcoder_is_dsi(cpu_transcoder))
5562                 intel_set_pipe_timings(intel_crtc);
5563
5564         intel_set_pipe_src_size(intel_crtc);
5565
5566         if (cpu_transcoder != TRANSCODER_EDP &&
5567             !transcoder_is_dsi(cpu_transcoder)) {
5568                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5569                            intel_crtc->config->pixel_multiplier - 1);
5570         }
5571
5572         if (intel_crtc->config->has_pch_encoder) {
5573                 intel_cpu_transcoder_set_m_n(intel_crtc,
5574                                      &intel_crtc->config->fdi_m_n, NULL);
5575         }
5576
5577         if (!transcoder_is_dsi(cpu_transcoder))
5578                 haswell_set_pipeconf(crtc);
5579
5580         haswell_set_pipemisc(crtc);
5581
5582         intel_color_set_csc(&pipe_config->base);
5583
5584         intel_crtc->active = true;
5585
5586         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5587
5588         if (!transcoder_is_dsi(cpu_transcoder))
5589                 intel_ddi_enable_pipe_clock(pipe_config);
5590
5591         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5592         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5593                          intel_crtc->config->pch_pfit.enabled;
5594         if (psl_clkgate_wa)
5595                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5596
5597         if (INTEL_GEN(dev_priv) >= 9)
5598                 skylake_pfit_enable(intel_crtc);
5599         else
5600                 ironlake_pfit_enable(intel_crtc);
5601
5602         /*
5603          * On ILK+ LUT must be loaded before the pipe is running but with
5604          * clocks enabled
5605          */
5606         intel_color_load_luts(&pipe_config->base);
5607
5608         intel_ddi_set_pipe_settings(pipe_config);
5609         if (!transcoder_is_dsi(cpu_transcoder))
5610                 intel_ddi_enable_transcoder_func(pipe_config);
5611
5612         if (dev_priv->display.initial_watermarks != NULL)
5613                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5614
5615         if (INTEL_GEN(dev_priv) >= 11)
5616                 icl_pipe_mbus_enable(intel_crtc);
5617
5618         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5619         if (!transcoder_is_dsi(cpu_transcoder))
5620                 intel_enable_pipe(pipe_config);
5621
5622         if (intel_crtc->config->has_pch_encoder)
5623                 lpt_pch_enable(pipe_config);
5624
5625         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5626                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5627
5628         assert_vblank_disabled(crtc);
5629         drm_crtc_vblank_on(crtc);
5630
5631         intel_encoders_enable(crtc, pipe_config, old_state);
5632
5633         if (psl_clkgate_wa) {
5634                 intel_wait_for_vblank(dev_priv, pipe);
5635                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5636         }
5637
5638         /* If we change the relative order between pipe/planes enabling, we need
5639          * to change the workaround. */
5640         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5641         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5642                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5643                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5644         }
5645 }
5646
5647 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5648 {
5649         struct drm_device *dev = crtc->base.dev;
5650         struct drm_i915_private *dev_priv = to_i915(dev);
5651         int pipe = crtc->pipe;
5652
5653         /* To avoid upsetting the power well on haswell only disable the pfit if
5654          * it's in use. The hw state code will make sure we get this right. */
5655         if (force || crtc->config->pch_pfit.enabled) {
5656                 I915_WRITE(PF_CTL(pipe), 0);
5657                 I915_WRITE(PF_WIN_POS(pipe), 0);
5658                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5659         }
5660 }
5661
5662 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5663                                   struct drm_atomic_state *old_state)
5664 {
5665         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5666         struct drm_device *dev = crtc->dev;
5667         struct drm_i915_private *dev_priv = to_i915(dev);
5668         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5669         int pipe = intel_crtc->pipe;
5670
5671         /*
5672          * Sometimes spurious CPU pipe underruns happen when the
5673          * pipe is already disabled, but FDI RX/TX is still enabled.
5674          * Happens at least with VGA+HDMI cloning. Suppress them.
5675          */
5676         if (intel_crtc->config->has_pch_encoder) {
5677                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5678                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5679         }
5680
5681         intel_encoders_disable(crtc, old_crtc_state, old_state);
5682
5683         drm_crtc_vblank_off(crtc);
5684         assert_vblank_disabled(crtc);
5685
5686         intel_disable_pipe(old_crtc_state);
5687
5688         ironlake_pfit_disable(intel_crtc, false);
5689
5690         if (intel_crtc->config->has_pch_encoder)
5691                 ironlake_fdi_disable(crtc);
5692
5693         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5694
5695         if (intel_crtc->config->has_pch_encoder) {
5696                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5697
5698                 if (HAS_PCH_CPT(dev_priv)) {
5699                         i915_reg_t reg;
5700                         u32 temp;
5701
5702                         /* disable TRANS_DP_CTL */
5703                         reg = TRANS_DP_CTL(pipe);
5704                         temp = I915_READ(reg);
5705                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5706                                   TRANS_DP_PORT_SEL_MASK);
5707                         temp |= TRANS_DP_PORT_SEL_NONE;
5708                         I915_WRITE(reg, temp);
5709
5710                         /* disable DPLL_SEL */
5711                         temp = I915_READ(PCH_DPLL_SEL);
5712                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5713                         I915_WRITE(PCH_DPLL_SEL, temp);
5714                 }
5715
5716                 ironlake_fdi_pll_disable(intel_crtc);
5717         }
5718
5719         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5720         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5721 }
5722
5723 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5724                                  struct drm_atomic_state *old_state)
5725 {
5726         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5727         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5728         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5729         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5730
5731         intel_encoders_disable(crtc, old_crtc_state, old_state);
5732
5733         drm_crtc_vblank_off(crtc);
5734         assert_vblank_disabled(crtc);
5735
5736         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5737         if (!transcoder_is_dsi(cpu_transcoder))
5738                 intel_disable_pipe(old_crtc_state);
5739
5740         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5741                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5742
5743         if (!transcoder_is_dsi(cpu_transcoder))
5744                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5745
5746         if (INTEL_GEN(dev_priv) >= 9)
5747                 skylake_scaler_disable(intel_crtc);
5748         else
5749                 ironlake_pfit_disable(intel_crtc, false);
5750
5751         if (!transcoder_is_dsi(cpu_transcoder))
5752                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5753
5754         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5755 }
5756
5757 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5758 {
5759         struct drm_device *dev = crtc->base.dev;
5760         struct drm_i915_private *dev_priv = to_i915(dev);
5761         struct intel_crtc_state *pipe_config = crtc->config;
5762
5763         if (!pipe_config->gmch_pfit.control)
5764                 return;
5765
5766         /*
5767          * The panel fitter should only be adjusted whilst the pipe is disabled,
5768          * according to register description and PRM.
5769          */
5770         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5771         assert_pipe_disabled(dev_priv, crtc->pipe);
5772
5773         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5774         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5775
5776         /* Border color in case we don't scale up to the full screen. Black by
5777          * default, change to something else for debugging. */
5778         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5779 }
5780
5781 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5782 {
5783         switch (port) {
5784         case PORT_A:
5785                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5786         case PORT_B:
5787                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5788         case PORT_C:
5789                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5790         case PORT_D:
5791                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5792         case PORT_E:
5793                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5794         case PORT_F:
5795                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5796         default:
5797                 MISSING_CASE(port);
5798                 return POWER_DOMAIN_PORT_OTHER;
5799         }
5800 }
5801
5802 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5803                                   struct intel_crtc_state *crtc_state)
5804 {
5805         struct drm_device *dev = crtc->dev;
5806         struct drm_i915_private *dev_priv = to_i915(dev);
5807         struct drm_encoder *encoder;
5808         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5809         enum pipe pipe = intel_crtc->pipe;
5810         u64 mask;
5811         enum transcoder transcoder = crtc_state->cpu_transcoder;
5812
5813         if (!crtc_state->base.active)
5814                 return 0;
5815
5816         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5817         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5818         if (crtc_state->pch_pfit.enabled ||
5819             crtc_state->pch_pfit.force_thru)
5820                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5821
5822         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5823                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5824
5825                 mask |= BIT_ULL(intel_encoder->power_domain);
5826         }
5827
5828         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5829                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5830
5831         if (crtc_state->shared_dpll)
5832                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5833
5834         return mask;
5835 }
5836
5837 static u64
5838 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5839                                struct intel_crtc_state *crtc_state)
5840 {
5841         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5842         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5843         enum intel_display_power_domain domain;
5844         u64 domains, new_domains, old_domains;
5845
5846         old_domains = intel_crtc->enabled_power_domains;
5847         intel_crtc->enabled_power_domains = new_domains =
5848                 get_crtc_power_domains(crtc, crtc_state);
5849
5850         domains = new_domains & ~old_domains;
5851
5852         for_each_power_domain(domain, domains)
5853                 intel_display_power_get(dev_priv, domain);
5854
5855         return old_domains & ~new_domains;
5856 }
5857
5858 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5859                                       u64 domains)
5860 {
5861         enum intel_display_power_domain domain;
5862
5863         for_each_power_domain(domain, domains)
5864                 intel_display_power_put(dev_priv, domain);
5865 }
5866
5867 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5868                                    struct drm_atomic_state *old_state)
5869 {
5870         struct intel_atomic_state *old_intel_state =
5871                 to_intel_atomic_state(old_state);
5872         struct drm_crtc *crtc = pipe_config->base.crtc;
5873         struct drm_device *dev = crtc->dev;
5874         struct drm_i915_private *dev_priv = to_i915(dev);
5875         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5876         int pipe = intel_crtc->pipe;
5877
5878         if (WARN_ON(intel_crtc->active))
5879                 return;
5880
5881         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5882                 intel_dp_set_m_n(intel_crtc, M1_N1);
5883
5884         intel_set_pipe_timings(intel_crtc);
5885         intel_set_pipe_src_size(intel_crtc);
5886
5887         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5888                 struct drm_i915_private *dev_priv = to_i915(dev);
5889
5890                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5891                 I915_WRITE(CHV_CANVAS(pipe), 0);
5892         }
5893
5894         i9xx_set_pipeconf(intel_crtc);
5895
5896         intel_crtc->active = true;
5897
5898         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5899
5900         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5901
5902         if (IS_CHERRYVIEW(dev_priv)) {
5903                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5904                 chv_enable_pll(intel_crtc, intel_crtc->config);
5905         } else {
5906                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5907                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5908         }
5909
5910         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5911
5912         i9xx_pfit_enable(intel_crtc);
5913
5914         intel_color_load_luts(&pipe_config->base);
5915
5916         dev_priv->display.initial_watermarks(old_intel_state,
5917                                              pipe_config);
5918         intel_enable_pipe(pipe_config);
5919
5920         assert_vblank_disabled(crtc);
5921         drm_crtc_vblank_on(crtc);
5922
5923         intel_encoders_enable(crtc, pipe_config, old_state);
5924 }
5925
5926 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5927 {
5928         struct drm_device *dev = crtc->base.dev;
5929         struct drm_i915_private *dev_priv = to_i915(dev);
5930
5931         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5932         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5933 }
5934
5935 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5936                              struct drm_atomic_state *old_state)
5937 {
5938         struct intel_atomic_state *old_intel_state =
5939                 to_intel_atomic_state(old_state);
5940         struct drm_crtc *crtc = pipe_config->base.crtc;
5941         struct drm_device *dev = crtc->dev;
5942         struct drm_i915_private *dev_priv = to_i915(dev);
5943         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5944         enum pipe pipe = intel_crtc->pipe;
5945
5946         if (WARN_ON(intel_crtc->active))
5947                 return;
5948
5949         i9xx_set_pll_dividers(intel_crtc);
5950
5951         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5952                 intel_dp_set_m_n(intel_crtc, M1_N1);
5953
5954         intel_set_pipe_timings(intel_crtc);
5955         intel_set_pipe_src_size(intel_crtc);
5956
5957         i9xx_set_pipeconf(intel_crtc);
5958
5959         intel_crtc->active = true;
5960
5961         if (!IS_GEN2(dev_priv))
5962                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5963
5964         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5965
5966         i9xx_enable_pll(intel_crtc, pipe_config);
5967
5968         i9xx_pfit_enable(intel_crtc);
5969
5970         intel_color_load_luts(&pipe_config->base);
5971
5972         if (dev_priv->display.initial_watermarks != NULL)
5973                 dev_priv->display.initial_watermarks(old_intel_state,
5974                                                      intel_crtc->config);
5975         else
5976                 intel_update_watermarks(intel_crtc);
5977         intel_enable_pipe(pipe_config);
5978
5979         assert_vblank_disabled(crtc);
5980         drm_crtc_vblank_on(crtc);
5981
5982         intel_encoders_enable(crtc, pipe_config, old_state);
5983 }
5984
5985 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5986 {
5987         struct drm_device *dev = crtc->base.dev;
5988         struct drm_i915_private *dev_priv = to_i915(dev);
5989
5990         if (!crtc->config->gmch_pfit.control)
5991                 return;
5992
5993         assert_pipe_disabled(dev_priv, crtc->pipe);
5994
5995         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5996                          I915_READ(PFIT_CONTROL));
5997         I915_WRITE(PFIT_CONTROL, 0);
5998 }
5999
6000 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6001                               struct drm_atomic_state *old_state)
6002 {
6003         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6004         struct drm_device *dev = crtc->dev;
6005         struct drm_i915_private *dev_priv = to_i915(dev);
6006         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6007         int pipe = intel_crtc->pipe;
6008
6009         /*
6010          * On gen2 planes are double buffered but the pipe isn't, so we must
6011          * wait for planes to fully turn off before disabling the pipe.
6012          */
6013         if (IS_GEN2(dev_priv))
6014                 intel_wait_for_vblank(dev_priv, pipe);
6015
6016         intel_encoders_disable(crtc, old_crtc_state, old_state);
6017
6018         drm_crtc_vblank_off(crtc);
6019         assert_vblank_disabled(crtc);
6020
6021         intel_disable_pipe(old_crtc_state);
6022
6023         i9xx_pfit_disable(intel_crtc);
6024
6025         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6026
6027         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6028                 if (IS_CHERRYVIEW(dev_priv))
6029                         chv_disable_pll(dev_priv, pipe);
6030                 else if (IS_VALLEYVIEW(dev_priv))
6031                         vlv_disable_pll(dev_priv, pipe);
6032                 else
6033                         i9xx_disable_pll(intel_crtc);
6034         }
6035
6036         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6037
6038         if (!IS_GEN2(dev_priv))
6039                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6040
6041         if (!dev_priv->display.initial_watermarks)
6042                 intel_update_watermarks(intel_crtc);
6043
6044         /* clock the pipe down to 640x480@60 to potentially save power */
6045         if (IS_I830(dev_priv))
6046                 i830_enable_pipe(dev_priv, pipe);
6047 }
6048
6049 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6050                                         struct drm_modeset_acquire_ctx *ctx)
6051 {
6052         struct intel_encoder *encoder;
6053         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6054         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6055         enum intel_display_power_domain domain;
6056         struct intel_plane *plane;
6057         u64 domains;
6058         struct drm_atomic_state *state;
6059         struct intel_crtc_state *crtc_state;
6060         int ret;
6061
6062         if (!intel_crtc->active)
6063                 return;
6064
6065         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6066                 const struct intel_plane_state *plane_state =
6067                         to_intel_plane_state(plane->base.state);
6068
6069                 if (plane_state->base.visible)
6070                         intel_plane_disable_noatomic(intel_crtc, plane);
6071         }
6072
6073         state = drm_atomic_state_alloc(crtc->dev);
6074         if (!state) {
6075                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6076                               crtc->base.id, crtc->name);
6077                 return;
6078         }
6079
6080         state->acquire_ctx = ctx;
6081
6082         /* Everything's already locked, -EDEADLK can't happen. */
6083         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6084         ret = drm_atomic_add_affected_connectors(state, crtc);
6085
6086         WARN_ON(IS_ERR(crtc_state) || ret);
6087
6088         dev_priv->display.crtc_disable(crtc_state, state);
6089
6090         drm_atomic_state_put(state);
6091
6092         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6093                       crtc->base.id, crtc->name);
6094
6095         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6096         crtc->state->active = false;
6097         intel_crtc->active = false;
6098         crtc->enabled = false;
6099         crtc->state->connector_mask = 0;
6100         crtc->state->encoder_mask = 0;
6101
6102         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6103                 encoder->base.crtc = NULL;
6104
6105         intel_fbc_disable(intel_crtc);
6106         intel_update_watermarks(intel_crtc);
6107         intel_disable_shared_dpll(intel_crtc);
6108
6109         domains = intel_crtc->enabled_power_domains;
6110         for_each_power_domain(domain, domains)
6111                 intel_display_power_put(dev_priv, domain);
6112         intel_crtc->enabled_power_domains = 0;
6113
6114         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6115         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6116         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6117 }
6118
6119 /*
6120  * turn all crtc's off, but do not adjust state
6121  * This has to be paired with a call to intel_modeset_setup_hw_state.
6122  */
6123 int intel_display_suspend(struct drm_device *dev)
6124 {
6125         struct drm_i915_private *dev_priv = to_i915(dev);
6126         struct drm_atomic_state *state;
6127         int ret;
6128
6129         state = drm_atomic_helper_suspend(dev);
6130         ret = PTR_ERR_OR_ZERO(state);
6131         if (ret)
6132                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6133         else
6134                 dev_priv->modeset_restore_state = state;
6135         return ret;
6136 }
6137
6138 void intel_encoder_destroy(struct drm_encoder *encoder)
6139 {
6140         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6141
6142         drm_encoder_cleanup(encoder);
6143         kfree(intel_encoder);
6144 }
6145
6146 /* Cross check the actual hw state with our own modeset state tracking (and it's
6147  * internal consistency). */
6148 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6149                                          struct drm_connector_state *conn_state)
6150 {
6151         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6152
6153         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6154                       connector->base.base.id,
6155                       connector->base.name);
6156
6157         if (connector->get_hw_state(connector)) {
6158                 struct intel_encoder *encoder = connector->encoder;
6159
6160                 I915_STATE_WARN(!crtc_state,
6161                          "connector enabled without attached crtc\n");
6162
6163                 if (!crtc_state)
6164                         return;
6165
6166                 I915_STATE_WARN(!crtc_state->active,
6167                       "connector is active, but attached crtc isn't\n");
6168
6169                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6170                         return;
6171
6172                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6173                         "atomic encoder doesn't match attached encoder\n");
6174
6175                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6176                         "attached encoder crtc differs from connector crtc\n");
6177         } else {
6178                 I915_STATE_WARN(crtc_state && crtc_state->active,
6179                         "attached crtc is active, but connector isn't\n");
6180                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6181                         "best encoder set without crtc!\n");
6182         }
6183 }
6184
6185 int intel_connector_init(struct intel_connector *connector)
6186 {
6187         struct intel_digital_connector_state *conn_state;
6188
6189         /*
6190          * Allocate enough memory to hold intel_digital_connector_state,
6191          * This might be a few bytes too many, but for connectors that don't
6192          * need it we'll free the state and allocate a smaller one on the first
6193          * succesful commit anyway.
6194          */
6195         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6196         if (!conn_state)
6197                 return -ENOMEM;
6198
6199         __drm_atomic_helper_connector_reset(&connector->base,
6200                                             &conn_state->base);
6201
6202         return 0;
6203 }
6204
6205 struct intel_connector *intel_connector_alloc(void)
6206 {
6207         struct intel_connector *connector;
6208
6209         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6210         if (!connector)
6211                 return NULL;
6212
6213         if (intel_connector_init(connector) < 0) {
6214                 kfree(connector);
6215                 return NULL;
6216         }
6217
6218         return connector;
6219 }
6220
6221 /*
6222  * Free the bits allocated by intel_connector_alloc.
6223  * This should only be used after intel_connector_alloc has returned
6224  * successfully, and before drm_connector_init returns successfully.
6225  * Otherwise the destroy callbacks for the connector and the state should
6226  * take care of proper cleanup/free
6227  */
6228 void intel_connector_free(struct intel_connector *connector)
6229 {
6230         kfree(to_intel_digital_connector_state(connector->base.state));
6231         kfree(connector);
6232 }
6233
6234 /* Simple connector->get_hw_state implementation for encoders that support only
6235  * one connector and no cloning and hence the encoder state determines the state
6236  * of the connector. */
6237 bool intel_connector_get_hw_state(struct intel_connector *connector)
6238 {
6239         enum pipe pipe = 0;
6240         struct intel_encoder *encoder = connector->encoder;
6241
6242         return encoder->get_hw_state(encoder, &pipe);
6243 }
6244
6245 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6246 {
6247         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6248                 return crtc_state->fdi_lanes;
6249
6250         return 0;
6251 }
6252
6253 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6254                                      struct intel_crtc_state *pipe_config)
6255 {
6256         struct drm_i915_private *dev_priv = to_i915(dev);
6257         struct drm_atomic_state *state = pipe_config->base.state;
6258         struct intel_crtc *other_crtc;
6259         struct intel_crtc_state *other_crtc_state;
6260
6261         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6262                       pipe_name(pipe), pipe_config->fdi_lanes);
6263         if (pipe_config->fdi_lanes > 4) {
6264                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6265                               pipe_name(pipe), pipe_config->fdi_lanes);
6266                 return -EINVAL;
6267         }
6268
6269         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6270                 if (pipe_config->fdi_lanes > 2) {
6271                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6272                                       pipe_config->fdi_lanes);
6273                         return -EINVAL;
6274                 } else {
6275                         return 0;
6276                 }
6277         }
6278
6279         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6280                 return 0;
6281
6282         /* Ivybridge 3 pipe is really complicated */
6283         switch (pipe) {
6284         case PIPE_A:
6285                 return 0;
6286         case PIPE_B:
6287                 if (pipe_config->fdi_lanes <= 2)
6288                         return 0;
6289
6290                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6291                 other_crtc_state =
6292                         intel_atomic_get_crtc_state(state, other_crtc);
6293                 if (IS_ERR(other_crtc_state))
6294                         return PTR_ERR(other_crtc_state);
6295
6296                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6297                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6298                                       pipe_name(pipe), pipe_config->fdi_lanes);
6299                         return -EINVAL;
6300                 }
6301                 return 0;
6302         case PIPE_C:
6303                 if (pipe_config->fdi_lanes > 2) {
6304                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6305                                       pipe_name(pipe), pipe_config->fdi_lanes);
6306                         return -EINVAL;
6307                 }
6308
6309                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6310                 other_crtc_state =
6311                         intel_atomic_get_crtc_state(state, other_crtc);
6312                 if (IS_ERR(other_crtc_state))
6313                         return PTR_ERR(other_crtc_state);
6314
6315                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6316                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6317                         return -EINVAL;
6318                 }
6319                 return 0;
6320         default:
6321                 BUG();
6322         }
6323 }
6324
6325 #define RETRY 1
6326 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6327                                        struct intel_crtc_state *pipe_config)
6328 {
6329         struct drm_device *dev = intel_crtc->base.dev;
6330         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6331         int lane, link_bw, fdi_dotclock, ret;
6332         bool needs_recompute = false;
6333
6334 retry:
6335         /* FDI is a binary signal running at ~2.7GHz, encoding
6336          * each output octet as 10 bits. The actual frequency
6337          * is stored as a divider into a 100MHz clock, and the
6338          * mode pixel clock is stored in units of 1KHz.
6339          * Hence the bw of each lane in terms of the mode signal
6340          * is:
6341          */
6342         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6343
6344         fdi_dotclock = adjusted_mode->crtc_clock;
6345
6346         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6347                                            pipe_config->pipe_bpp);
6348
6349         pipe_config->fdi_lanes = lane;
6350
6351         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6352                                link_bw, &pipe_config->fdi_m_n, false);
6353
6354         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6355         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6356                 pipe_config->pipe_bpp -= 2*3;
6357                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6358                               pipe_config->pipe_bpp);
6359                 needs_recompute = true;
6360                 pipe_config->bw_constrained = true;
6361
6362                 goto retry;
6363         }
6364
6365         if (needs_recompute)
6366                 return RETRY;
6367
6368         return ret;
6369 }
6370
6371 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6372 {
6373         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6374         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6375
6376         /* IPS only exists on ULT machines and is tied to pipe A. */
6377         if (!hsw_crtc_supports_ips(crtc))
6378                 return false;
6379
6380         if (!i915_modparams.enable_ips)
6381                 return false;
6382
6383         if (crtc_state->pipe_bpp > 24)
6384                 return false;
6385
6386         /*
6387          * We compare against max which means we must take
6388          * the increased cdclk requirement into account when
6389          * calculating the new cdclk.
6390          *
6391          * Should measure whether using a lower cdclk w/o IPS
6392          */
6393         if (IS_BROADWELL(dev_priv) &&
6394             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6395                 return false;
6396
6397         return true;
6398 }
6399
6400 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6401 {
6402         struct drm_i915_private *dev_priv =
6403                 to_i915(crtc_state->base.crtc->dev);
6404         struct intel_atomic_state *intel_state =
6405                 to_intel_atomic_state(crtc_state->base.state);
6406
6407         if (!hsw_crtc_state_ips_capable(crtc_state))
6408                 return false;
6409
6410         if (crtc_state->ips_force_disable)
6411                 return false;
6412
6413         /* IPS should be fine as long as at least one plane is enabled. */
6414         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6415                 return false;
6416
6417         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6418         if (IS_BROADWELL(dev_priv) &&
6419             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6420                 return false;
6421
6422         return true;
6423 }
6424
6425 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6426 {
6427         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6428
6429         /* GDG double wide on either pipe, otherwise pipe A only */
6430         return INTEL_GEN(dev_priv) < 4 &&
6431                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6432 }
6433
6434 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6435 {
6436         uint32_t pixel_rate;
6437
6438         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6439
6440         /*
6441          * We only use IF-ID interlacing. If we ever use
6442          * PF-ID we'll need to adjust the pixel_rate here.
6443          */
6444
6445         if (pipe_config->pch_pfit.enabled) {
6446                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6447                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6448
6449                 pipe_w = pipe_config->pipe_src_w;
6450                 pipe_h = pipe_config->pipe_src_h;
6451
6452                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6453                 pfit_h = pfit_size & 0xFFFF;
6454                 if (pipe_w < pfit_w)
6455                         pipe_w = pfit_w;
6456                 if (pipe_h < pfit_h)
6457                         pipe_h = pfit_h;
6458
6459                 if (WARN_ON(!pfit_w || !pfit_h))
6460                         return pixel_rate;
6461
6462                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6463                                      pfit_w * pfit_h);
6464         }
6465
6466         return pixel_rate;
6467 }
6468
6469 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6470 {
6471         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6472
6473         if (HAS_GMCH_DISPLAY(dev_priv))
6474                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6475                 crtc_state->pixel_rate =
6476                         crtc_state->base.adjusted_mode.crtc_clock;
6477         else
6478                 crtc_state->pixel_rate =
6479                         ilk_pipe_pixel_rate(crtc_state);
6480 }
6481
6482 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6483                                      struct intel_crtc_state *pipe_config)
6484 {
6485         struct drm_device *dev = crtc->base.dev;
6486         struct drm_i915_private *dev_priv = to_i915(dev);
6487         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6488         int clock_limit = dev_priv->max_dotclk_freq;
6489
6490         if (INTEL_GEN(dev_priv) < 4) {
6491                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6492
6493                 /*
6494                  * Enable double wide mode when the dot clock
6495                  * is > 90% of the (display) core speed.
6496                  */
6497                 if (intel_crtc_supports_double_wide(crtc) &&
6498                     adjusted_mode->crtc_clock > clock_limit) {
6499                         clock_limit = dev_priv->max_dotclk_freq;
6500                         pipe_config->double_wide = true;
6501                 }
6502         }
6503
6504         if (adjusted_mode->crtc_clock > clock_limit) {
6505                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6506                               adjusted_mode->crtc_clock, clock_limit,
6507                               yesno(pipe_config->double_wide));
6508                 return -EINVAL;
6509         }
6510
6511         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6512                 /*
6513                  * There is only one pipe CSC unit per pipe, and we need that
6514                  * for output conversion from RGB->YCBCR. So if CTM is already
6515                  * applied we can't support YCBCR420 output.
6516                  */
6517                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6518                 return -EINVAL;
6519         }
6520
6521         /*
6522          * Pipe horizontal size must be even in:
6523          * - DVO ganged mode
6524          * - LVDS dual channel mode
6525          * - Double wide pipe
6526          */
6527         if (pipe_config->pipe_src_w & 1) {
6528                 if (pipe_config->double_wide) {
6529                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6530                         return -EINVAL;
6531                 }
6532
6533                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6534                     intel_is_dual_link_lvds(dev)) {
6535                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6536                         return -EINVAL;
6537                 }
6538         }
6539
6540         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6541          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6542          */
6543         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6544                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6545                 return -EINVAL;
6546
6547         intel_crtc_compute_pixel_rate(pipe_config);
6548
6549         if (pipe_config->has_pch_encoder)
6550                 return ironlake_fdi_compute_config(crtc, pipe_config);
6551
6552         return 0;
6553 }
6554
6555 static void
6556 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6557 {
6558         while (*num > DATA_LINK_M_N_MASK ||
6559                *den > DATA_LINK_M_N_MASK) {
6560                 *num >>= 1;
6561                 *den >>= 1;
6562         }
6563 }
6564
6565 static void compute_m_n(unsigned int m, unsigned int n,
6566                         uint32_t *ret_m, uint32_t *ret_n,
6567                         bool reduce_m_n)
6568 {
6569         /*
6570          * Reduce M/N as much as possible without loss in precision. Several DP
6571          * dongles in particular seem to be fussy about too large *link* M/N
6572          * values. The passed in values are more likely to have the least
6573          * significant bits zero than M after rounding below, so do this first.
6574          */
6575         if (reduce_m_n) {
6576                 while ((m & 1) == 0 && (n & 1) == 0) {
6577                         m >>= 1;
6578                         n >>= 1;
6579                 }
6580         }
6581
6582         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6583         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6584         intel_reduce_m_n_ratio(ret_m, ret_n);
6585 }
6586
6587 void
6588 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6589                        int pixel_clock, int link_clock,
6590                        struct intel_link_m_n *m_n,
6591                        bool reduce_m_n)
6592 {
6593         m_n->tu = 64;
6594
6595         compute_m_n(bits_per_pixel * pixel_clock,
6596                     link_clock * nlanes * 8,
6597                     &m_n->gmch_m, &m_n->gmch_n,
6598                     reduce_m_n);
6599
6600         compute_m_n(pixel_clock, link_clock,
6601                     &m_n->link_m, &m_n->link_n,
6602                     reduce_m_n);
6603 }
6604
6605 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6606 {
6607         if (i915_modparams.panel_use_ssc >= 0)
6608                 return i915_modparams.panel_use_ssc != 0;
6609         return dev_priv->vbt.lvds_use_ssc
6610                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6611 }
6612
6613 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6614 {
6615         return (1 << dpll->n) << 16 | dpll->m2;
6616 }
6617
6618 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6619 {
6620         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6621 }
6622
6623 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6624                                      struct intel_crtc_state *crtc_state,
6625                                      struct dpll *reduced_clock)
6626 {
6627         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6628         u32 fp, fp2 = 0;
6629
6630         if (IS_PINEVIEW(dev_priv)) {
6631                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6632                 if (reduced_clock)
6633                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6634         } else {
6635                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6636                 if (reduced_clock)
6637                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6638         }
6639
6640         crtc_state->dpll_hw_state.fp0 = fp;
6641
6642         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6643             reduced_clock) {
6644                 crtc_state->dpll_hw_state.fp1 = fp2;
6645         } else {
6646                 crtc_state->dpll_hw_state.fp1 = fp;
6647         }
6648 }
6649
6650 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6651                 pipe)
6652 {
6653         u32 reg_val;
6654
6655         /*
6656          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6657          * and set it to a reasonable value instead.
6658          */
6659         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6660         reg_val &= 0xffffff00;
6661         reg_val |= 0x00000030;
6662         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6663
6664         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6665         reg_val &= 0x00ffffff;
6666         reg_val |= 0x8c000000;
6667         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6668
6669         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6670         reg_val &= 0xffffff00;
6671         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6672
6673         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6674         reg_val &= 0x00ffffff;
6675         reg_val |= 0xb0000000;
6676         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6677 }
6678
6679 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6680                                          struct intel_link_m_n *m_n)
6681 {
6682         struct drm_device *dev = crtc->base.dev;
6683         struct drm_i915_private *dev_priv = to_i915(dev);
6684         int pipe = crtc->pipe;
6685
6686         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6687         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6688         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6689         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6690 }
6691
6692 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6693                                          struct intel_link_m_n *m_n,
6694                                          struct intel_link_m_n *m2_n2)
6695 {
6696         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6697         int pipe = crtc->pipe;
6698         enum transcoder transcoder = crtc->config->cpu_transcoder;
6699
6700         if (INTEL_GEN(dev_priv) >= 5) {
6701                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6702                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6703                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6704                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6705                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6706                  * for gen < 8) and if DRRS is supported (to make sure the
6707                  * registers are not unnecessarily accessed).
6708                  */
6709                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6710                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6711                         I915_WRITE(PIPE_DATA_M2(transcoder),
6712                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6713                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6714                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6715                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6716                 }
6717         } else {
6718                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6719                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6720                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6721                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6722         }
6723 }
6724
6725 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6726 {
6727         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6728
6729         if (m_n == M1_N1) {
6730                 dp_m_n = &crtc->config->dp_m_n;
6731                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6732         } else if (m_n == M2_N2) {
6733
6734                 /*
6735                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6736                  * needs to be programmed into M1_N1.
6737                  */
6738                 dp_m_n = &crtc->config->dp_m2_n2;
6739         } else {
6740                 DRM_ERROR("Unsupported divider value\n");
6741                 return;
6742         }
6743
6744         if (crtc->config->has_pch_encoder)
6745                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6746         else
6747                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6748 }
6749
6750 static void vlv_compute_dpll(struct intel_crtc *crtc,
6751                              struct intel_crtc_state *pipe_config)
6752 {
6753         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6754                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6755         if (crtc->pipe != PIPE_A)
6756                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6757
6758         /* DPLL not used with DSI, but still need the rest set up */
6759         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6760                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6761                         DPLL_EXT_BUFFER_ENABLE_VLV;
6762
6763         pipe_config->dpll_hw_state.dpll_md =
6764                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6765 }
6766
6767 static void chv_compute_dpll(struct intel_crtc *crtc,
6768                              struct intel_crtc_state *pipe_config)
6769 {
6770         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6771                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6772         if (crtc->pipe != PIPE_A)
6773                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6774
6775         /* DPLL not used with DSI, but still need the rest set up */
6776         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6777                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6778
6779         pipe_config->dpll_hw_state.dpll_md =
6780                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6781 }
6782
6783 static void vlv_prepare_pll(struct intel_crtc *crtc,
6784                             const struct intel_crtc_state *pipe_config)
6785 {
6786         struct drm_device *dev = crtc->base.dev;
6787         struct drm_i915_private *dev_priv = to_i915(dev);
6788         enum pipe pipe = crtc->pipe;
6789         u32 mdiv;
6790         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6791         u32 coreclk, reg_val;
6792
6793         /* Enable Refclk */
6794         I915_WRITE(DPLL(pipe),
6795                    pipe_config->dpll_hw_state.dpll &
6796                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6797
6798         /* No need to actually set up the DPLL with DSI */
6799         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6800                 return;
6801
6802         mutex_lock(&dev_priv->sb_lock);
6803
6804         bestn = pipe_config->dpll.n;
6805         bestm1 = pipe_config->dpll.m1;
6806         bestm2 = pipe_config->dpll.m2;
6807         bestp1 = pipe_config->dpll.p1;
6808         bestp2 = pipe_config->dpll.p2;
6809
6810         /* See eDP HDMI DPIO driver vbios notes doc */
6811
6812         /* PLL B needs special handling */
6813         if (pipe == PIPE_B)
6814                 vlv_pllb_recal_opamp(dev_priv, pipe);
6815
6816         /* Set up Tx target for periodic Rcomp update */
6817         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6818
6819         /* Disable target IRef on PLL */
6820         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6821         reg_val &= 0x00ffffff;
6822         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6823
6824         /* Disable fast lock */
6825         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6826
6827         /* Set idtafcrecal before PLL is enabled */
6828         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6829         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6830         mdiv |= ((bestn << DPIO_N_SHIFT));
6831         mdiv |= (1 << DPIO_K_SHIFT);
6832
6833         /*
6834          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6835          * but we don't support that).
6836          * Note: don't use the DAC post divider as it seems unstable.
6837          */
6838         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6839         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6840
6841         mdiv |= DPIO_ENABLE_CALIBRATION;
6842         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6843
6844         /* Set HBR and RBR LPF coefficients */
6845         if (pipe_config->port_clock == 162000 ||
6846             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6847             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6848                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6849                                  0x009f0003);
6850         else
6851                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6852                                  0x00d0000f);
6853
6854         if (intel_crtc_has_dp_encoder(pipe_config)) {
6855                 /* Use SSC source */
6856                 if (pipe == PIPE_A)
6857                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6858                                          0x0df40000);
6859                 else
6860                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6861                                          0x0df70000);
6862         } else { /* HDMI or VGA */
6863                 /* Use bend source */
6864                 if (pipe == PIPE_A)
6865                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6866                                          0x0df70000);
6867                 else
6868                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6869                                          0x0df40000);
6870         }
6871
6872         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6873         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6874         if (intel_crtc_has_dp_encoder(crtc->config))
6875                 coreclk |= 0x01000000;
6876         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6877
6878         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6879         mutex_unlock(&dev_priv->sb_lock);
6880 }
6881
6882 static void chv_prepare_pll(struct intel_crtc *crtc,
6883                             const struct intel_crtc_state *pipe_config)
6884 {
6885         struct drm_device *dev = crtc->base.dev;
6886         struct drm_i915_private *dev_priv = to_i915(dev);
6887         enum pipe pipe = crtc->pipe;
6888         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6889         u32 loopfilter, tribuf_calcntr;
6890         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6891         u32 dpio_val;
6892         int vco;
6893
6894         /* Enable Refclk and SSC */
6895         I915_WRITE(DPLL(pipe),
6896                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6897
6898         /* No need to actually set up the DPLL with DSI */
6899         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6900                 return;
6901
6902         bestn = pipe_config->dpll.n;
6903         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6904         bestm1 = pipe_config->dpll.m1;
6905         bestm2 = pipe_config->dpll.m2 >> 22;
6906         bestp1 = pipe_config->dpll.p1;
6907         bestp2 = pipe_config->dpll.p2;
6908         vco = pipe_config->dpll.vco;
6909         dpio_val = 0;
6910         loopfilter = 0;
6911
6912         mutex_lock(&dev_priv->sb_lock);
6913
6914         /* p1 and p2 divider */
6915         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6916                         5 << DPIO_CHV_S1_DIV_SHIFT |
6917                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6918                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6919                         1 << DPIO_CHV_K_DIV_SHIFT);
6920
6921         /* Feedback post-divider - m2 */
6922         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6923
6924         /* Feedback refclk divider - n and m1 */
6925         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6926                         DPIO_CHV_M1_DIV_BY_2 |
6927                         1 << DPIO_CHV_N_DIV_SHIFT);
6928
6929         /* M2 fraction division */
6930         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6931
6932         /* M2 fraction division enable */
6933         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6934         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6935         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6936         if (bestm2_frac)
6937                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6938         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6939
6940         /* Program digital lock detect threshold */
6941         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6942         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6943                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6944         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6945         if (!bestm2_frac)
6946                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6947         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6948
6949         /* Loop filter */
6950         if (vco == 5400000) {
6951                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6952                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6953                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6954                 tribuf_calcntr = 0x9;
6955         } else if (vco <= 6200000) {
6956                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6957                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6958                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6959                 tribuf_calcntr = 0x9;
6960         } else if (vco <= 6480000) {
6961                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6962                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6963                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6964                 tribuf_calcntr = 0x8;
6965         } else {
6966                 /* Not supported. Apply the same limits as in the max case */
6967                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6968                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6969                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6970                 tribuf_calcntr = 0;
6971         }
6972         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6973
6974         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6975         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6976         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6977         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6978
6979         /* AFC Recal */
6980         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6981                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6982                         DPIO_AFC_RECAL);
6983
6984         mutex_unlock(&dev_priv->sb_lock);
6985 }
6986
6987 /**
6988  * vlv_force_pll_on - forcibly enable just the PLL
6989  * @dev_priv: i915 private structure
6990  * @pipe: pipe PLL to enable
6991  * @dpll: PLL configuration
6992  *
6993  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6994  * in cases where we need the PLL enabled even when @pipe is not going to
6995  * be enabled.
6996  */
6997 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6998                      const struct dpll *dpll)
6999 {
7000         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7001         struct intel_crtc_state *pipe_config;
7002
7003         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7004         if (!pipe_config)
7005                 return -ENOMEM;
7006
7007         pipe_config->base.crtc = &crtc->base;
7008         pipe_config->pixel_multiplier = 1;
7009         pipe_config->dpll = *dpll;
7010
7011         if (IS_CHERRYVIEW(dev_priv)) {
7012                 chv_compute_dpll(crtc, pipe_config);
7013                 chv_prepare_pll(crtc, pipe_config);
7014                 chv_enable_pll(crtc, pipe_config);
7015         } else {
7016                 vlv_compute_dpll(crtc, pipe_config);
7017                 vlv_prepare_pll(crtc, pipe_config);
7018                 vlv_enable_pll(crtc, pipe_config);
7019         }
7020
7021         kfree(pipe_config);
7022
7023         return 0;
7024 }
7025
7026 /**
7027  * vlv_force_pll_off - forcibly disable just the PLL
7028  * @dev_priv: i915 private structure
7029  * @pipe: pipe PLL to disable
7030  *
7031  * Disable the PLL for @pipe. To be used in cases where we need
7032  * the PLL enabled even when @pipe is not going to be enabled.
7033  */
7034 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7035 {
7036         if (IS_CHERRYVIEW(dev_priv))
7037                 chv_disable_pll(dev_priv, pipe);
7038         else
7039                 vlv_disable_pll(dev_priv, pipe);
7040 }
7041
7042 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7043                               struct intel_crtc_state *crtc_state,
7044                               struct dpll *reduced_clock)
7045 {
7046         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7047         u32 dpll;
7048         struct dpll *clock = &crtc_state->dpll;
7049
7050         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7051
7052         dpll = DPLL_VGA_MODE_DIS;
7053
7054         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7055                 dpll |= DPLLB_MODE_LVDS;
7056         else
7057                 dpll |= DPLLB_MODE_DAC_SERIAL;
7058
7059         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7060             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7061                 dpll |= (crtc_state->pixel_multiplier - 1)
7062                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7063         }
7064
7065         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7066             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7067                 dpll |= DPLL_SDVO_HIGH_SPEED;
7068
7069         if (intel_crtc_has_dp_encoder(crtc_state))
7070                 dpll |= DPLL_SDVO_HIGH_SPEED;
7071
7072         /* compute bitmask from p1 value */
7073         if (IS_PINEVIEW(dev_priv))
7074                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7075         else {
7076                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7077                 if (IS_G4X(dev_priv) && reduced_clock)
7078                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7079         }
7080         switch (clock->p2) {
7081         case 5:
7082                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7083                 break;
7084         case 7:
7085                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7086                 break;
7087         case 10:
7088                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7089                 break;
7090         case 14:
7091                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7092                 break;
7093         }
7094         if (INTEL_GEN(dev_priv) >= 4)
7095                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7096
7097         if (crtc_state->sdvo_tv_clock)
7098                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7099         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7100                  intel_panel_use_ssc(dev_priv))
7101                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7102         else
7103                 dpll |= PLL_REF_INPUT_DREFCLK;
7104
7105         dpll |= DPLL_VCO_ENABLE;
7106         crtc_state->dpll_hw_state.dpll = dpll;
7107
7108         if (INTEL_GEN(dev_priv) >= 4) {
7109                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7110                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7111                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7112         }
7113 }
7114
7115 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7116                               struct intel_crtc_state *crtc_state,
7117                               struct dpll *reduced_clock)
7118 {
7119         struct drm_device *dev = crtc->base.dev;
7120         struct drm_i915_private *dev_priv = to_i915(dev);
7121         u32 dpll;
7122         struct dpll *clock = &crtc_state->dpll;
7123
7124         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7125
7126         dpll = DPLL_VGA_MODE_DIS;
7127
7128         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7129                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7130         } else {
7131                 if (clock->p1 == 2)
7132                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7133                 else
7134                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7135                 if (clock->p2 == 4)
7136                         dpll |= PLL_P2_DIVIDE_BY_4;
7137         }
7138
7139         if (!IS_I830(dev_priv) &&
7140             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7141                 dpll |= DPLL_DVO_2X_MODE;
7142
7143         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7144             intel_panel_use_ssc(dev_priv))
7145                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7146         else
7147                 dpll |= PLL_REF_INPUT_DREFCLK;
7148
7149         dpll |= DPLL_VCO_ENABLE;
7150         crtc_state->dpll_hw_state.dpll = dpll;
7151 }
7152
7153 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7154 {
7155         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7156         enum pipe pipe = intel_crtc->pipe;
7157         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7158         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7159         uint32_t crtc_vtotal, crtc_vblank_end;
7160         int vsyncshift = 0;
7161
7162         /* We need to be careful not to changed the adjusted mode, for otherwise
7163          * the hw state checker will get angry at the mismatch. */
7164         crtc_vtotal = adjusted_mode->crtc_vtotal;
7165         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7166
7167         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7168                 /* the chip adds 2 halflines automatically */
7169                 crtc_vtotal -= 1;
7170                 crtc_vblank_end -= 1;
7171
7172                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7173                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7174                 else
7175                         vsyncshift = adjusted_mode->crtc_hsync_start -
7176                                 adjusted_mode->crtc_htotal / 2;
7177                 if (vsyncshift < 0)
7178                         vsyncshift += adjusted_mode->crtc_htotal;
7179         }
7180
7181         if (INTEL_GEN(dev_priv) > 3)
7182                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7183
7184         I915_WRITE(HTOTAL(cpu_transcoder),
7185                    (adjusted_mode->crtc_hdisplay - 1) |
7186                    ((adjusted_mode->crtc_htotal - 1) << 16));
7187         I915_WRITE(HBLANK(cpu_transcoder),
7188                    (adjusted_mode->crtc_hblank_start - 1) |
7189                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7190         I915_WRITE(HSYNC(cpu_transcoder),
7191                    (adjusted_mode->crtc_hsync_start - 1) |
7192                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7193
7194         I915_WRITE(VTOTAL(cpu_transcoder),
7195                    (adjusted_mode->crtc_vdisplay - 1) |
7196                    ((crtc_vtotal - 1) << 16));
7197         I915_WRITE(VBLANK(cpu_transcoder),
7198                    (adjusted_mode->crtc_vblank_start - 1) |
7199                    ((crtc_vblank_end - 1) << 16));
7200         I915_WRITE(VSYNC(cpu_transcoder),
7201                    (adjusted_mode->crtc_vsync_start - 1) |
7202                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7203
7204         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7205          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7206          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7207          * bits. */
7208         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7209             (pipe == PIPE_B || pipe == PIPE_C))
7210                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7211
7212 }
7213
7214 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7215 {
7216         struct drm_device *dev = intel_crtc->base.dev;
7217         struct drm_i915_private *dev_priv = to_i915(dev);
7218         enum pipe pipe = intel_crtc->pipe;
7219
7220         /* pipesrc controls the size that is scaled from, which should
7221          * always be the user's requested size.
7222          */
7223         I915_WRITE(PIPESRC(pipe),
7224                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7225                    (intel_crtc->config->pipe_src_h - 1));
7226 }
7227
7228 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7229                                    struct intel_crtc_state *pipe_config)
7230 {
7231         struct drm_device *dev = crtc->base.dev;
7232         struct drm_i915_private *dev_priv = to_i915(dev);
7233         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7234         uint32_t tmp;
7235
7236         tmp = I915_READ(HTOTAL(cpu_transcoder));
7237         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7238         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7239         tmp = I915_READ(HBLANK(cpu_transcoder));
7240         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7241         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7242         tmp = I915_READ(HSYNC(cpu_transcoder));
7243         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7244         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7245
7246         tmp = I915_READ(VTOTAL(cpu_transcoder));
7247         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7248         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7249         tmp = I915_READ(VBLANK(cpu_transcoder));
7250         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7251         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7252         tmp = I915_READ(VSYNC(cpu_transcoder));
7253         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7254         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7255
7256         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7257                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7258                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7259                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7260         }
7261 }
7262
7263 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7264                                     struct intel_crtc_state *pipe_config)
7265 {
7266         struct drm_device *dev = crtc->base.dev;
7267         struct drm_i915_private *dev_priv = to_i915(dev);
7268         u32 tmp;
7269
7270         tmp = I915_READ(PIPESRC(crtc->pipe));
7271         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7272         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7273
7274         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7275         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7276 }
7277
7278 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7279                                  struct intel_crtc_state *pipe_config)
7280 {
7281         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7282         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7283         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7284         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7285
7286         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7287         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7288         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7289         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7290
7291         mode->flags = pipe_config->base.adjusted_mode.flags;
7292         mode->type = DRM_MODE_TYPE_DRIVER;
7293
7294         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7295
7296         mode->hsync = drm_mode_hsync(mode);
7297         mode->vrefresh = drm_mode_vrefresh(mode);
7298         drm_mode_set_name(mode);
7299 }
7300
7301 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7302 {
7303         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7304         uint32_t pipeconf;
7305
7306         pipeconf = 0;
7307
7308         /* we keep both pipes enabled on 830 */
7309         if (IS_I830(dev_priv))
7310                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7311
7312         if (intel_crtc->config->double_wide)
7313                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7314
7315         /* only g4x and later have fancy bpc/dither controls */
7316         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7317             IS_CHERRYVIEW(dev_priv)) {
7318                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7319                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7320                         pipeconf |= PIPECONF_DITHER_EN |
7321                                     PIPECONF_DITHER_TYPE_SP;
7322
7323                 switch (intel_crtc->config->pipe_bpp) {
7324                 case 18:
7325                         pipeconf |= PIPECONF_6BPC;
7326                         break;
7327                 case 24:
7328                         pipeconf |= PIPECONF_8BPC;
7329                         break;
7330                 case 30:
7331                         pipeconf |= PIPECONF_10BPC;
7332                         break;
7333                 default:
7334                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7335                         BUG();
7336                 }
7337         }
7338
7339         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7340                 if (INTEL_GEN(dev_priv) < 4 ||
7341                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7342                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7343                 else
7344                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7345         } else
7346                 pipeconf |= PIPECONF_PROGRESSIVE;
7347
7348         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7349              intel_crtc->config->limited_color_range)
7350                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7351
7352         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7353         POSTING_READ(PIPECONF(intel_crtc->pipe));
7354 }
7355
7356 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7357                                    struct intel_crtc_state *crtc_state)
7358 {
7359         struct drm_device *dev = crtc->base.dev;
7360         struct drm_i915_private *dev_priv = to_i915(dev);
7361         const struct intel_limit *limit;
7362         int refclk = 48000;
7363
7364         memset(&crtc_state->dpll_hw_state, 0,
7365                sizeof(crtc_state->dpll_hw_state));
7366
7367         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7368                 if (intel_panel_use_ssc(dev_priv)) {
7369                         refclk = dev_priv->vbt.lvds_ssc_freq;
7370                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7371                 }
7372
7373                 limit = &intel_limits_i8xx_lvds;
7374         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7375                 limit = &intel_limits_i8xx_dvo;
7376         } else {
7377                 limit = &intel_limits_i8xx_dac;
7378         }
7379
7380         if (!crtc_state->clock_set &&
7381             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7382                                  refclk, NULL, &crtc_state->dpll)) {
7383                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7384                 return -EINVAL;
7385         }
7386
7387         i8xx_compute_dpll(crtc, crtc_state, NULL);
7388
7389         return 0;
7390 }
7391
7392 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7393                                   struct intel_crtc_state *crtc_state)
7394 {
7395         struct drm_device *dev = crtc->base.dev;
7396         struct drm_i915_private *dev_priv = to_i915(dev);
7397         const struct intel_limit *limit;
7398         int refclk = 96000;
7399
7400         memset(&crtc_state->dpll_hw_state, 0,
7401                sizeof(crtc_state->dpll_hw_state));
7402
7403         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7404                 if (intel_panel_use_ssc(dev_priv)) {
7405                         refclk = dev_priv->vbt.lvds_ssc_freq;
7406                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7407                 }
7408
7409                 if (intel_is_dual_link_lvds(dev))
7410                         limit = &intel_limits_g4x_dual_channel_lvds;
7411                 else
7412                         limit = &intel_limits_g4x_single_channel_lvds;
7413         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7414                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7415                 limit = &intel_limits_g4x_hdmi;
7416         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7417                 limit = &intel_limits_g4x_sdvo;
7418         } else {
7419                 /* The option is for other outputs */
7420                 limit = &intel_limits_i9xx_sdvo;
7421         }
7422
7423         if (!crtc_state->clock_set &&
7424             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7425                                 refclk, NULL, &crtc_state->dpll)) {
7426                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7427                 return -EINVAL;
7428         }
7429
7430         i9xx_compute_dpll(crtc, crtc_state, NULL);
7431
7432         return 0;
7433 }
7434
7435 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7436                                   struct intel_crtc_state *crtc_state)
7437 {
7438         struct drm_device *dev = crtc->base.dev;
7439         struct drm_i915_private *dev_priv = to_i915(dev);
7440         const struct intel_limit *limit;
7441         int refclk = 96000;
7442
7443         memset(&crtc_state->dpll_hw_state, 0,
7444                sizeof(crtc_state->dpll_hw_state));
7445
7446         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7447                 if (intel_panel_use_ssc(dev_priv)) {
7448                         refclk = dev_priv->vbt.lvds_ssc_freq;
7449                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7450                 }
7451
7452                 limit = &intel_limits_pineview_lvds;
7453         } else {
7454                 limit = &intel_limits_pineview_sdvo;
7455         }
7456
7457         if (!crtc_state->clock_set &&
7458             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7459                                 refclk, NULL, &crtc_state->dpll)) {
7460                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7461                 return -EINVAL;
7462         }
7463
7464         i9xx_compute_dpll(crtc, crtc_state, NULL);
7465
7466         return 0;
7467 }
7468
7469 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7470                                    struct intel_crtc_state *crtc_state)
7471 {
7472         struct drm_device *dev = crtc->base.dev;
7473         struct drm_i915_private *dev_priv = to_i915(dev);
7474         const struct intel_limit *limit;
7475         int refclk = 96000;
7476
7477         memset(&crtc_state->dpll_hw_state, 0,
7478                sizeof(crtc_state->dpll_hw_state));
7479
7480         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7481                 if (intel_panel_use_ssc(dev_priv)) {
7482                         refclk = dev_priv->vbt.lvds_ssc_freq;
7483                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7484                 }
7485
7486                 limit = &intel_limits_i9xx_lvds;
7487         } else {
7488                 limit = &intel_limits_i9xx_sdvo;
7489         }
7490
7491         if (!crtc_state->clock_set &&
7492             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7493                                  refclk, NULL, &crtc_state->dpll)) {
7494                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7495                 return -EINVAL;
7496         }
7497
7498         i9xx_compute_dpll(crtc, crtc_state, NULL);
7499
7500         return 0;
7501 }
7502
7503 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7504                                   struct intel_crtc_state *crtc_state)
7505 {
7506         int refclk = 100000;
7507         const struct intel_limit *limit = &intel_limits_chv;
7508
7509         memset(&crtc_state->dpll_hw_state, 0,
7510                sizeof(crtc_state->dpll_hw_state));
7511
7512         if (!crtc_state->clock_set &&
7513             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7514                                 refclk, NULL, &crtc_state->dpll)) {
7515                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7516                 return -EINVAL;
7517         }
7518
7519         chv_compute_dpll(crtc, crtc_state);
7520
7521         return 0;
7522 }
7523
7524 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7525                                   struct intel_crtc_state *crtc_state)
7526 {
7527         int refclk = 100000;
7528         const struct intel_limit *limit = &intel_limits_vlv;
7529
7530         memset(&crtc_state->dpll_hw_state, 0,
7531                sizeof(crtc_state->dpll_hw_state));
7532
7533         if (!crtc_state->clock_set &&
7534             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7535                                 refclk, NULL, &crtc_state->dpll)) {
7536                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7537                 return -EINVAL;
7538         }
7539
7540         vlv_compute_dpll(crtc, crtc_state);
7541
7542         return 0;
7543 }
7544
7545 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7546                                  struct intel_crtc_state *pipe_config)
7547 {
7548         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7549         uint32_t tmp;
7550
7551         if (INTEL_GEN(dev_priv) <= 3 &&
7552             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7553                 return;
7554
7555         tmp = I915_READ(PFIT_CONTROL);
7556         if (!(tmp & PFIT_ENABLE))
7557                 return;
7558
7559         /* Check whether the pfit is attached to our pipe. */
7560         if (INTEL_GEN(dev_priv) < 4) {
7561                 if (crtc->pipe != PIPE_B)
7562                         return;
7563         } else {
7564                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7565                         return;
7566         }
7567
7568         pipe_config->gmch_pfit.control = tmp;
7569         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7570 }
7571
7572 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7573                                struct intel_crtc_state *pipe_config)
7574 {
7575         struct drm_device *dev = crtc->base.dev;
7576         struct drm_i915_private *dev_priv = to_i915(dev);
7577         int pipe = pipe_config->cpu_transcoder;
7578         struct dpll clock;
7579         u32 mdiv;
7580         int refclk = 100000;
7581
7582         /* In case of DSI, DPLL will not be used */
7583         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7584                 return;
7585
7586         mutex_lock(&dev_priv->sb_lock);
7587         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7588         mutex_unlock(&dev_priv->sb_lock);
7589
7590         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7591         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7592         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7593         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7594         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7595
7596         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7597 }
7598
7599 static void
7600 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7601                               struct intel_initial_plane_config *plane_config)
7602 {
7603         struct drm_device *dev = crtc->base.dev;
7604         struct drm_i915_private *dev_priv = to_i915(dev);
7605         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7606         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7607         enum pipe pipe = crtc->pipe;
7608         u32 val, base, offset;
7609         int fourcc, pixel_format;
7610         unsigned int aligned_height;
7611         struct drm_framebuffer *fb;
7612         struct intel_framebuffer *intel_fb;
7613
7614         if (!plane->get_hw_state(plane))
7615                 return;
7616
7617         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7618         if (!intel_fb) {
7619                 DRM_DEBUG_KMS("failed to alloc fb\n");
7620                 return;
7621         }
7622
7623         fb = &intel_fb->base;
7624
7625         fb->dev = dev;
7626
7627         val = I915_READ(DSPCNTR(i9xx_plane));
7628
7629         if (INTEL_GEN(dev_priv) >= 4) {
7630                 if (val & DISPPLANE_TILED) {
7631                         plane_config->tiling = I915_TILING_X;
7632                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7633                 }
7634         }
7635
7636         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7637         fourcc = i9xx_format_to_fourcc(pixel_format);
7638         fb->format = drm_format_info(fourcc);
7639
7640         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7641                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7642                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7643         } else if (INTEL_GEN(dev_priv) >= 4) {
7644                 if (plane_config->tiling)
7645                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7646                 else
7647                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7648                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7649         } else {
7650                 base = I915_READ(DSPADDR(i9xx_plane));
7651         }
7652         plane_config->base = base;
7653
7654         val = I915_READ(PIPESRC(pipe));
7655         fb->width = ((val >> 16) & 0xfff) + 1;
7656         fb->height = ((val >> 0) & 0xfff) + 1;
7657
7658         val = I915_READ(DSPSTRIDE(i9xx_plane));
7659         fb->pitches[0] = val & 0xffffffc0;
7660
7661         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7662
7663         plane_config->size = fb->pitches[0] * aligned_height;
7664
7665         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7666                       crtc->base.name, plane->base.name, fb->width, fb->height,
7667                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7668                       plane_config->size);
7669
7670         plane_config->fb = intel_fb;
7671 }
7672
7673 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7674                                struct intel_crtc_state *pipe_config)
7675 {
7676         struct drm_device *dev = crtc->base.dev;
7677         struct drm_i915_private *dev_priv = to_i915(dev);
7678         int pipe = pipe_config->cpu_transcoder;
7679         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7680         struct dpll clock;
7681         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7682         int refclk = 100000;
7683
7684         /* In case of DSI, DPLL will not be used */
7685         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7686                 return;
7687
7688         mutex_lock(&dev_priv->sb_lock);
7689         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7690         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7691         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7692         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7693         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7694         mutex_unlock(&dev_priv->sb_lock);
7695
7696         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7697         clock.m2 = (pll_dw0 & 0xff) << 22;
7698         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7699                 clock.m2 |= pll_dw2 & 0x3fffff;
7700         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7701         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7702         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7703
7704         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7705 }
7706
7707 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7708                                  struct intel_crtc_state *pipe_config)
7709 {
7710         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7711         enum intel_display_power_domain power_domain;
7712         uint32_t tmp;
7713         bool ret;
7714
7715         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7716         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7717                 return false;
7718
7719         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7720         pipe_config->shared_dpll = NULL;
7721
7722         ret = false;
7723
7724         tmp = I915_READ(PIPECONF(crtc->pipe));
7725         if (!(tmp & PIPECONF_ENABLE))
7726                 goto out;
7727
7728         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7729             IS_CHERRYVIEW(dev_priv)) {
7730                 switch (tmp & PIPECONF_BPC_MASK) {
7731                 case PIPECONF_6BPC:
7732                         pipe_config->pipe_bpp = 18;
7733                         break;
7734                 case PIPECONF_8BPC:
7735                         pipe_config->pipe_bpp = 24;
7736                         break;
7737                 case PIPECONF_10BPC:
7738                         pipe_config->pipe_bpp = 30;
7739                         break;
7740                 default:
7741                         break;
7742                 }
7743         }
7744
7745         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7746             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7747                 pipe_config->limited_color_range = true;
7748
7749         if (INTEL_GEN(dev_priv) < 4)
7750                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7751
7752         intel_get_pipe_timings(crtc, pipe_config);
7753         intel_get_pipe_src_size(crtc, pipe_config);
7754
7755         i9xx_get_pfit_config(crtc, pipe_config);
7756
7757         if (INTEL_GEN(dev_priv) >= 4) {
7758                 /* No way to read it out on pipes B and C */
7759                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7760                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7761                 else
7762                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7763                 pipe_config->pixel_multiplier =
7764                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7765                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7766                 pipe_config->dpll_hw_state.dpll_md = tmp;
7767         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7768                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7769                 tmp = I915_READ(DPLL(crtc->pipe));
7770                 pipe_config->pixel_multiplier =
7771                         ((tmp & SDVO_MULTIPLIER_MASK)
7772                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7773         } else {
7774                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7775                  * port and will be fixed up in the encoder->get_config
7776                  * function. */
7777                 pipe_config->pixel_multiplier = 1;
7778         }
7779         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7780         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7781                 /*
7782                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7783                  * on 830. Filter it out here so that we don't
7784                  * report errors due to that.
7785                  */
7786                 if (IS_I830(dev_priv))
7787                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7788
7789                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7790                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7791         } else {
7792                 /* Mask out read-only status bits. */
7793                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7794                                                      DPLL_PORTC_READY_MASK |
7795                                                      DPLL_PORTB_READY_MASK);
7796         }
7797
7798         if (IS_CHERRYVIEW(dev_priv))
7799                 chv_crtc_clock_get(crtc, pipe_config);
7800         else if (IS_VALLEYVIEW(dev_priv))
7801                 vlv_crtc_clock_get(crtc, pipe_config);
7802         else
7803                 i9xx_crtc_clock_get(crtc, pipe_config);
7804
7805         /*
7806          * Normally the dotclock is filled in by the encoder .get_config()
7807          * but in case the pipe is enabled w/o any ports we need a sane
7808          * default.
7809          */
7810         pipe_config->base.adjusted_mode.crtc_clock =
7811                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7812
7813         ret = true;
7814
7815 out:
7816         intel_display_power_put(dev_priv, power_domain);
7817
7818         return ret;
7819 }
7820
7821 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7822 {
7823         struct intel_encoder *encoder;
7824         int i;
7825         u32 val, final;
7826         bool has_lvds = false;
7827         bool has_cpu_edp = false;
7828         bool has_panel = false;
7829         bool has_ck505 = false;
7830         bool can_ssc = false;
7831         bool using_ssc_source = false;
7832
7833         /* We need to take the global config into account */
7834         for_each_intel_encoder(&dev_priv->drm, encoder) {
7835                 switch (encoder->type) {
7836                 case INTEL_OUTPUT_LVDS:
7837                         has_panel = true;
7838                         has_lvds = true;
7839                         break;
7840                 case INTEL_OUTPUT_EDP:
7841                         has_panel = true;
7842                         if (encoder->port == PORT_A)
7843                                 has_cpu_edp = true;
7844                         break;
7845                 default:
7846                         break;
7847                 }
7848         }
7849
7850         if (HAS_PCH_IBX(dev_priv)) {
7851                 has_ck505 = dev_priv->vbt.display_clock_mode;
7852                 can_ssc = has_ck505;
7853         } else {
7854                 has_ck505 = false;
7855                 can_ssc = true;
7856         }
7857
7858         /* Check if any DPLLs are using the SSC source */
7859         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7860                 u32 temp = I915_READ(PCH_DPLL(i));
7861
7862                 if (!(temp & DPLL_VCO_ENABLE))
7863                         continue;
7864
7865                 if ((temp & PLL_REF_INPUT_MASK) ==
7866                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7867                         using_ssc_source = true;
7868                         break;
7869                 }
7870         }
7871
7872         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7873                       has_panel, has_lvds, has_ck505, using_ssc_source);
7874
7875         /* Ironlake: try to setup display ref clock before DPLL
7876          * enabling. This is only under driver's control after
7877          * PCH B stepping, previous chipset stepping should be
7878          * ignoring this setting.
7879          */
7880         val = I915_READ(PCH_DREF_CONTROL);
7881
7882         /* As we must carefully and slowly disable/enable each source in turn,
7883          * compute the final state we want first and check if we need to
7884          * make any changes at all.
7885          */
7886         final = val;
7887         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7888         if (has_ck505)
7889                 final |= DREF_NONSPREAD_CK505_ENABLE;
7890         else
7891                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7892
7893         final &= ~DREF_SSC_SOURCE_MASK;
7894         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7895         final &= ~DREF_SSC1_ENABLE;
7896
7897         if (has_panel) {
7898                 final |= DREF_SSC_SOURCE_ENABLE;
7899
7900                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7901                         final |= DREF_SSC1_ENABLE;
7902
7903                 if (has_cpu_edp) {
7904                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7905                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7906                         else
7907                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7908                 } else
7909                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7910         } else if (using_ssc_source) {
7911                 final |= DREF_SSC_SOURCE_ENABLE;
7912                 final |= DREF_SSC1_ENABLE;
7913         }
7914
7915         if (final == val)
7916                 return;
7917
7918         /* Always enable nonspread source */
7919         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7920
7921         if (has_ck505)
7922                 val |= DREF_NONSPREAD_CK505_ENABLE;
7923         else
7924                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7925
7926         if (has_panel) {
7927                 val &= ~DREF_SSC_SOURCE_MASK;
7928                 val |= DREF_SSC_SOURCE_ENABLE;
7929
7930                 /* SSC must be turned on before enabling the CPU output  */
7931                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7932                         DRM_DEBUG_KMS("Using SSC on panel\n");
7933                         val |= DREF_SSC1_ENABLE;
7934                 } else
7935                         val &= ~DREF_SSC1_ENABLE;
7936
7937                 /* Get SSC going before enabling the outputs */
7938                 I915_WRITE(PCH_DREF_CONTROL, val);
7939                 POSTING_READ(PCH_DREF_CONTROL);
7940                 udelay(200);
7941
7942                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7943
7944                 /* Enable CPU source on CPU attached eDP */
7945                 if (has_cpu_edp) {
7946                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7947                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7948                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7949                         } else
7950                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7951                 } else
7952                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7953
7954                 I915_WRITE(PCH_DREF_CONTROL, val);
7955                 POSTING_READ(PCH_DREF_CONTROL);
7956                 udelay(200);
7957         } else {
7958                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7959
7960                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7961
7962                 /* Turn off CPU output */
7963                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7964
7965                 I915_WRITE(PCH_DREF_CONTROL, val);
7966                 POSTING_READ(PCH_DREF_CONTROL);
7967                 udelay(200);
7968
7969                 if (!using_ssc_source) {
7970                         DRM_DEBUG_KMS("Disabling SSC source\n");
7971
7972                         /* Turn off the SSC source */
7973                         val &= ~DREF_SSC_SOURCE_MASK;
7974                         val |= DREF_SSC_SOURCE_DISABLE;
7975
7976                         /* Turn off SSC1 */
7977                         val &= ~DREF_SSC1_ENABLE;
7978
7979                         I915_WRITE(PCH_DREF_CONTROL, val);
7980                         POSTING_READ(PCH_DREF_CONTROL);
7981                         udelay(200);
7982                 }
7983         }
7984
7985         BUG_ON(val != final);
7986 }
7987
7988 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7989 {
7990         uint32_t tmp;
7991
7992         tmp = I915_READ(SOUTH_CHICKEN2);
7993         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7994         I915_WRITE(SOUTH_CHICKEN2, tmp);
7995
7996         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7997                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7998                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7999
8000         tmp = I915_READ(SOUTH_CHICKEN2);
8001         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8002         I915_WRITE(SOUTH_CHICKEN2, tmp);
8003
8004         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8005                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8006                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8007 }
8008
8009 /* WaMPhyProgramming:hsw */
8010 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8011 {
8012         uint32_t tmp;
8013
8014         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8015         tmp &= ~(0xFF << 24);
8016         tmp |= (0x12 << 24);
8017         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8018
8019         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8020         tmp |= (1 << 11);
8021         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8022
8023         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8024         tmp |= (1 << 11);
8025         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8026
8027         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8028         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8029         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8030
8031         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8032         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8033         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8034
8035         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8036         tmp &= ~(7 << 13);
8037         tmp |= (5 << 13);
8038         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8039
8040         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8041         tmp &= ~(7 << 13);
8042         tmp |= (5 << 13);
8043         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8044
8045         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8046         tmp &= ~0xFF;
8047         tmp |= 0x1C;
8048         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8049
8050         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8051         tmp &= ~0xFF;
8052         tmp |= 0x1C;
8053         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8054
8055         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8056         tmp &= ~(0xFF << 16);
8057         tmp |= (0x1C << 16);
8058         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8059
8060         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8061         tmp &= ~(0xFF << 16);
8062         tmp |= (0x1C << 16);
8063         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8064
8065         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8066         tmp |= (1 << 27);
8067         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8068
8069         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8070         tmp |= (1 << 27);
8071         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8072
8073         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8074         tmp &= ~(0xF << 28);
8075         tmp |= (4 << 28);
8076         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8077
8078         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8079         tmp &= ~(0xF << 28);
8080         tmp |= (4 << 28);
8081         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8082 }
8083
8084 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8085  * Programming" based on the parameters passed:
8086  * - Sequence to enable CLKOUT_DP
8087  * - Sequence to enable CLKOUT_DP without spread
8088  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8089  */
8090 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8091                                  bool with_spread, bool with_fdi)
8092 {
8093         uint32_t reg, tmp;
8094
8095         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8096                 with_spread = true;
8097         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8098             with_fdi, "LP PCH doesn't have FDI\n"))
8099                 with_fdi = false;
8100
8101         mutex_lock(&dev_priv->sb_lock);
8102
8103         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8104         tmp &= ~SBI_SSCCTL_DISABLE;
8105         tmp |= SBI_SSCCTL_PATHALT;
8106         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8107
8108         udelay(24);
8109
8110         if (with_spread) {
8111                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8112                 tmp &= ~SBI_SSCCTL_PATHALT;
8113                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8114
8115                 if (with_fdi) {
8116                         lpt_reset_fdi_mphy(dev_priv);
8117                         lpt_program_fdi_mphy(dev_priv);
8118                 }
8119         }
8120
8121         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8122         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8123         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8124         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8125
8126         mutex_unlock(&dev_priv->sb_lock);
8127 }
8128
8129 /* Sequence to disable CLKOUT_DP */
8130 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8131 {
8132         uint32_t reg, tmp;
8133
8134         mutex_lock(&dev_priv->sb_lock);
8135
8136         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8137         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8138         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8139         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8140
8141         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8142         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8143                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8144                         tmp |= SBI_SSCCTL_PATHALT;
8145                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8146                         udelay(32);
8147                 }
8148                 tmp |= SBI_SSCCTL_DISABLE;
8149                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8150         }
8151
8152         mutex_unlock(&dev_priv->sb_lock);
8153 }
8154
8155 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8156
8157 static const uint16_t sscdivintphase[] = {
8158         [BEND_IDX( 50)] = 0x3B23,
8159         [BEND_IDX( 45)] = 0x3B23,
8160         [BEND_IDX( 40)] = 0x3C23,
8161         [BEND_IDX( 35)] = 0x3C23,
8162         [BEND_IDX( 30)] = 0x3D23,
8163         [BEND_IDX( 25)] = 0x3D23,
8164         [BEND_IDX( 20)] = 0x3E23,
8165         [BEND_IDX( 15)] = 0x3E23,
8166         [BEND_IDX( 10)] = 0x3F23,
8167         [BEND_IDX(  5)] = 0x3F23,
8168         [BEND_IDX(  0)] = 0x0025,
8169         [BEND_IDX( -5)] = 0x0025,
8170         [BEND_IDX(-10)] = 0x0125,
8171         [BEND_IDX(-15)] = 0x0125,
8172         [BEND_IDX(-20)] = 0x0225,
8173         [BEND_IDX(-25)] = 0x0225,
8174         [BEND_IDX(-30)] = 0x0325,
8175         [BEND_IDX(-35)] = 0x0325,
8176         [BEND_IDX(-40)] = 0x0425,
8177         [BEND_IDX(-45)] = 0x0425,
8178         [BEND_IDX(-50)] = 0x0525,
8179 };
8180
8181 /*
8182  * Bend CLKOUT_DP
8183  * steps -50 to 50 inclusive, in steps of 5
8184  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8185  * change in clock period = -(steps / 10) * 5.787 ps
8186  */
8187 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8188 {
8189         uint32_t tmp;
8190         int idx = BEND_IDX(steps);
8191
8192         if (WARN_ON(steps % 5 != 0))
8193                 return;
8194
8195         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8196                 return;
8197
8198         mutex_lock(&dev_priv->sb_lock);
8199
8200         if (steps % 10 != 0)
8201                 tmp = 0xAAAAAAAB;
8202         else
8203                 tmp = 0x00000000;
8204         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8205
8206         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8207         tmp &= 0xffff0000;
8208         tmp |= sscdivintphase[idx];
8209         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8210
8211         mutex_unlock(&dev_priv->sb_lock);
8212 }
8213
8214 #undef BEND_IDX
8215
8216 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8217 {
8218         struct intel_encoder *encoder;
8219         bool has_vga = false;
8220
8221         for_each_intel_encoder(&dev_priv->drm, encoder) {
8222                 switch (encoder->type) {
8223                 case INTEL_OUTPUT_ANALOG:
8224                         has_vga = true;
8225                         break;
8226                 default:
8227                         break;
8228                 }
8229         }
8230
8231         if (has_vga) {
8232                 lpt_bend_clkout_dp(dev_priv, 0);
8233                 lpt_enable_clkout_dp(dev_priv, true, true);
8234         } else {
8235                 lpt_disable_clkout_dp(dev_priv);
8236         }
8237 }
8238
8239 /*
8240  * Initialize reference clocks when the driver loads
8241  */
8242 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8243 {
8244         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8245                 ironlake_init_pch_refclk(dev_priv);
8246         else if (HAS_PCH_LPT(dev_priv))
8247                 lpt_init_pch_refclk(dev_priv);
8248 }
8249
8250 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8251 {
8252         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8253         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8254         int pipe = intel_crtc->pipe;
8255         uint32_t val;
8256
8257         val = 0;
8258
8259         switch (intel_crtc->config->pipe_bpp) {
8260         case 18:
8261                 val |= PIPECONF_6BPC;
8262                 break;
8263         case 24:
8264                 val |= PIPECONF_8BPC;
8265                 break;
8266         case 30:
8267                 val |= PIPECONF_10BPC;
8268                 break;
8269         case 36:
8270                 val |= PIPECONF_12BPC;
8271                 break;
8272         default:
8273                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8274                 BUG();
8275         }
8276
8277         if (intel_crtc->config->dither)
8278                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8279
8280         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8281                 val |= PIPECONF_INTERLACED_ILK;
8282         else
8283                 val |= PIPECONF_PROGRESSIVE;
8284
8285         if (intel_crtc->config->limited_color_range)
8286                 val |= PIPECONF_COLOR_RANGE_SELECT;
8287
8288         I915_WRITE(PIPECONF(pipe), val);
8289         POSTING_READ(PIPECONF(pipe));
8290 }
8291
8292 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8293 {
8294         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8295         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8296         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8297         u32 val = 0;
8298
8299         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8300                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8301
8302         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8303                 val |= PIPECONF_INTERLACED_ILK;
8304         else
8305                 val |= PIPECONF_PROGRESSIVE;
8306
8307         I915_WRITE(PIPECONF(cpu_transcoder), val);
8308         POSTING_READ(PIPECONF(cpu_transcoder));
8309 }
8310
8311 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8312 {
8313         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8314         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8315         struct intel_crtc_state *config = intel_crtc->config;
8316
8317         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8318                 u32 val = 0;
8319
8320                 switch (intel_crtc->config->pipe_bpp) {
8321                 case 18:
8322                         val |= PIPEMISC_DITHER_6_BPC;
8323                         break;
8324                 case 24:
8325                         val |= PIPEMISC_DITHER_8_BPC;
8326                         break;
8327                 case 30:
8328                         val |= PIPEMISC_DITHER_10_BPC;
8329                         break;
8330                 case 36:
8331                         val |= PIPEMISC_DITHER_12_BPC;
8332                         break;
8333                 default:
8334                         /* Case prevented by pipe_config_set_bpp. */
8335                         BUG();
8336                 }
8337
8338                 if (intel_crtc->config->dither)
8339                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8340
8341                 if (config->ycbcr420) {
8342                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8343                                 PIPEMISC_YUV420_ENABLE |
8344                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8345                 }
8346
8347                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8348         }
8349 }
8350
8351 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8352 {
8353         /*
8354          * Account for spread spectrum to avoid
8355          * oversubscribing the link. Max center spread
8356          * is 2.5%; use 5% for safety's sake.
8357          */
8358         u32 bps = target_clock * bpp * 21 / 20;
8359         return DIV_ROUND_UP(bps, link_bw * 8);
8360 }
8361
8362 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8363 {
8364         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8365 }
8366
8367 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8368                                   struct intel_crtc_state *crtc_state,
8369                                   struct dpll *reduced_clock)
8370 {
8371         struct drm_crtc *crtc = &intel_crtc->base;
8372         struct drm_device *dev = crtc->dev;
8373         struct drm_i915_private *dev_priv = to_i915(dev);
8374         u32 dpll, fp, fp2;
8375         int factor;
8376
8377         /* Enable autotuning of the PLL clock (if permissible) */
8378         factor = 21;
8379         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8380                 if ((intel_panel_use_ssc(dev_priv) &&
8381                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8382                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8383                         factor = 25;
8384         } else if (crtc_state->sdvo_tv_clock)
8385                 factor = 20;
8386
8387         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8388
8389         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8390                 fp |= FP_CB_TUNE;
8391
8392         if (reduced_clock) {
8393                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8394
8395                 if (reduced_clock->m < factor * reduced_clock->n)
8396                         fp2 |= FP_CB_TUNE;
8397         } else {
8398                 fp2 = fp;
8399         }
8400
8401         dpll = 0;
8402
8403         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8404                 dpll |= DPLLB_MODE_LVDS;
8405         else
8406                 dpll |= DPLLB_MODE_DAC_SERIAL;
8407
8408         dpll |= (crtc_state->pixel_multiplier - 1)
8409                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8410
8411         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8412             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8413                 dpll |= DPLL_SDVO_HIGH_SPEED;
8414
8415         if (intel_crtc_has_dp_encoder(crtc_state))
8416                 dpll |= DPLL_SDVO_HIGH_SPEED;
8417
8418         /*
8419          * The high speed IO clock is only really required for
8420          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8421          * possible to share the DPLL between CRT and HDMI. Enabling
8422          * the clock needlessly does no real harm, except use up a
8423          * bit of power potentially.
8424          *
8425          * We'll limit this to IVB with 3 pipes, since it has only two
8426          * DPLLs and so DPLL sharing is the only way to get three pipes
8427          * driving PCH ports at the same time. On SNB we could do this,
8428          * and potentially avoid enabling the second DPLL, but it's not
8429          * clear if it''s a win or loss power wise. No point in doing
8430          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8431          */
8432         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8433             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8434                 dpll |= DPLL_SDVO_HIGH_SPEED;
8435
8436         /* compute bitmask from p1 value */
8437         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8438         /* also FPA1 */
8439         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8440
8441         switch (crtc_state->dpll.p2) {
8442         case 5:
8443                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8444                 break;
8445         case 7:
8446                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8447                 break;
8448         case 10:
8449                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8450                 break;
8451         case 14:
8452                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8453                 break;
8454         }
8455
8456         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8457             intel_panel_use_ssc(dev_priv))
8458                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8459         else
8460                 dpll |= PLL_REF_INPUT_DREFCLK;
8461
8462         dpll |= DPLL_VCO_ENABLE;
8463
8464         crtc_state->dpll_hw_state.dpll = dpll;
8465         crtc_state->dpll_hw_state.fp0 = fp;
8466         crtc_state->dpll_hw_state.fp1 = fp2;
8467 }
8468
8469 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8470                                        struct intel_crtc_state *crtc_state)
8471 {
8472         struct drm_device *dev = crtc->base.dev;
8473         struct drm_i915_private *dev_priv = to_i915(dev);
8474         const struct intel_limit *limit;
8475         int refclk = 120000;
8476
8477         memset(&crtc_state->dpll_hw_state, 0,
8478                sizeof(crtc_state->dpll_hw_state));
8479
8480         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8481         if (!crtc_state->has_pch_encoder)
8482                 return 0;
8483
8484         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8485                 if (intel_panel_use_ssc(dev_priv)) {
8486                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8487                                       dev_priv->vbt.lvds_ssc_freq);
8488                         refclk = dev_priv->vbt.lvds_ssc_freq;
8489                 }
8490
8491                 if (intel_is_dual_link_lvds(dev)) {
8492                         if (refclk == 100000)
8493                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8494                         else
8495                                 limit = &intel_limits_ironlake_dual_lvds;
8496                 } else {
8497                         if (refclk == 100000)
8498                                 limit = &intel_limits_ironlake_single_lvds_100m;
8499                         else
8500                                 limit = &intel_limits_ironlake_single_lvds;
8501                 }
8502         } else {
8503                 limit = &intel_limits_ironlake_dac;
8504         }
8505
8506         if (!crtc_state->clock_set &&
8507             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8508                                 refclk, NULL, &crtc_state->dpll)) {
8509                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8510                 return -EINVAL;
8511         }
8512
8513         ironlake_compute_dpll(crtc, crtc_state, NULL);
8514
8515         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8516                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8517                                  pipe_name(crtc->pipe));
8518                 return -EINVAL;
8519         }
8520
8521         return 0;
8522 }
8523
8524 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8525                                          struct intel_link_m_n *m_n)
8526 {
8527         struct drm_device *dev = crtc->base.dev;
8528         struct drm_i915_private *dev_priv = to_i915(dev);
8529         enum pipe pipe = crtc->pipe;
8530
8531         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8532         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8533         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8534                 & ~TU_SIZE_MASK;
8535         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8536         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8537                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8538 }
8539
8540 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8541                                          enum transcoder transcoder,
8542                                          struct intel_link_m_n *m_n,
8543                                          struct intel_link_m_n *m2_n2)
8544 {
8545         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8546         enum pipe pipe = crtc->pipe;
8547
8548         if (INTEL_GEN(dev_priv) >= 5) {
8549                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8550                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8551                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8552                         & ~TU_SIZE_MASK;
8553                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8554                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8555                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8556                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8557                  * gen < 8) and if DRRS is supported (to make sure the
8558                  * registers are not unnecessarily read).
8559                  */
8560                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8561                         crtc->config->has_drrs) {
8562                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8563                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8564                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8565                                         & ~TU_SIZE_MASK;
8566                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8567                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8568                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8569                 }
8570         } else {
8571                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8572                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8573                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8574                         & ~TU_SIZE_MASK;
8575                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8576                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8577                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8578         }
8579 }
8580
8581 void intel_dp_get_m_n(struct intel_crtc *crtc,
8582                       struct intel_crtc_state *pipe_config)
8583 {
8584         if (pipe_config->has_pch_encoder)
8585                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8586         else
8587                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8588                                              &pipe_config->dp_m_n,
8589                                              &pipe_config->dp_m2_n2);
8590 }
8591
8592 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8593                                         struct intel_crtc_state *pipe_config)
8594 {
8595         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8596                                      &pipe_config->fdi_m_n, NULL);
8597 }
8598
8599 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8600                                     struct intel_crtc_state *pipe_config)
8601 {
8602         struct drm_device *dev = crtc->base.dev;
8603         struct drm_i915_private *dev_priv = to_i915(dev);
8604         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8605         uint32_t ps_ctrl = 0;
8606         int id = -1;
8607         int i;
8608
8609         /* find scaler attached to this pipe */
8610         for (i = 0; i < crtc->num_scalers; i++) {
8611                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8612                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8613                         id = i;
8614                         pipe_config->pch_pfit.enabled = true;
8615                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8616                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8617                         break;
8618                 }
8619         }
8620
8621         scaler_state->scaler_id = id;
8622         if (id >= 0) {
8623                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8624         } else {
8625                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8626         }
8627 }
8628
8629 static void
8630 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8631                                  struct intel_initial_plane_config *plane_config)
8632 {
8633         struct drm_device *dev = crtc->base.dev;
8634         struct drm_i915_private *dev_priv = to_i915(dev);
8635         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8636         enum plane_id plane_id = plane->id;
8637         enum pipe pipe = crtc->pipe;
8638         u32 val, base, offset, stride_mult, tiling, alpha;
8639         int fourcc, pixel_format;
8640         unsigned int aligned_height;
8641         struct drm_framebuffer *fb;
8642         struct intel_framebuffer *intel_fb;
8643
8644         if (!plane->get_hw_state(plane))
8645                 return;
8646
8647         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8648         if (!intel_fb) {
8649                 DRM_DEBUG_KMS("failed to alloc fb\n");
8650                 return;
8651         }
8652
8653         fb = &intel_fb->base;
8654
8655         fb->dev = dev;
8656
8657         val = I915_READ(PLANE_CTL(pipe, plane_id));
8658
8659         if (INTEL_GEN(dev_priv) >= 11)
8660                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8661         else
8662                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8663
8664         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8665                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8666                 alpha &= PLANE_COLOR_ALPHA_MASK;
8667         } else {
8668                 alpha = val & PLANE_CTL_ALPHA_MASK;
8669         }
8670
8671         fourcc = skl_format_to_fourcc(pixel_format,
8672                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8673         fb->format = drm_format_info(fourcc);
8674
8675         tiling = val & PLANE_CTL_TILED_MASK;
8676         switch (tiling) {
8677         case PLANE_CTL_TILED_LINEAR:
8678                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8679                 break;
8680         case PLANE_CTL_TILED_X:
8681                 plane_config->tiling = I915_TILING_X;
8682                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8683                 break;
8684         case PLANE_CTL_TILED_Y:
8685                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8686                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8687                 else
8688                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8689                 break;
8690         case PLANE_CTL_TILED_YF:
8691                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8692                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8693                 else
8694                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8695                 break;
8696         default:
8697                 MISSING_CASE(tiling);
8698                 goto error;
8699         }
8700
8701         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8702         plane_config->base = base;
8703
8704         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8705
8706         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8707         fb->height = ((val >> 16) & 0xfff) + 1;
8708         fb->width = ((val >> 0) & 0x1fff) + 1;
8709
8710         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8711         stride_mult = intel_fb_stride_alignment(fb, 0);
8712         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8713
8714         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8715
8716         plane_config->size = fb->pitches[0] * aligned_height;
8717
8718         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8719                       crtc->base.name, plane->base.name, fb->width, fb->height,
8720                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8721                       plane_config->size);
8722
8723         plane_config->fb = intel_fb;
8724         return;
8725
8726 error:
8727         kfree(intel_fb);
8728 }
8729
8730 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8731                                      struct intel_crtc_state *pipe_config)
8732 {
8733         struct drm_device *dev = crtc->base.dev;
8734         struct drm_i915_private *dev_priv = to_i915(dev);
8735         uint32_t tmp;
8736
8737         tmp = I915_READ(PF_CTL(crtc->pipe));
8738
8739         if (tmp & PF_ENABLE) {
8740                 pipe_config->pch_pfit.enabled = true;
8741                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8742                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8743
8744                 /* We currently do not free assignements of panel fitters on
8745                  * ivb/hsw (since we don't use the higher upscaling modes which
8746                  * differentiates them) so just WARN about this case for now. */
8747                 if (IS_GEN7(dev_priv)) {
8748                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8749                                 PF_PIPE_SEL_IVB(crtc->pipe));
8750                 }
8751         }
8752 }
8753
8754 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8755                                      struct intel_crtc_state *pipe_config)
8756 {
8757         struct drm_device *dev = crtc->base.dev;
8758         struct drm_i915_private *dev_priv = to_i915(dev);
8759         enum intel_display_power_domain power_domain;
8760         uint32_t tmp;
8761         bool ret;
8762
8763         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8764         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8765                 return false;
8766
8767         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8768         pipe_config->shared_dpll = NULL;
8769
8770         ret = false;
8771         tmp = I915_READ(PIPECONF(crtc->pipe));
8772         if (!(tmp & PIPECONF_ENABLE))
8773                 goto out;
8774
8775         switch (tmp & PIPECONF_BPC_MASK) {
8776         case PIPECONF_6BPC:
8777                 pipe_config->pipe_bpp = 18;
8778                 break;
8779         case PIPECONF_8BPC:
8780                 pipe_config->pipe_bpp = 24;
8781                 break;
8782         case PIPECONF_10BPC:
8783                 pipe_config->pipe_bpp = 30;
8784                 break;
8785         case PIPECONF_12BPC:
8786                 pipe_config->pipe_bpp = 36;
8787                 break;
8788         default:
8789                 break;
8790         }
8791
8792         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8793                 pipe_config->limited_color_range = true;
8794
8795         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8796                 struct intel_shared_dpll *pll;
8797                 enum intel_dpll_id pll_id;
8798
8799                 pipe_config->has_pch_encoder = true;
8800
8801                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8802                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8803                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8804
8805                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8806
8807                 if (HAS_PCH_IBX(dev_priv)) {
8808                         /*
8809                          * The pipe->pch transcoder and pch transcoder->pll
8810                          * mapping is fixed.
8811                          */
8812                         pll_id = (enum intel_dpll_id) crtc->pipe;
8813                 } else {
8814                         tmp = I915_READ(PCH_DPLL_SEL);
8815                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8816                                 pll_id = DPLL_ID_PCH_PLL_B;
8817                         else
8818                                 pll_id= DPLL_ID_PCH_PLL_A;
8819                 }
8820
8821                 pipe_config->shared_dpll =
8822                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8823                 pll = pipe_config->shared_dpll;
8824
8825                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
8826                                                 &pipe_config->dpll_hw_state));
8827
8828                 tmp = pipe_config->dpll_hw_state.dpll;
8829                 pipe_config->pixel_multiplier =
8830                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8831                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8832
8833                 ironlake_pch_clock_get(crtc, pipe_config);
8834         } else {
8835                 pipe_config->pixel_multiplier = 1;
8836         }
8837
8838         intel_get_pipe_timings(crtc, pipe_config);
8839         intel_get_pipe_src_size(crtc, pipe_config);
8840
8841         ironlake_get_pfit_config(crtc, pipe_config);
8842
8843         ret = true;
8844
8845 out:
8846         intel_display_power_put(dev_priv, power_domain);
8847
8848         return ret;
8849 }
8850
8851 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8852 {
8853         struct drm_device *dev = &dev_priv->drm;
8854         struct intel_crtc *crtc;
8855
8856         for_each_intel_crtc(dev, crtc)
8857                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8858                      pipe_name(crtc->pipe));
8859
8860         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8861                         "Display power well on\n");
8862         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8863         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8864         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8865         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8866         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8867              "CPU PWM1 enabled\n");
8868         if (IS_HASWELL(dev_priv))
8869                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8870                      "CPU PWM2 enabled\n");
8871         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8872              "PCH PWM1 enabled\n");
8873         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8874              "Utility pin enabled\n");
8875         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8876
8877         /*
8878          * In theory we can still leave IRQs enabled, as long as only the HPD
8879          * interrupts remain enabled. We used to check for that, but since it's
8880          * gen-specific and since we only disable LCPLL after we fully disable
8881          * the interrupts, the check below should be enough.
8882          */
8883         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8884 }
8885
8886 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8887 {
8888         if (IS_HASWELL(dev_priv))
8889                 return I915_READ(D_COMP_HSW);
8890         else
8891                 return I915_READ(D_COMP_BDW);
8892 }
8893
8894 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8895 {
8896         if (IS_HASWELL(dev_priv)) {
8897                 mutex_lock(&dev_priv->pcu_lock);
8898                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8899                                             val))
8900                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8901                 mutex_unlock(&dev_priv->pcu_lock);
8902         } else {
8903                 I915_WRITE(D_COMP_BDW, val);
8904                 POSTING_READ(D_COMP_BDW);
8905         }
8906 }
8907
8908 /*
8909  * This function implements pieces of two sequences from BSpec:
8910  * - Sequence for display software to disable LCPLL
8911  * - Sequence for display software to allow package C8+
8912  * The steps implemented here are just the steps that actually touch the LCPLL
8913  * register. Callers should take care of disabling all the display engine
8914  * functions, doing the mode unset, fixing interrupts, etc.
8915  */
8916 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8917                               bool switch_to_fclk, bool allow_power_down)
8918 {
8919         uint32_t val;
8920
8921         assert_can_disable_lcpll(dev_priv);
8922
8923         val = I915_READ(LCPLL_CTL);
8924
8925         if (switch_to_fclk) {
8926                 val |= LCPLL_CD_SOURCE_FCLK;
8927                 I915_WRITE(LCPLL_CTL, val);
8928
8929                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8930                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8931                         DRM_ERROR("Switching to FCLK failed\n");
8932
8933                 val = I915_READ(LCPLL_CTL);
8934         }
8935
8936         val |= LCPLL_PLL_DISABLE;
8937         I915_WRITE(LCPLL_CTL, val);
8938         POSTING_READ(LCPLL_CTL);
8939
8940         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8941                 DRM_ERROR("LCPLL still locked\n");
8942
8943         val = hsw_read_dcomp(dev_priv);
8944         val |= D_COMP_COMP_DISABLE;
8945         hsw_write_dcomp(dev_priv, val);
8946         ndelay(100);
8947
8948         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8949                      1))
8950                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8951
8952         if (allow_power_down) {
8953                 val = I915_READ(LCPLL_CTL);
8954                 val |= LCPLL_POWER_DOWN_ALLOW;
8955                 I915_WRITE(LCPLL_CTL, val);
8956                 POSTING_READ(LCPLL_CTL);
8957         }
8958 }
8959
8960 /*
8961  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8962  * source.
8963  */
8964 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8965 {
8966         uint32_t val;
8967
8968         val = I915_READ(LCPLL_CTL);
8969
8970         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8971                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8972                 return;
8973
8974         /*
8975          * Make sure we're not on PC8 state before disabling PC8, otherwise
8976          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8977          */
8978         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8979
8980         if (val & LCPLL_POWER_DOWN_ALLOW) {
8981                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8982                 I915_WRITE(LCPLL_CTL, val);
8983                 POSTING_READ(LCPLL_CTL);
8984         }
8985
8986         val = hsw_read_dcomp(dev_priv);
8987         val |= D_COMP_COMP_FORCE;
8988         val &= ~D_COMP_COMP_DISABLE;
8989         hsw_write_dcomp(dev_priv, val);
8990
8991         val = I915_READ(LCPLL_CTL);
8992         val &= ~LCPLL_PLL_DISABLE;
8993         I915_WRITE(LCPLL_CTL, val);
8994
8995         if (intel_wait_for_register(dev_priv,
8996                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8997                                     5))
8998                 DRM_ERROR("LCPLL not locked yet\n");
8999
9000         if (val & LCPLL_CD_SOURCE_FCLK) {
9001                 val = I915_READ(LCPLL_CTL);
9002                 val &= ~LCPLL_CD_SOURCE_FCLK;
9003                 I915_WRITE(LCPLL_CTL, val);
9004
9005                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9006                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9007                         DRM_ERROR("Switching back to LCPLL failed\n");
9008         }
9009
9010         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9011
9012         intel_update_cdclk(dev_priv);
9013         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9014 }
9015
9016 /*
9017  * Package states C8 and deeper are really deep PC states that can only be
9018  * reached when all the devices on the system allow it, so even if the graphics
9019  * device allows PC8+, it doesn't mean the system will actually get to these
9020  * states. Our driver only allows PC8+ when going into runtime PM.
9021  *
9022  * The requirements for PC8+ are that all the outputs are disabled, the power
9023  * well is disabled and most interrupts are disabled, and these are also
9024  * requirements for runtime PM. When these conditions are met, we manually do
9025  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9026  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9027  * hang the machine.
9028  *
9029  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9030  * the state of some registers, so when we come back from PC8+ we need to
9031  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9032  * need to take care of the registers kept by RC6. Notice that this happens even
9033  * if we don't put the device in PCI D3 state (which is what currently happens
9034  * because of the runtime PM support).
9035  *
9036  * For more, read "Display Sequences for Package C8" on the hardware
9037  * documentation.
9038  */
9039 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9040 {
9041         uint32_t val;
9042
9043         DRM_DEBUG_KMS("Enabling package C8+\n");
9044
9045         if (HAS_PCH_LPT_LP(dev_priv)) {
9046                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9047                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9048                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9049         }
9050
9051         lpt_disable_clkout_dp(dev_priv);
9052         hsw_disable_lcpll(dev_priv, true, true);
9053 }
9054
9055 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9056 {
9057         uint32_t val;
9058
9059         DRM_DEBUG_KMS("Disabling package C8+\n");
9060
9061         hsw_restore_lcpll(dev_priv);
9062         lpt_init_pch_refclk(dev_priv);
9063
9064         if (HAS_PCH_LPT_LP(dev_priv)) {
9065                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9066                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9067                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9068         }
9069 }
9070
9071 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9072                                       struct intel_crtc_state *crtc_state)
9073 {
9074         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9075                 struct intel_encoder *encoder =
9076                         intel_ddi_get_crtc_new_encoder(crtc_state);
9077
9078                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9079                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9080                                          pipe_name(crtc->pipe));
9081                         return -EINVAL;
9082                 }
9083         }
9084
9085         return 0;
9086 }
9087
9088 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9089                                    enum port port,
9090                                    struct intel_crtc_state *pipe_config)
9091 {
9092         enum intel_dpll_id id;
9093         u32 temp;
9094
9095         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9096         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9097
9098         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9099                 return;
9100
9101         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9102 }
9103
9104 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9105                                 enum port port,
9106                                 struct intel_crtc_state *pipe_config)
9107 {
9108         enum intel_dpll_id id;
9109
9110         switch (port) {
9111         case PORT_A:
9112                 id = DPLL_ID_SKL_DPLL0;
9113                 break;
9114         case PORT_B:
9115                 id = DPLL_ID_SKL_DPLL1;
9116                 break;
9117         case PORT_C:
9118                 id = DPLL_ID_SKL_DPLL2;
9119                 break;
9120         default:
9121                 DRM_ERROR("Incorrect port type\n");
9122                 return;
9123         }
9124
9125         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9126 }
9127
9128 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9129                                 enum port port,
9130                                 struct intel_crtc_state *pipe_config)
9131 {
9132         enum intel_dpll_id id;
9133         u32 temp;
9134
9135         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9136         id = temp >> (port * 3 + 1);
9137
9138         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9139                 return;
9140
9141         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9142 }
9143
9144 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9145                                 enum port port,
9146                                 struct intel_crtc_state *pipe_config)
9147 {
9148         enum intel_dpll_id id;
9149         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9150
9151         switch (ddi_pll_sel) {
9152         case PORT_CLK_SEL_WRPLL1:
9153                 id = DPLL_ID_WRPLL1;
9154                 break;
9155         case PORT_CLK_SEL_WRPLL2:
9156                 id = DPLL_ID_WRPLL2;
9157                 break;
9158         case PORT_CLK_SEL_SPLL:
9159                 id = DPLL_ID_SPLL;
9160                 break;
9161         case PORT_CLK_SEL_LCPLL_810:
9162                 id = DPLL_ID_LCPLL_810;
9163                 break;
9164         case PORT_CLK_SEL_LCPLL_1350:
9165                 id = DPLL_ID_LCPLL_1350;
9166                 break;
9167         case PORT_CLK_SEL_LCPLL_2700:
9168                 id = DPLL_ID_LCPLL_2700;
9169                 break;
9170         default:
9171                 MISSING_CASE(ddi_pll_sel);
9172                 /* fall through */
9173         case PORT_CLK_SEL_NONE:
9174                 return;
9175         }
9176
9177         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9178 }
9179
9180 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9181                                      struct intel_crtc_state *pipe_config,
9182                                      u64 *power_domain_mask)
9183 {
9184         struct drm_device *dev = crtc->base.dev;
9185         struct drm_i915_private *dev_priv = to_i915(dev);
9186         enum intel_display_power_domain power_domain;
9187         u32 tmp;
9188
9189         /*
9190          * The pipe->transcoder mapping is fixed with the exception of the eDP
9191          * transcoder handled below.
9192          */
9193         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9194
9195         /*
9196          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9197          * consistency and less surprising code; it's in always on power).
9198          */
9199         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9200         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9201                 enum pipe trans_edp_pipe;
9202                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9203                 default:
9204                         WARN(1, "unknown pipe linked to edp transcoder\n");
9205                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9206                 case TRANS_DDI_EDP_INPUT_A_ON:
9207                         trans_edp_pipe = PIPE_A;
9208                         break;
9209                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9210                         trans_edp_pipe = PIPE_B;
9211                         break;
9212                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9213                         trans_edp_pipe = PIPE_C;
9214                         break;
9215                 }
9216
9217                 if (trans_edp_pipe == crtc->pipe)
9218                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9219         }
9220
9221         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9222         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9223                 return false;
9224         *power_domain_mask |= BIT_ULL(power_domain);
9225
9226         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9227
9228         return tmp & PIPECONF_ENABLE;
9229 }
9230
9231 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9232                                          struct intel_crtc_state *pipe_config,
9233                                          u64 *power_domain_mask)
9234 {
9235         struct drm_device *dev = crtc->base.dev;
9236         struct drm_i915_private *dev_priv = to_i915(dev);
9237         enum intel_display_power_domain power_domain;
9238         enum port port;
9239         enum transcoder cpu_transcoder;
9240         u32 tmp;
9241
9242         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9243                 if (port == PORT_A)
9244                         cpu_transcoder = TRANSCODER_DSI_A;
9245                 else
9246                         cpu_transcoder = TRANSCODER_DSI_C;
9247
9248                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9249                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9250                         continue;
9251                 *power_domain_mask |= BIT_ULL(power_domain);
9252
9253                 /*
9254                  * The PLL needs to be enabled with a valid divider
9255                  * configuration, otherwise accessing DSI registers will hang
9256                  * the machine. See BSpec North Display Engine
9257                  * registers/MIPI[BXT]. We can break out here early, since we
9258                  * need the same DSI PLL to be enabled for both DSI ports.
9259                  */
9260                 if (!intel_dsi_pll_is_enabled(dev_priv))
9261                         break;
9262
9263                 /* XXX: this works for video mode only */
9264                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9265                 if (!(tmp & DPI_ENABLE))
9266                         continue;
9267
9268                 tmp = I915_READ(MIPI_CTRL(port));
9269                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9270                         continue;
9271
9272                 pipe_config->cpu_transcoder = cpu_transcoder;
9273                 break;
9274         }
9275
9276         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9277 }
9278
9279 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9280                                        struct intel_crtc_state *pipe_config)
9281 {
9282         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9283         struct intel_shared_dpll *pll;
9284         enum port port;
9285         uint32_t tmp;
9286
9287         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9288
9289         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9290
9291         if (IS_CANNONLAKE(dev_priv))
9292                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9293         else if (IS_GEN9_BC(dev_priv))
9294                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9295         else if (IS_GEN9_LP(dev_priv))
9296                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9297         else
9298                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9299
9300         pll = pipe_config->shared_dpll;
9301         if (pll) {
9302                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9303                                                 &pipe_config->dpll_hw_state));
9304         }
9305
9306         /*
9307          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9308          * DDI E. So just check whether this pipe is wired to DDI E and whether
9309          * the PCH transcoder is on.
9310          */
9311         if (INTEL_GEN(dev_priv) < 9 &&
9312             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9313                 pipe_config->has_pch_encoder = true;
9314
9315                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9316                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9317                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9318
9319                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9320         }
9321 }
9322
9323 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9324                                     struct intel_crtc_state *pipe_config)
9325 {
9326         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9327         enum intel_display_power_domain power_domain;
9328         u64 power_domain_mask;
9329         bool active;
9330
9331         intel_crtc_init_scalers(crtc, pipe_config);
9332
9333         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9334         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9335                 return false;
9336         power_domain_mask = BIT_ULL(power_domain);
9337
9338         pipe_config->shared_dpll = NULL;
9339
9340         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9341
9342         if (IS_GEN9_LP(dev_priv) &&
9343             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9344                 WARN_ON(active);
9345                 active = true;
9346         }
9347
9348         if (!active)
9349                 goto out;
9350
9351         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9352                 haswell_get_ddi_port_state(crtc, pipe_config);
9353                 intel_get_pipe_timings(crtc, pipe_config);
9354         }
9355
9356         intel_get_pipe_src_size(crtc, pipe_config);
9357
9358         pipe_config->gamma_mode =
9359                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9360
9361         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9362                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9363                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9364
9365                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9366                         bool blend_mode_420 = tmp &
9367                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9368
9369                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9370                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9371                             pipe_config->ycbcr420 != blend_mode_420)
9372                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9373                 } else if (clrspace_yuv) {
9374                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9375                 }
9376         }
9377
9378         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9379         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9380                 power_domain_mask |= BIT_ULL(power_domain);
9381                 if (INTEL_GEN(dev_priv) >= 9)
9382                         skylake_get_pfit_config(crtc, pipe_config);
9383                 else
9384                         ironlake_get_pfit_config(crtc, pipe_config);
9385         }
9386
9387         if (hsw_crtc_supports_ips(crtc)) {
9388                 if (IS_HASWELL(dev_priv))
9389                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9390                 else {
9391                         /*
9392                          * We cannot readout IPS state on broadwell, set to
9393                          * true so we can set it to a defined state on first
9394                          * commit.
9395                          */
9396                         pipe_config->ips_enabled = true;
9397                 }
9398         }
9399
9400         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9401             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9402                 pipe_config->pixel_multiplier =
9403                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9404         } else {
9405                 pipe_config->pixel_multiplier = 1;
9406         }
9407
9408 out:
9409         for_each_power_domain(power_domain, power_domain_mask)
9410                 intel_display_power_put(dev_priv, power_domain);
9411
9412         return active;
9413 }
9414
9415 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9416 {
9417         struct drm_i915_private *dev_priv =
9418                 to_i915(plane_state->base.plane->dev);
9419         const struct drm_framebuffer *fb = plane_state->base.fb;
9420         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9421         u32 base;
9422
9423         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9424                 base = obj->phys_handle->busaddr;
9425         else
9426                 base = intel_plane_ggtt_offset(plane_state);
9427
9428         base += plane_state->main.offset;
9429
9430         /* ILK+ do this automagically */
9431         if (HAS_GMCH_DISPLAY(dev_priv) &&
9432             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9433                 base += (plane_state->base.crtc_h *
9434                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9435
9436         return base;
9437 }
9438
9439 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9440 {
9441         int x = plane_state->base.crtc_x;
9442         int y = plane_state->base.crtc_y;
9443         u32 pos = 0;
9444
9445         if (x < 0) {
9446                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9447                 x = -x;
9448         }
9449         pos |= x << CURSOR_X_SHIFT;
9450
9451         if (y < 0) {
9452                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9453                 y = -y;
9454         }
9455         pos |= y << CURSOR_Y_SHIFT;
9456
9457         return pos;
9458 }
9459
9460 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9461 {
9462         const struct drm_mode_config *config =
9463                 &plane_state->base.plane->dev->mode_config;
9464         int width = plane_state->base.crtc_w;
9465         int height = plane_state->base.crtc_h;
9466
9467         return width > 0 && width <= config->cursor_width &&
9468                 height > 0 && height <= config->cursor_height;
9469 }
9470
9471 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9472                               struct intel_plane_state *plane_state)
9473 {
9474         const struct drm_framebuffer *fb = plane_state->base.fb;
9475         int src_x, src_y;
9476         u32 offset;
9477         int ret;
9478
9479         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9480                                                   &crtc_state->base,
9481                                                   DRM_PLANE_HELPER_NO_SCALING,
9482                                                   DRM_PLANE_HELPER_NO_SCALING,
9483                                                   true, true);
9484         if (ret)
9485                 return ret;
9486
9487         if (!fb)
9488                 return 0;
9489
9490         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9491                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9492                 return -EINVAL;
9493         }
9494
9495         src_x = plane_state->base.src_x >> 16;
9496         src_y = plane_state->base.src_y >> 16;
9497
9498         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9499         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9500
9501         if (src_x != 0 || src_y != 0) {
9502                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9503                 return -EINVAL;
9504         }
9505
9506         plane_state->main.offset = offset;
9507
9508         return 0;
9509 }
9510
9511 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9512                            const struct intel_plane_state *plane_state)
9513 {
9514         const struct drm_framebuffer *fb = plane_state->base.fb;
9515
9516         return CURSOR_ENABLE |
9517                 CURSOR_GAMMA_ENABLE |
9518                 CURSOR_FORMAT_ARGB |
9519                 CURSOR_STRIDE(fb->pitches[0]);
9520 }
9521
9522 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9523 {
9524         int width = plane_state->base.crtc_w;
9525
9526         /*
9527          * 845g/865g are only limited by the width of their cursors,
9528          * the height is arbitrary up to the precision of the register.
9529          */
9530         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9531 }
9532
9533 static int i845_check_cursor(struct intel_plane *plane,
9534                              struct intel_crtc_state *crtc_state,
9535                              struct intel_plane_state *plane_state)
9536 {
9537         const struct drm_framebuffer *fb = plane_state->base.fb;
9538         int ret;
9539
9540         ret = intel_check_cursor(crtc_state, plane_state);
9541         if (ret)
9542                 return ret;
9543
9544         /* if we want to turn off the cursor ignore width and height */
9545         if (!fb)
9546                 return 0;
9547
9548         /* Check for which cursor types we support */
9549         if (!i845_cursor_size_ok(plane_state)) {
9550                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9551                           plane_state->base.crtc_w,
9552                           plane_state->base.crtc_h);
9553                 return -EINVAL;
9554         }
9555
9556         switch (fb->pitches[0]) {
9557         case 256:
9558         case 512:
9559         case 1024:
9560         case 2048:
9561                 break;
9562         default:
9563                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9564                               fb->pitches[0]);
9565                 return -EINVAL;
9566         }
9567
9568         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9569
9570         return 0;
9571 }
9572
9573 static void i845_update_cursor(struct intel_plane *plane,
9574                                const struct intel_crtc_state *crtc_state,
9575                                const struct intel_plane_state *plane_state)
9576 {
9577         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9578         u32 cntl = 0, base = 0, pos = 0, size = 0;
9579         unsigned long irqflags;
9580
9581         if (plane_state && plane_state->base.visible) {
9582                 unsigned int width = plane_state->base.crtc_w;
9583                 unsigned int height = plane_state->base.crtc_h;
9584
9585                 cntl = plane_state->ctl;
9586                 size = (height << 12) | width;
9587
9588                 base = intel_cursor_base(plane_state);
9589                 pos = intel_cursor_position(plane_state);
9590         }
9591
9592         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9593
9594         /* On these chipsets we can only modify the base/size/stride
9595          * whilst the cursor is disabled.
9596          */
9597         if (plane->cursor.base != base ||
9598             plane->cursor.size != size ||
9599             plane->cursor.cntl != cntl) {
9600                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9601                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9602                 I915_WRITE_FW(CURSIZE, size);
9603                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9604                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9605
9606                 plane->cursor.base = base;
9607                 plane->cursor.size = size;
9608                 plane->cursor.cntl = cntl;
9609         } else {
9610                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9611         }
9612
9613         POSTING_READ_FW(CURCNTR(PIPE_A));
9614
9615         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9616 }
9617
9618 static void i845_disable_cursor(struct intel_plane *plane,
9619                                 struct intel_crtc *crtc)
9620 {
9621         i845_update_cursor(plane, NULL, NULL);
9622 }
9623
9624 static bool i845_cursor_get_hw_state(struct intel_plane *plane)
9625 {
9626         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9627         enum intel_display_power_domain power_domain;
9628         bool ret;
9629
9630         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9631         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9632                 return false;
9633
9634         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9635
9636         intel_display_power_put(dev_priv, power_domain);
9637
9638         return ret;
9639 }
9640
9641 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9642                            const struct intel_plane_state *plane_state)
9643 {
9644         struct drm_i915_private *dev_priv =
9645                 to_i915(plane_state->base.plane->dev);
9646         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9647         u32 cntl;
9648
9649         cntl = MCURSOR_GAMMA_ENABLE;
9650
9651         if (HAS_DDI(dev_priv))
9652                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9653
9654         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9655                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9656
9657         switch (plane_state->base.crtc_w) {
9658         case 64:
9659                 cntl |= CURSOR_MODE_64_ARGB_AX;
9660                 break;
9661         case 128:
9662                 cntl |= CURSOR_MODE_128_ARGB_AX;
9663                 break;
9664         case 256:
9665                 cntl |= CURSOR_MODE_256_ARGB_AX;
9666                 break;
9667         default:
9668                 MISSING_CASE(plane_state->base.crtc_w);
9669                 return 0;
9670         }
9671
9672         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9673                 cntl |= CURSOR_ROTATE_180;
9674
9675         return cntl;
9676 }
9677
9678 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9679 {
9680         struct drm_i915_private *dev_priv =
9681                 to_i915(plane_state->base.plane->dev);
9682         int width = plane_state->base.crtc_w;
9683         int height = plane_state->base.crtc_h;
9684
9685         if (!intel_cursor_size_ok(plane_state))
9686                 return false;
9687
9688         /* Cursor width is limited to a few power-of-two sizes */
9689         switch (width) {
9690         case 256:
9691         case 128:
9692         case 64:
9693                 break;
9694         default:
9695                 return false;
9696         }
9697
9698         /*
9699          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9700          * height from 8 lines up to the cursor width, when the
9701          * cursor is not rotated. Everything else requires square
9702          * cursors.
9703          */
9704         if (HAS_CUR_FBC(dev_priv) &&
9705             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9706                 if (height < 8 || height > width)
9707                         return false;
9708         } else {
9709                 if (height != width)
9710                         return false;
9711         }
9712
9713         return true;
9714 }
9715
9716 static int i9xx_check_cursor(struct intel_plane *plane,
9717                              struct intel_crtc_state *crtc_state,
9718                              struct intel_plane_state *plane_state)
9719 {
9720         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9721         const struct drm_framebuffer *fb = plane_state->base.fb;
9722         enum pipe pipe = plane->pipe;
9723         int ret;
9724
9725         ret = intel_check_cursor(crtc_state, plane_state);
9726         if (ret)
9727                 return ret;
9728
9729         /* if we want to turn off the cursor ignore width and height */
9730         if (!fb)
9731                 return 0;
9732
9733         /* Check for which cursor types we support */
9734         if (!i9xx_cursor_size_ok(plane_state)) {
9735                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9736                           plane_state->base.crtc_w,
9737                           plane_state->base.crtc_h);
9738                 return -EINVAL;
9739         }
9740
9741         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9742                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9743                               fb->pitches[0], plane_state->base.crtc_w);
9744                 return -EINVAL;
9745         }
9746
9747         /*
9748          * There's something wrong with the cursor on CHV pipe C.
9749          * If it straddles the left edge of the screen then
9750          * moving it away from the edge or disabling it often
9751          * results in a pipe underrun, and often that can lead to
9752          * dead pipe (constant underrun reported, and it scans
9753          * out just a solid color). To recover from that, the
9754          * display power well must be turned off and on again.
9755          * Refuse the put the cursor into that compromised position.
9756          */
9757         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9758             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9759                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9760                 return -EINVAL;
9761         }
9762
9763         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9764
9765         return 0;
9766 }
9767
9768 static void i9xx_update_cursor(struct intel_plane *plane,
9769                                const struct intel_crtc_state *crtc_state,
9770                                const struct intel_plane_state *plane_state)
9771 {
9772         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9773         enum pipe pipe = plane->pipe;
9774         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9775         unsigned long irqflags;
9776
9777         if (plane_state && plane_state->base.visible) {
9778                 cntl = plane_state->ctl;
9779
9780                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9781                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9782
9783                 base = intel_cursor_base(plane_state);
9784                 pos = intel_cursor_position(plane_state);
9785         }
9786
9787         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9788
9789         /*
9790          * On some platforms writing CURCNTR first will also
9791          * cause CURPOS to be armed by the CURBASE write.
9792          * Without the CURCNTR write the CURPOS write would
9793          * arm itself. Thus we always start the full update
9794          * with a CURCNTR write.
9795          *
9796          * On other platforms CURPOS always requires the
9797          * CURBASE write to arm the update. Additonally
9798          * a write to any of the cursor register will cancel
9799          * an already armed cursor update. Thus leaving out
9800          * the CURBASE write after CURPOS could lead to a
9801          * cursor that doesn't appear to move, or even change
9802          * shape. Thus we always write CURBASE.
9803          *
9804          * CURCNTR and CUR_FBC_CTL are always
9805          * armed by the CURBASE write only.
9806          */
9807         if (plane->cursor.base != base ||
9808             plane->cursor.size != fbc_ctl ||
9809             plane->cursor.cntl != cntl) {
9810                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9811                 if (HAS_CUR_FBC(dev_priv))
9812                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9813                 I915_WRITE_FW(CURPOS(pipe), pos);
9814                 I915_WRITE_FW(CURBASE(pipe), base);
9815
9816                 plane->cursor.base = base;
9817                 plane->cursor.size = fbc_ctl;
9818                 plane->cursor.cntl = cntl;
9819         } else {
9820                 I915_WRITE_FW(CURPOS(pipe), pos);
9821                 I915_WRITE_FW(CURBASE(pipe), base);
9822         }
9823
9824         POSTING_READ_FW(CURBASE(pipe));
9825
9826         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9827 }
9828
9829 static void i9xx_disable_cursor(struct intel_plane *plane,
9830                                 struct intel_crtc *crtc)
9831 {
9832         i9xx_update_cursor(plane, NULL, NULL);
9833 }
9834
9835 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane)
9836 {
9837         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9838         enum intel_display_power_domain power_domain;
9839         enum pipe pipe = plane->pipe;
9840         bool ret;
9841
9842         /*
9843          * Not 100% correct for planes that can move between pipes,
9844          * but that's only the case for gen2-3 which don't have any
9845          * display power wells.
9846          */
9847         power_domain = POWER_DOMAIN_PIPE(pipe);
9848         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9849                 return false;
9850
9851         ret = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
9852
9853         intel_display_power_put(dev_priv, power_domain);
9854
9855         return ret;
9856 }
9857
9858 /* VESA 640x480x72Hz mode to set on the pipe */
9859 static const struct drm_display_mode load_detect_mode = {
9860         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9861                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9862 };
9863
9864 struct drm_framebuffer *
9865 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9866                          struct drm_mode_fb_cmd2 *mode_cmd)
9867 {
9868         struct intel_framebuffer *intel_fb;
9869         int ret;
9870
9871         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9872         if (!intel_fb)
9873                 return ERR_PTR(-ENOMEM);
9874
9875         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9876         if (ret)
9877                 goto err;
9878
9879         return &intel_fb->base;
9880
9881 err:
9882         kfree(intel_fb);
9883         return ERR_PTR(ret);
9884 }
9885
9886 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
9887                                         struct drm_crtc *crtc)
9888 {
9889         struct drm_plane *plane;
9890         struct drm_plane_state *plane_state;
9891         int ret, i;
9892
9893         ret = drm_atomic_add_affected_planes(state, crtc);
9894         if (ret)
9895                 return ret;
9896
9897         for_each_new_plane_in_state(state, plane, plane_state, i) {
9898                 if (plane_state->crtc != crtc)
9899                         continue;
9900
9901                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
9902                 if (ret)
9903                         return ret;
9904
9905                 drm_atomic_set_fb_for_plane(plane_state, NULL);
9906         }
9907
9908         return 0;
9909 }
9910
9911 int intel_get_load_detect_pipe(struct drm_connector *connector,
9912                                const struct drm_display_mode *mode,
9913                                struct intel_load_detect_pipe *old,
9914                                struct drm_modeset_acquire_ctx *ctx)
9915 {
9916         struct intel_crtc *intel_crtc;
9917         struct intel_encoder *intel_encoder =
9918                 intel_attached_encoder(connector);
9919         struct drm_crtc *possible_crtc;
9920         struct drm_encoder *encoder = &intel_encoder->base;
9921         struct drm_crtc *crtc = NULL;
9922         struct drm_device *dev = encoder->dev;
9923         struct drm_i915_private *dev_priv = to_i915(dev);
9924         struct drm_mode_config *config = &dev->mode_config;
9925         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9926         struct drm_connector_state *connector_state;
9927         struct intel_crtc_state *crtc_state;
9928         int ret, i = -1;
9929
9930         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9931                       connector->base.id, connector->name,
9932                       encoder->base.id, encoder->name);
9933
9934         old->restore_state = NULL;
9935
9936         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9937
9938         /*
9939          * Algorithm gets a little messy:
9940          *
9941          *   - if the connector already has an assigned crtc, use it (but make
9942          *     sure it's on first)
9943          *
9944          *   - try to find the first unused crtc that can drive this connector,
9945          *     and use that if we find one
9946          */
9947
9948         /* See if we already have a CRTC for this connector */
9949         if (connector->state->crtc) {
9950                 crtc = connector->state->crtc;
9951
9952                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9953                 if (ret)
9954                         goto fail;
9955
9956                 /* Make sure the crtc and connector are running */
9957                 goto found;
9958         }
9959
9960         /* Find an unused one (if possible) */
9961         for_each_crtc(dev, possible_crtc) {
9962                 i++;
9963                 if (!(encoder->possible_crtcs & (1 << i)))
9964                         continue;
9965
9966                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9967                 if (ret)
9968                         goto fail;
9969
9970                 if (possible_crtc->state->enable) {
9971                         drm_modeset_unlock(&possible_crtc->mutex);
9972                         continue;
9973                 }
9974
9975                 crtc = possible_crtc;
9976                 break;
9977         }
9978
9979         /*
9980          * If we didn't find an unused CRTC, don't use any.
9981          */
9982         if (!crtc) {
9983                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9984                 ret = -ENODEV;
9985                 goto fail;
9986         }
9987
9988 found:
9989         intel_crtc = to_intel_crtc(crtc);
9990
9991         state = drm_atomic_state_alloc(dev);
9992         restore_state = drm_atomic_state_alloc(dev);
9993         if (!state || !restore_state) {
9994                 ret = -ENOMEM;
9995                 goto fail;
9996         }
9997
9998         state->acquire_ctx = ctx;
9999         restore_state->acquire_ctx = ctx;
10000
10001         connector_state = drm_atomic_get_connector_state(state, connector);
10002         if (IS_ERR(connector_state)) {
10003                 ret = PTR_ERR(connector_state);
10004                 goto fail;
10005         }
10006
10007         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10008         if (ret)
10009                 goto fail;
10010
10011         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10012         if (IS_ERR(crtc_state)) {
10013                 ret = PTR_ERR(crtc_state);
10014                 goto fail;
10015         }
10016
10017         crtc_state->base.active = crtc_state->base.enable = true;
10018
10019         if (!mode)
10020                 mode = &load_detect_mode;
10021
10022         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10023         if (ret)
10024                 goto fail;
10025
10026         ret = intel_modeset_disable_planes(state, crtc);
10027         if (ret)
10028                 goto fail;
10029
10030         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10031         if (!ret)
10032                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10033         if (!ret)
10034                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10035         if (ret) {
10036                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10037                 goto fail;
10038         }
10039
10040         ret = drm_atomic_commit(state);
10041         if (ret) {
10042                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10043                 goto fail;
10044         }
10045
10046         old->restore_state = restore_state;
10047         drm_atomic_state_put(state);
10048
10049         /* let the connector get through one full cycle before testing */
10050         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10051         return true;
10052
10053 fail:
10054         if (state) {
10055                 drm_atomic_state_put(state);
10056                 state = NULL;
10057         }
10058         if (restore_state) {
10059                 drm_atomic_state_put(restore_state);
10060                 restore_state = NULL;
10061         }
10062
10063         if (ret == -EDEADLK)
10064                 return ret;
10065
10066         return false;
10067 }
10068
10069 void intel_release_load_detect_pipe(struct drm_connector *connector,
10070                                     struct intel_load_detect_pipe *old,
10071                                     struct drm_modeset_acquire_ctx *ctx)
10072 {
10073         struct intel_encoder *intel_encoder =
10074                 intel_attached_encoder(connector);
10075         struct drm_encoder *encoder = &intel_encoder->base;
10076         struct drm_atomic_state *state = old->restore_state;
10077         int ret;
10078
10079         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10080                       connector->base.id, connector->name,
10081                       encoder->base.id, encoder->name);
10082
10083         if (!state)
10084                 return;
10085
10086         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10087         if (ret)
10088                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10089         drm_atomic_state_put(state);
10090 }
10091
10092 static int i9xx_pll_refclk(struct drm_device *dev,
10093                            const struct intel_crtc_state *pipe_config)
10094 {
10095         struct drm_i915_private *dev_priv = to_i915(dev);
10096         u32 dpll = pipe_config->dpll_hw_state.dpll;
10097
10098         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10099                 return dev_priv->vbt.lvds_ssc_freq;
10100         else if (HAS_PCH_SPLIT(dev_priv))
10101                 return 120000;
10102         else if (!IS_GEN2(dev_priv))
10103                 return 96000;
10104         else
10105                 return 48000;
10106 }
10107
10108 /* Returns the clock of the currently programmed mode of the given pipe. */
10109 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10110                                 struct intel_crtc_state *pipe_config)
10111 {
10112         struct drm_device *dev = crtc->base.dev;
10113         struct drm_i915_private *dev_priv = to_i915(dev);
10114         int pipe = pipe_config->cpu_transcoder;
10115         u32 dpll = pipe_config->dpll_hw_state.dpll;
10116         u32 fp;
10117         struct dpll clock;
10118         int port_clock;
10119         int refclk = i9xx_pll_refclk(dev, pipe_config);
10120
10121         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10122                 fp = pipe_config->dpll_hw_state.fp0;
10123         else
10124                 fp = pipe_config->dpll_hw_state.fp1;
10125
10126         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10127         if (IS_PINEVIEW(dev_priv)) {
10128                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10129                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10130         } else {
10131                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10132                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10133         }
10134
10135         if (!IS_GEN2(dev_priv)) {
10136                 if (IS_PINEVIEW(dev_priv))
10137                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10138                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10139                 else
10140                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10141                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10142
10143                 switch (dpll & DPLL_MODE_MASK) {
10144                 case DPLLB_MODE_DAC_SERIAL:
10145                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10146                                 5 : 10;
10147                         break;
10148                 case DPLLB_MODE_LVDS:
10149                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10150                                 7 : 14;
10151                         break;
10152                 default:
10153                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10154                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10155                         return;
10156                 }
10157
10158                 if (IS_PINEVIEW(dev_priv))
10159                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10160                 else
10161                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10162         } else {
10163                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10164                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10165
10166                 if (is_lvds) {
10167                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10168                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10169
10170                         if (lvds & LVDS_CLKB_POWER_UP)
10171                                 clock.p2 = 7;
10172                         else
10173                                 clock.p2 = 14;
10174                 } else {
10175                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10176                                 clock.p1 = 2;
10177                         else {
10178                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10179                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10180                         }
10181                         if (dpll & PLL_P2_DIVIDE_BY_4)
10182                                 clock.p2 = 4;
10183                         else
10184                                 clock.p2 = 2;
10185                 }
10186
10187                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10188         }
10189
10190         /*
10191          * This value includes pixel_multiplier. We will use
10192          * port_clock to compute adjusted_mode.crtc_clock in the
10193          * encoder's get_config() function.
10194          */
10195         pipe_config->port_clock = port_clock;
10196 }
10197
10198 int intel_dotclock_calculate(int link_freq,
10199                              const struct intel_link_m_n *m_n)
10200 {
10201         /*
10202          * The calculation for the data clock is:
10203          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10204          * But we want to avoid losing precison if possible, so:
10205          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10206          *
10207          * and the link clock is simpler:
10208          * link_clock = (m * link_clock) / n
10209          */
10210
10211         if (!m_n->link_n)
10212                 return 0;
10213
10214         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10215 }
10216
10217 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10218                                    struct intel_crtc_state *pipe_config)
10219 {
10220         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10221
10222         /* read out port_clock from the DPLL */
10223         i9xx_crtc_clock_get(crtc, pipe_config);
10224
10225         /*
10226          * In case there is an active pipe without active ports,
10227          * we may need some idea for the dotclock anyway.
10228          * Calculate one based on the FDI configuration.
10229          */
10230         pipe_config->base.adjusted_mode.crtc_clock =
10231                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10232                                          &pipe_config->fdi_m_n);
10233 }
10234
10235 /* Returns the currently programmed mode of the given encoder. */
10236 struct drm_display_mode *
10237 intel_encoder_current_mode(struct intel_encoder *encoder)
10238 {
10239         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10240         struct intel_crtc_state *crtc_state;
10241         struct drm_display_mode *mode;
10242         struct intel_crtc *crtc;
10243         enum pipe pipe;
10244
10245         if (!encoder->get_hw_state(encoder, &pipe))
10246                 return NULL;
10247
10248         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10249
10250         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10251         if (!mode)
10252                 return NULL;
10253
10254         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10255         if (!crtc_state) {
10256                 kfree(mode);
10257                 return NULL;
10258         }
10259
10260         crtc_state->base.crtc = &crtc->base;
10261
10262         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10263                 kfree(crtc_state);
10264                 kfree(mode);
10265                 return NULL;
10266         }
10267
10268         encoder->get_config(encoder, crtc_state);
10269
10270         intel_mode_from_pipe_config(mode, crtc_state);
10271
10272         kfree(crtc_state);
10273
10274         return mode;
10275 }
10276
10277 static void intel_crtc_destroy(struct drm_crtc *crtc)
10278 {
10279         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10280
10281         drm_crtc_cleanup(crtc);
10282         kfree(intel_crtc);
10283 }
10284
10285 /**
10286  * intel_wm_need_update - Check whether watermarks need updating
10287  * @plane: drm plane
10288  * @state: new plane state
10289  *
10290  * Check current plane state versus the new one to determine whether
10291  * watermarks need to be recalculated.
10292  *
10293  * Returns true or false.
10294  */
10295 static bool intel_wm_need_update(struct drm_plane *plane,
10296                                  struct drm_plane_state *state)
10297 {
10298         struct intel_plane_state *new = to_intel_plane_state(state);
10299         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10300
10301         /* Update watermarks on tiling or size changes. */
10302         if (new->base.visible != cur->base.visible)
10303                 return true;
10304
10305         if (!cur->base.fb || !new->base.fb)
10306                 return false;
10307
10308         if (cur->base.fb->modifier != new->base.fb->modifier ||
10309             cur->base.rotation != new->base.rotation ||
10310             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10311             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10312             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10313             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10314                 return true;
10315
10316         return false;
10317 }
10318
10319 static bool needs_scaling(const struct intel_plane_state *state)
10320 {
10321         int src_w = drm_rect_width(&state->base.src) >> 16;
10322         int src_h = drm_rect_height(&state->base.src) >> 16;
10323         int dst_w = drm_rect_width(&state->base.dst);
10324         int dst_h = drm_rect_height(&state->base.dst);
10325
10326         return (src_w != dst_w || src_h != dst_h);
10327 }
10328
10329 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10330                                     struct drm_crtc_state *crtc_state,
10331                                     const struct intel_plane_state *old_plane_state,
10332                                     struct drm_plane_state *plane_state)
10333 {
10334         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10335         struct drm_crtc *crtc = crtc_state->crtc;
10336         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10337         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10338         struct drm_device *dev = crtc->dev;
10339         struct drm_i915_private *dev_priv = to_i915(dev);
10340         bool mode_changed = needs_modeset(crtc_state);
10341         bool was_crtc_enabled = old_crtc_state->base.active;
10342         bool is_crtc_enabled = crtc_state->active;
10343         bool turn_off, turn_on, visible, was_visible;
10344         struct drm_framebuffer *fb = plane_state->fb;
10345         int ret;
10346
10347         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10348                 ret = skl_update_scaler_plane(
10349                         to_intel_crtc_state(crtc_state),
10350                         to_intel_plane_state(plane_state));
10351                 if (ret)
10352                         return ret;
10353         }
10354
10355         was_visible = old_plane_state->base.visible;
10356         visible = plane_state->visible;
10357
10358         if (!was_crtc_enabled && WARN_ON(was_visible))
10359                 was_visible = false;
10360
10361         /*
10362          * Visibility is calculated as if the crtc was on, but
10363          * after scaler setup everything depends on it being off
10364          * when the crtc isn't active.
10365          *
10366          * FIXME this is wrong for watermarks. Watermarks should also
10367          * be computed as if the pipe would be active. Perhaps move
10368          * per-plane wm computation to the .check_plane() hook, and
10369          * only combine the results from all planes in the current place?
10370          */
10371         if (!is_crtc_enabled) {
10372                 plane_state->visible = visible = false;
10373                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10374         }
10375
10376         if (!was_visible && !visible)
10377                 return 0;
10378
10379         if (fb != old_plane_state->base.fb)
10380                 pipe_config->fb_changed = true;
10381
10382         turn_off = was_visible && (!visible || mode_changed);
10383         turn_on = visible && (!was_visible || mode_changed);
10384
10385         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10386                          intel_crtc->base.base.id, intel_crtc->base.name,
10387                          plane->base.base.id, plane->base.name,
10388                          fb ? fb->base.id : -1);
10389
10390         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10391                          plane->base.base.id, plane->base.name,
10392                          was_visible, visible,
10393                          turn_off, turn_on, mode_changed);
10394
10395         if (turn_on) {
10396                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10397                         pipe_config->update_wm_pre = true;
10398
10399                 /* must disable cxsr around plane enable/disable */
10400                 if (plane->id != PLANE_CURSOR)
10401                         pipe_config->disable_cxsr = true;
10402         } else if (turn_off) {
10403                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10404                         pipe_config->update_wm_post = true;
10405
10406                 /* must disable cxsr around plane enable/disable */
10407                 if (plane->id != PLANE_CURSOR)
10408                         pipe_config->disable_cxsr = true;
10409         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10410                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10411                         /* FIXME bollocks */
10412                         pipe_config->update_wm_pre = true;
10413                         pipe_config->update_wm_post = true;
10414                 }
10415         }
10416
10417         if (visible || was_visible)
10418                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10419
10420         /*
10421          * WaCxSRDisabledForSpriteScaling:ivb
10422          *
10423          * cstate->update_wm was already set above, so this flag will
10424          * take effect when we commit and program watermarks.
10425          */
10426         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10427             needs_scaling(to_intel_plane_state(plane_state)) &&
10428             !needs_scaling(old_plane_state))
10429                 pipe_config->disable_lp_wm = true;
10430
10431         return 0;
10432 }
10433
10434 static bool encoders_cloneable(const struct intel_encoder *a,
10435                                const struct intel_encoder *b)
10436 {
10437         /* masks could be asymmetric, so check both ways */
10438         return a == b || (a->cloneable & (1 << b->type) &&
10439                           b->cloneable & (1 << a->type));
10440 }
10441
10442 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10443                                          struct intel_crtc *crtc,
10444                                          struct intel_encoder *encoder)
10445 {
10446         struct intel_encoder *source_encoder;
10447         struct drm_connector *connector;
10448         struct drm_connector_state *connector_state;
10449         int i;
10450
10451         for_each_new_connector_in_state(state, connector, connector_state, i) {
10452                 if (connector_state->crtc != &crtc->base)
10453                         continue;
10454
10455                 source_encoder =
10456                         to_intel_encoder(connector_state->best_encoder);
10457                 if (!encoders_cloneable(encoder, source_encoder))
10458                         return false;
10459         }
10460
10461         return true;
10462 }
10463
10464 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10465                                    struct drm_crtc_state *crtc_state)
10466 {
10467         struct drm_device *dev = crtc->dev;
10468         struct drm_i915_private *dev_priv = to_i915(dev);
10469         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10470         struct intel_crtc_state *pipe_config =
10471                 to_intel_crtc_state(crtc_state);
10472         struct drm_atomic_state *state = crtc_state->state;
10473         int ret;
10474         bool mode_changed = needs_modeset(crtc_state);
10475
10476         if (mode_changed && !crtc_state->active)
10477                 pipe_config->update_wm_post = true;
10478
10479         if (mode_changed && crtc_state->enable &&
10480             dev_priv->display.crtc_compute_clock &&
10481             !WARN_ON(pipe_config->shared_dpll)) {
10482                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10483                                                            pipe_config);
10484                 if (ret)
10485                         return ret;
10486         }
10487
10488         if (crtc_state->color_mgmt_changed) {
10489                 ret = intel_color_check(crtc, crtc_state);
10490                 if (ret)
10491                         return ret;
10492
10493                 /*
10494                  * Changing color management on Intel hardware is
10495                  * handled as part of planes update.
10496                  */
10497                 crtc_state->planes_changed = true;
10498         }
10499
10500         ret = 0;
10501         if (dev_priv->display.compute_pipe_wm) {
10502                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10503                 if (ret) {
10504                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10505                         return ret;
10506                 }
10507         }
10508
10509         if (dev_priv->display.compute_intermediate_wm &&
10510             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10511                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10512                         return 0;
10513
10514                 /*
10515                  * Calculate 'intermediate' watermarks that satisfy both the
10516                  * old state and the new state.  We can program these
10517                  * immediately.
10518                  */
10519                 ret = dev_priv->display.compute_intermediate_wm(dev,
10520                                                                 intel_crtc,
10521                                                                 pipe_config);
10522                 if (ret) {
10523                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10524                         return ret;
10525                 }
10526         } else if (dev_priv->display.compute_intermediate_wm) {
10527                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10528                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10529         }
10530
10531         if (INTEL_GEN(dev_priv) >= 9) {
10532                 if (mode_changed)
10533                         ret = skl_update_scaler_crtc(pipe_config);
10534
10535                 if (!ret)
10536                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10537                                                             pipe_config);
10538                 if (!ret)
10539                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10540                                                          pipe_config);
10541         }
10542
10543         if (HAS_IPS(dev_priv))
10544                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10545
10546         return ret;
10547 }
10548
10549 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10550         .atomic_begin = intel_begin_crtc_commit,
10551         .atomic_flush = intel_finish_crtc_commit,
10552         .atomic_check = intel_crtc_atomic_check,
10553 };
10554
10555 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10556 {
10557         struct intel_connector *connector;
10558         struct drm_connector_list_iter conn_iter;
10559
10560         drm_connector_list_iter_begin(dev, &conn_iter);
10561         for_each_intel_connector_iter(connector, &conn_iter) {
10562                 if (connector->base.state->crtc)
10563                         drm_connector_unreference(&connector->base);
10564
10565                 if (connector->base.encoder) {
10566                         connector->base.state->best_encoder =
10567                                 connector->base.encoder;
10568                         connector->base.state->crtc =
10569                                 connector->base.encoder->crtc;
10570
10571                         drm_connector_reference(&connector->base);
10572                 } else {
10573                         connector->base.state->best_encoder = NULL;
10574                         connector->base.state->crtc = NULL;
10575                 }
10576         }
10577         drm_connector_list_iter_end(&conn_iter);
10578 }
10579
10580 static void
10581 connected_sink_compute_bpp(struct intel_connector *connector,
10582                            struct intel_crtc_state *pipe_config)
10583 {
10584         const struct drm_display_info *info = &connector->base.display_info;
10585         int bpp = pipe_config->pipe_bpp;
10586
10587         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10588                       connector->base.base.id,
10589                       connector->base.name);
10590
10591         /* Don't use an invalid EDID bpc value */
10592         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10593                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10594                               bpp, info->bpc * 3);
10595                 pipe_config->pipe_bpp = info->bpc * 3;
10596         }
10597
10598         /* Clamp bpp to 8 on screens without EDID 1.4 */
10599         if (info->bpc == 0 && bpp > 24) {
10600                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10601                               bpp);
10602                 pipe_config->pipe_bpp = 24;
10603         }
10604 }
10605
10606 static int
10607 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10608                           struct intel_crtc_state *pipe_config)
10609 {
10610         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10611         struct drm_atomic_state *state;
10612         struct drm_connector *connector;
10613         struct drm_connector_state *connector_state;
10614         int bpp, i;
10615
10616         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10617             IS_CHERRYVIEW(dev_priv)))
10618                 bpp = 10*3;
10619         else if (INTEL_GEN(dev_priv) >= 5)
10620                 bpp = 12*3;
10621         else
10622                 bpp = 8*3;
10623
10624
10625         pipe_config->pipe_bpp = bpp;
10626
10627         state = pipe_config->base.state;
10628
10629         /* Clamp display bpp to EDID value */
10630         for_each_new_connector_in_state(state, connector, connector_state, i) {
10631                 if (connector_state->crtc != &crtc->base)
10632                         continue;
10633
10634                 connected_sink_compute_bpp(to_intel_connector(connector),
10635                                            pipe_config);
10636         }
10637
10638         return bpp;
10639 }
10640
10641 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10642 {
10643         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10644                         "type: 0x%x flags: 0x%x\n",
10645                 mode->crtc_clock,
10646                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10647                 mode->crtc_hsync_end, mode->crtc_htotal,
10648                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10649                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10650 }
10651
10652 static inline void
10653 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10654                       unsigned int lane_count, struct intel_link_m_n *m_n)
10655 {
10656         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10657                       id, lane_count,
10658                       m_n->gmch_m, m_n->gmch_n,
10659                       m_n->link_m, m_n->link_n, m_n->tu);
10660 }
10661
10662 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10663
10664 static const char * const output_type_str[] = {
10665         OUTPUT_TYPE(UNUSED),
10666         OUTPUT_TYPE(ANALOG),
10667         OUTPUT_TYPE(DVO),
10668         OUTPUT_TYPE(SDVO),
10669         OUTPUT_TYPE(LVDS),
10670         OUTPUT_TYPE(TVOUT),
10671         OUTPUT_TYPE(HDMI),
10672         OUTPUT_TYPE(DP),
10673         OUTPUT_TYPE(EDP),
10674         OUTPUT_TYPE(DSI),
10675         OUTPUT_TYPE(DDI),
10676         OUTPUT_TYPE(DP_MST),
10677 };
10678
10679 #undef OUTPUT_TYPE
10680
10681 static void snprintf_output_types(char *buf, size_t len,
10682                                   unsigned int output_types)
10683 {
10684         char *str = buf;
10685         int i;
10686
10687         str[0] = '\0';
10688
10689         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10690                 int r;
10691
10692                 if ((output_types & BIT(i)) == 0)
10693                         continue;
10694
10695                 r = snprintf(str, len, "%s%s",
10696                              str != buf ? "," : "", output_type_str[i]);
10697                 if (r >= len)
10698                         break;
10699                 str += r;
10700                 len -= r;
10701
10702                 output_types &= ~BIT(i);
10703         }
10704
10705         WARN_ON_ONCE(output_types != 0);
10706 }
10707
10708 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10709                                    struct intel_crtc_state *pipe_config,
10710                                    const char *context)
10711 {
10712         struct drm_device *dev = crtc->base.dev;
10713         struct drm_i915_private *dev_priv = to_i915(dev);
10714         struct drm_plane *plane;
10715         struct intel_plane *intel_plane;
10716         struct intel_plane_state *state;
10717         struct drm_framebuffer *fb;
10718         char buf[64];
10719
10720         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10721                       crtc->base.base.id, crtc->base.name, context);
10722
10723         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10724         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10725                       buf, pipe_config->output_types);
10726
10727         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10728                       transcoder_name(pipe_config->cpu_transcoder),
10729                       pipe_config->pipe_bpp, pipe_config->dither);
10730
10731         if (pipe_config->has_pch_encoder)
10732                 intel_dump_m_n_config(pipe_config, "fdi",
10733                                       pipe_config->fdi_lanes,
10734                                       &pipe_config->fdi_m_n);
10735
10736         if (pipe_config->ycbcr420)
10737                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10738
10739         if (intel_crtc_has_dp_encoder(pipe_config)) {
10740                 intel_dump_m_n_config(pipe_config, "dp m_n",
10741                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10742                 if (pipe_config->has_drrs)
10743                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10744                                               pipe_config->lane_count,
10745                                               &pipe_config->dp_m2_n2);
10746         }
10747
10748         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10749                       pipe_config->has_audio, pipe_config->has_infoframe);
10750
10751         DRM_DEBUG_KMS("requested mode:\n");
10752         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10753         DRM_DEBUG_KMS("adjusted mode:\n");
10754         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10755         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10756         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10757                       pipe_config->port_clock,
10758                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10759                       pipe_config->pixel_rate);
10760
10761         if (INTEL_GEN(dev_priv) >= 9)
10762                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10763                               crtc->num_scalers,
10764                               pipe_config->scaler_state.scaler_users,
10765                               pipe_config->scaler_state.scaler_id);
10766
10767         if (HAS_GMCH_DISPLAY(dev_priv))
10768                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10769                               pipe_config->gmch_pfit.control,
10770                               pipe_config->gmch_pfit.pgm_ratios,
10771                               pipe_config->gmch_pfit.lvds_border_bits);
10772         else
10773                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10774                               pipe_config->pch_pfit.pos,
10775                               pipe_config->pch_pfit.size,
10776                               enableddisabled(pipe_config->pch_pfit.enabled));
10777
10778         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10779                       pipe_config->ips_enabled, pipe_config->double_wide);
10780
10781         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10782
10783         DRM_DEBUG_KMS("planes on this crtc\n");
10784         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10785                 struct drm_format_name_buf format_name;
10786                 intel_plane = to_intel_plane(plane);
10787                 if (intel_plane->pipe != crtc->pipe)
10788                         continue;
10789
10790                 state = to_intel_plane_state(plane->state);
10791                 fb = state->base.fb;
10792                 if (!fb) {
10793                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10794                                       plane->base.id, plane->name, state->scaler_id);
10795                         continue;
10796                 }
10797
10798                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10799                               plane->base.id, plane->name,
10800                               fb->base.id, fb->width, fb->height,
10801                               drm_get_format_name(fb->format->format, &format_name));
10802                 if (INTEL_GEN(dev_priv) >= 9)
10803                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10804                                       state->scaler_id,
10805                                       state->base.src.x1 >> 16,
10806                                       state->base.src.y1 >> 16,
10807                                       drm_rect_width(&state->base.src) >> 16,
10808                                       drm_rect_height(&state->base.src) >> 16,
10809                                       state->base.dst.x1, state->base.dst.y1,
10810                                       drm_rect_width(&state->base.dst),
10811                                       drm_rect_height(&state->base.dst));
10812         }
10813 }
10814
10815 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10816 {
10817         struct drm_device *dev = state->dev;
10818         struct drm_connector *connector;
10819         struct drm_connector_list_iter conn_iter;
10820         unsigned int used_ports = 0;
10821         unsigned int used_mst_ports = 0;
10822         bool ret = true;
10823
10824         /*
10825          * Walk the connector list instead of the encoder
10826          * list to detect the problem on ddi platforms
10827          * where there's just one encoder per digital port.
10828          */
10829         drm_connector_list_iter_begin(dev, &conn_iter);
10830         drm_for_each_connector_iter(connector, &conn_iter) {
10831                 struct drm_connector_state *connector_state;
10832                 struct intel_encoder *encoder;
10833
10834                 connector_state = drm_atomic_get_new_connector_state(state, connector);
10835                 if (!connector_state)
10836                         connector_state = connector->state;
10837
10838                 if (!connector_state->best_encoder)
10839                         continue;
10840
10841                 encoder = to_intel_encoder(connector_state->best_encoder);
10842
10843                 WARN_ON(!connector_state->crtc);
10844
10845                 switch (encoder->type) {
10846                         unsigned int port_mask;
10847                 case INTEL_OUTPUT_DDI:
10848                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
10849                                 break;
10850                 case INTEL_OUTPUT_DP:
10851                 case INTEL_OUTPUT_HDMI:
10852                 case INTEL_OUTPUT_EDP:
10853                         port_mask = 1 << encoder->port;
10854
10855                         /* the same port mustn't appear more than once */
10856                         if (used_ports & port_mask)
10857                                 ret = false;
10858
10859                         used_ports |= port_mask;
10860                         break;
10861                 case INTEL_OUTPUT_DP_MST:
10862                         used_mst_ports |=
10863                                 1 << encoder->port;
10864                         break;
10865                 default:
10866                         break;
10867                 }
10868         }
10869         drm_connector_list_iter_end(&conn_iter);
10870
10871         /* can't mix MST and SST/HDMI on the same port */
10872         if (used_ports & used_mst_ports)
10873                 return false;
10874
10875         return ret;
10876 }
10877
10878 static void
10879 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10880 {
10881         struct drm_i915_private *dev_priv =
10882                 to_i915(crtc_state->base.crtc->dev);
10883         struct intel_crtc_scaler_state scaler_state;
10884         struct intel_dpll_hw_state dpll_hw_state;
10885         struct intel_shared_dpll *shared_dpll;
10886         struct intel_crtc_wm_state wm_state;
10887         bool force_thru, ips_force_disable;
10888
10889         /* FIXME: before the switch to atomic started, a new pipe_config was
10890          * kzalloc'd. Code that depends on any field being zero should be
10891          * fixed, so that the crtc_state can be safely duplicated. For now,
10892          * only fields that are know to not cause problems are preserved. */
10893
10894         scaler_state = crtc_state->scaler_state;
10895         shared_dpll = crtc_state->shared_dpll;
10896         dpll_hw_state = crtc_state->dpll_hw_state;
10897         force_thru = crtc_state->pch_pfit.force_thru;
10898         ips_force_disable = crtc_state->ips_force_disable;
10899         if (IS_G4X(dev_priv) ||
10900             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10901                 wm_state = crtc_state->wm;
10902
10903         /* Keep base drm_crtc_state intact, only clear our extended struct */
10904         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
10905         memset(&crtc_state->base + 1, 0,
10906                sizeof(*crtc_state) - sizeof(crtc_state->base));
10907
10908         crtc_state->scaler_state = scaler_state;
10909         crtc_state->shared_dpll = shared_dpll;
10910         crtc_state->dpll_hw_state = dpll_hw_state;
10911         crtc_state->pch_pfit.force_thru = force_thru;
10912         crtc_state->ips_force_disable = ips_force_disable;
10913         if (IS_G4X(dev_priv) ||
10914             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10915                 crtc_state->wm = wm_state;
10916 }
10917
10918 static int
10919 intel_modeset_pipe_config(struct drm_crtc *crtc,
10920                           struct intel_crtc_state *pipe_config)
10921 {
10922         struct drm_atomic_state *state = pipe_config->base.state;
10923         struct intel_encoder *encoder;
10924         struct drm_connector *connector;
10925         struct drm_connector_state *connector_state;
10926         int base_bpp, ret = -EINVAL;
10927         int i;
10928         bool retry = true;
10929
10930         clear_intel_crtc_state(pipe_config);
10931
10932         pipe_config->cpu_transcoder =
10933                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10934
10935         /*
10936          * Sanitize sync polarity flags based on requested ones. If neither
10937          * positive or negative polarity is requested, treat this as meaning
10938          * negative polarity.
10939          */
10940         if (!(pipe_config->base.adjusted_mode.flags &
10941               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10942                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10943
10944         if (!(pipe_config->base.adjusted_mode.flags &
10945               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10946                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10947
10948         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10949                                              pipe_config);
10950         if (base_bpp < 0)
10951                 goto fail;
10952
10953         /*
10954          * Determine the real pipe dimensions. Note that stereo modes can
10955          * increase the actual pipe size due to the frame doubling and
10956          * insertion of additional space for blanks between the frame. This
10957          * is stored in the crtc timings. We use the requested mode to do this
10958          * computation to clearly distinguish it from the adjusted mode, which
10959          * can be changed by the connectors in the below retry loop.
10960          */
10961         drm_mode_get_hv_timing(&pipe_config->base.mode,
10962                                &pipe_config->pipe_src_w,
10963                                &pipe_config->pipe_src_h);
10964
10965         for_each_new_connector_in_state(state, connector, connector_state, i) {
10966                 if (connector_state->crtc != crtc)
10967                         continue;
10968
10969                 encoder = to_intel_encoder(connector_state->best_encoder);
10970
10971                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
10972                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10973                         goto fail;
10974                 }
10975
10976                 /*
10977                  * Determine output_types before calling the .compute_config()
10978                  * hooks so that the hooks can use this information safely.
10979                  */
10980                 if (encoder->compute_output_type)
10981                         pipe_config->output_types |=
10982                                 BIT(encoder->compute_output_type(encoder, pipe_config,
10983                                                                  connector_state));
10984                 else
10985                         pipe_config->output_types |= BIT(encoder->type);
10986         }
10987
10988 encoder_retry:
10989         /* Ensure the port clock defaults are reset when retrying. */
10990         pipe_config->port_clock = 0;
10991         pipe_config->pixel_multiplier = 1;
10992
10993         /* Fill in default crtc timings, allow encoders to overwrite them. */
10994         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10995                               CRTC_STEREO_DOUBLE);
10996
10997         /* Pass our mode to the connectors and the CRTC to give them a chance to
10998          * adjust it according to limitations or connector properties, and also
10999          * a chance to reject the mode entirely.
11000          */
11001         for_each_new_connector_in_state(state, connector, connector_state, i) {
11002                 if (connector_state->crtc != crtc)
11003                         continue;
11004
11005                 encoder = to_intel_encoder(connector_state->best_encoder);
11006
11007                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11008                         DRM_DEBUG_KMS("Encoder config failure\n");
11009                         goto fail;
11010                 }
11011         }
11012
11013         /* Set default port clock if not overwritten by the encoder. Needs to be
11014          * done afterwards in case the encoder adjusts the mode. */
11015         if (!pipe_config->port_clock)
11016                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11017                         * pipe_config->pixel_multiplier;
11018
11019         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11020         if (ret < 0) {
11021                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11022                 goto fail;
11023         }
11024
11025         if (ret == RETRY) {
11026                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11027                         ret = -EINVAL;
11028                         goto fail;
11029                 }
11030
11031                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11032                 retry = false;
11033                 goto encoder_retry;
11034         }
11035
11036         /* Dithering seems to not pass-through bits correctly when it should, so
11037          * only enable it on 6bpc panels and when its not a compliance
11038          * test requesting 6bpc video pattern.
11039          */
11040         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11041                 !pipe_config->dither_force_disable;
11042         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11043                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11044
11045 fail:
11046         return ret;
11047 }
11048
11049 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11050 {
11051         int diff;
11052
11053         if (clock1 == clock2)
11054                 return true;
11055
11056         if (!clock1 || !clock2)
11057                 return false;
11058
11059         diff = abs(clock1 - clock2);
11060
11061         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11062                 return true;
11063
11064         return false;
11065 }
11066
11067 static bool
11068 intel_compare_m_n(unsigned int m, unsigned int n,
11069                   unsigned int m2, unsigned int n2,
11070                   bool exact)
11071 {
11072         if (m == m2 && n == n2)
11073                 return true;
11074
11075         if (exact || !m || !n || !m2 || !n2)
11076                 return false;
11077
11078         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11079
11080         if (n > n2) {
11081                 while (n > n2) {
11082                         m2 <<= 1;
11083                         n2 <<= 1;
11084                 }
11085         } else if (n < n2) {
11086                 while (n < n2) {
11087                         m <<= 1;
11088                         n <<= 1;
11089                 }
11090         }
11091
11092         if (n != n2)
11093                 return false;
11094
11095         return intel_fuzzy_clock_check(m, m2);
11096 }
11097
11098 static bool
11099 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11100                        struct intel_link_m_n *m2_n2,
11101                        bool adjust)
11102 {
11103         if (m_n->tu == m2_n2->tu &&
11104             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11105                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11106             intel_compare_m_n(m_n->link_m, m_n->link_n,
11107                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11108                 if (adjust)
11109                         *m2_n2 = *m_n;
11110
11111                 return true;
11112         }
11113
11114         return false;
11115 }
11116
11117 static void __printf(3, 4)
11118 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11119 {
11120         struct va_format vaf;
11121         va_list args;
11122
11123         va_start(args, format);
11124         vaf.fmt = format;
11125         vaf.va = &args;
11126
11127         if (adjust)
11128                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11129         else
11130                 drm_err("mismatch in %s %pV", name, &vaf);
11131
11132         va_end(args);
11133 }
11134
11135 static bool
11136 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11137                           struct intel_crtc_state *current_config,
11138                           struct intel_crtc_state *pipe_config,
11139                           bool adjust)
11140 {
11141         bool ret = true;
11142         bool fixup_inherited = adjust &&
11143                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11144                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11145
11146 #define PIPE_CONF_CHECK_X(name) \
11147         if (current_config->name != pipe_config->name) { \
11148                 pipe_config_err(adjust, __stringify(name), \
11149                           "(expected 0x%08x, found 0x%08x)\n", \
11150                           current_config->name, \
11151                           pipe_config->name); \
11152                 ret = false; \
11153         }
11154
11155 #define PIPE_CONF_CHECK_I(name) \
11156         if (current_config->name != pipe_config->name) { \
11157                 pipe_config_err(adjust, __stringify(name), \
11158                           "(expected %i, found %i)\n", \
11159                           current_config->name, \
11160                           pipe_config->name); \
11161                 ret = false; \
11162         }
11163
11164 #define PIPE_CONF_CHECK_BOOL(name)      \
11165         if (current_config->name != pipe_config->name) { \
11166                 pipe_config_err(adjust, __stringify(name), \
11167                           "(expected %s, found %s)\n", \
11168                           yesno(current_config->name), \
11169                           yesno(pipe_config->name)); \
11170                 ret = false; \
11171         }
11172
11173 /*
11174  * Checks state where we only read out the enabling, but not the entire
11175  * state itself (like full infoframes or ELD for audio). These states
11176  * require a full modeset on bootup to fix up.
11177  */
11178 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) \
11179         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11180                 PIPE_CONF_CHECK_BOOL(name); \
11181         } else { \
11182                 pipe_config_err(adjust, __stringify(name), \
11183                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11184                           yesno(current_config->name), \
11185                           yesno(pipe_config->name)); \
11186                 ret = false; \
11187         }
11188
11189 #define PIPE_CONF_CHECK_P(name) \
11190         if (current_config->name != pipe_config->name) { \
11191                 pipe_config_err(adjust, __stringify(name), \
11192                           "(expected %p, found %p)\n", \
11193                           current_config->name, \
11194                           pipe_config->name); \
11195                 ret = false; \
11196         }
11197
11198 #define PIPE_CONF_CHECK_M_N(name) \
11199         if (!intel_compare_link_m_n(&current_config->name, \
11200                                     &pipe_config->name,\
11201                                     adjust)) { \
11202                 pipe_config_err(adjust, __stringify(name), \
11203                           "(expected tu %i gmch %i/%i link %i/%i, " \
11204                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11205                           current_config->name.tu, \
11206                           current_config->name.gmch_m, \
11207                           current_config->name.gmch_n, \
11208                           current_config->name.link_m, \
11209                           current_config->name.link_n, \
11210                           pipe_config->name.tu, \
11211                           pipe_config->name.gmch_m, \
11212                           pipe_config->name.gmch_n, \
11213                           pipe_config->name.link_m, \
11214                           pipe_config->name.link_n); \
11215                 ret = false; \
11216         }
11217
11218 /* This is required for BDW+ where there is only one set of registers for
11219  * switching between high and low RR.
11220  * This macro can be used whenever a comparison has to be made between one
11221  * hw state and multiple sw state variables.
11222  */
11223 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11224         if (!intel_compare_link_m_n(&current_config->name, \
11225                                     &pipe_config->name, adjust) && \
11226             !intel_compare_link_m_n(&current_config->alt_name, \
11227                                     &pipe_config->name, adjust)) { \
11228                 pipe_config_err(adjust, __stringify(name), \
11229                           "(expected tu %i gmch %i/%i link %i/%i, " \
11230                           "or tu %i gmch %i/%i link %i/%i, " \
11231                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11232                           current_config->name.tu, \
11233                           current_config->name.gmch_m, \
11234                           current_config->name.gmch_n, \
11235                           current_config->name.link_m, \
11236                           current_config->name.link_n, \
11237                           current_config->alt_name.tu, \
11238                           current_config->alt_name.gmch_m, \
11239                           current_config->alt_name.gmch_n, \
11240                           current_config->alt_name.link_m, \
11241                           current_config->alt_name.link_n, \
11242                           pipe_config->name.tu, \
11243                           pipe_config->name.gmch_m, \
11244                           pipe_config->name.gmch_n, \
11245                           pipe_config->name.link_m, \
11246                           pipe_config->name.link_n); \
11247                 ret = false; \
11248         }
11249
11250 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11251         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11252                 pipe_config_err(adjust, __stringify(name), \
11253                           "(%x) (expected %i, found %i)\n", \
11254                           (mask), \
11255                           current_config->name & (mask), \
11256                           pipe_config->name & (mask)); \
11257                 ret = false; \
11258         }
11259
11260 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11261         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11262                 pipe_config_err(adjust, __stringify(name), \
11263                           "(expected %i, found %i)\n", \
11264                           current_config->name, \
11265                           pipe_config->name); \
11266                 ret = false; \
11267         }
11268
11269 #define PIPE_CONF_QUIRK(quirk)  \
11270         ((current_config->quirks | pipe_config->quirks) & (quirk))
11271
11272         PIPE_CONF_CHECK_I(cpu_transcoder);
11273
11274         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11275         PIPE_CONF_CHECK_I(fdi_lanes);
11276         PIPE_CONF_CHECK_M_N(fdi_m_n);
11277
11278         PIPE_CONF_CHECK_I(lane_count);
11279         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11280
11281         if (INTEL_GEN(dev_priv) < 8) {
11282                 PIPE_CONF_CHECK_M_N(dp_m_n);
11283
11284                 if (current_config->has_drrs)
11285                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11286         } else
11287                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11288
11289         PIPE_CONF_CHECK_X(output_types);
11290
11291         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11292         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11293         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11294         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11295         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11296         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11297
11298         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11299         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11300         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11301         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11302         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11303         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11304
11305         PIPE_CONF_CHECK_I(pixel_multiplier);
11306         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11307         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11308             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11309                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11310
11311         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11312         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11313         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11314         PIPE_CONF_CHECK_BOOL(ycbcr420);
11315
11316         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11317
11318         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11319                               DRM_MODE_FLAG_INTERLACE);
11320
11321         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11322                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11323                                       DRM_MODE_FLAG_PHSYNC);
11324                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11325                                       DRM_MODE_FLAG_NHSYNC);
11326                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11327                                       DRM_MODE_FLAG_PVSYNC);
11328                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11329                                       DRM_MODE_FLAG_NVSYNC);
11330         }
11331
11332         PIPE_CONF_CHECK_X(gmch_pfit.control);
11333         /* pfit ratios are autocomputed by the hw on gen4+ */
11334         if (INTEL_GEN(dev_priv) < 4)
11335                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11336         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11337
11338         if (!adjust) {
11339                 PIPE_CONF_CHECK_I(pipe_src_w);
11340                 PIPE_CONF_CHECK_I(pipe_src_h);
11341
11342                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11343                 if (current_config->pch_pfit.enabled) {
11344                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11345                         PIPE_CONF_CHECK_X(pch_pfit.size);
11346                 }
11347
11348                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11349                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11350         }
11351
11352         PIPE_CONF_CHECK_BOOL(double_wide);
11353
11354         PIPE_CONF_CHECK_P(shared_dpll);
11355         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11356         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11357         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11358         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11359         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11360         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11361         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11362         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11363         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11364         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11365         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11366         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11367         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11368         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11369         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11370         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11371         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11372         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11373         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11374         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11375         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11376
11377         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11378         PIPE_CONF_CHECK_X(dsi_pll.div);
11379
11380         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11381                 PIPE_CONF_CHECK_I(pipe_bpp);
11382
11383         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11384         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11385
11386         PIPE_CONF_CHECK_I(min_voltage_level);
11387
11388 #undef PIPE_CONF_CHECK_X
11389 #undef PIPE_CONF_CHECK_I
11390 #undef PIPE_CONF_CHECK_BOOL
11391 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11392 #undef PIPE_CONF_CHECK_P
11393 #undef PIPE_CONF_CHECK_FLAGS
11394 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11395 #undef PIPE_CONF_QUIRK
11396
11397         return ret;
11398 }
11399
11400 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11401                                            const struct intel_crtc_state *pipe_config)
11402 {
11403         if (pipe_config->has_pch_encoder) {
11404                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11405                                                             &pipe_config->fdi_m_n);
11406                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11407
11408                 /*
11409                  * FDI already provided one idea for the dotclock.
11410                  * Yell if the encoder disagrees.
11411                  */
11412                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11413                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11414                      fdi_dotclock, dotclock);
11415         }
11416 }
11417
11418 static void verify_wm_state(struct drm_crtc *crtc,
11419                             struct drm_crtc_state *new_state)
11420 {
11421         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11422         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11423         struct skl_pipe_wm hw_wm, *sw_wm;
11424         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11425         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11426         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11427         const enum pipe pipe = intel_crtc->pipe;
11428         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11429
11430         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11431                 return;
11432
11433         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11434         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11435
11436         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11437         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11438
11439         /* planes */
11440         for_each_universal_plane(dev_priv, pipe, plane) {
11441                 hw_plane_wm = &hw_wm.planes[plane];
11442                 sw_plane_wm = &sw_wm->planes[plane];
11443
11444                 /* Watermarks */
11445                 for (level = 0; level <= max_level; level++) {
11446                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11447                                                 &sw_plane_wm->wm[level]))
11448                                 continue;
11449
11450                         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",
11451                                   pipe_name(pipe), plane + 1, level,
11452                                   sw_plane_wm->wm[level].plane_en,
11453                                   sw_plane_wm->wm[level].plane_res_b,
11454                                   sw_plane_wm->wm[level].plane_res_l,
11455                                   hw_plane_wm->wm[level].plane_en,
11456                                   hw_plane_wm->wm[level].plane_res_b,
11457                                   hw_plane_wm->wm[level].plane_res_l);
11458                 }
11459
11460                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11461                                          &sw_plane_wm->trans_wm)) {
11462                         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",
11463                                   pipe_name(pipe), plane + 1,
11464                                   sw_plane_wm->trans_wm.plane_en,
11465                                   sw_plane_wm->trans_wm.plane_res_b,
11466                                   sw_plane_wm->trans_wm.plane_res_l,
11467                                   hw_plane_wm->trans_wm.plane_en,
11468                                   hw_plane_wm->trans_wm.plane_res_b,
11469                                   hw_plane_wm->trans_wm.plane_res_l);
11470                 }
11471
11472                 /* DDB */
11473                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11474                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11475
11476                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11477                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11478                                   pipe_name(pipe), plane + 1,
11479                                   sw_ddb_entry->start, sw_ddb_entry->end,
11480                                   hw_ddb_entry->start, hw_ddb_entry->end);
11481                 }
11482         }
11483
11484         /*
11485          * cursor
11486          * If the cursor plane isn't active, we may not have updated it's ddb
11487          * allocation. In that case since the ddb allocation will be updated
11488          * once the plane becomes visible, we can skip this check
11489          */
11490         if (1) {
11491                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11492                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11493
11494                 /* Watermarks */
11495                 for (level = 0; level <= max_level; level++) {
11496                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11497                                                 &sw_plane_wm->wm[level]))
11498                                 continue;
11499
11500                         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",
11501                                   pipe_name(pipe), level,
11502                                   sw_plane_wm->wm[level].plane_en,
11503                                   sw_plane_wm->wm[level].plane_res_b,
11504                                   sw_plane_wm->wm[level].plane_res_l,
11505                                   hw_plane_wm->wm[level].plane_en,
11506                                   hw_plane_wm->wm[level].plane_res_b,
11507                                   hw_plane_wm->wm[level].plane_res_l);
11508                 }
11509
11510                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11511                                          &sw_plane_wm->trans_wm)) {
11512                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11513                                   pipe_name(pipe),
11514                                   sw_plane_wm->trans_wm.plane_en,
11515                                   sw_plane_wm->trans_wm.plane_res_b,
11516                                   sw_plane_wm->trans_wm.plane_res_l,
11517                                   hw_plane_wm->trans_wm.plane_en,
11518                                   hw_plane_wm->trans_wm.plane_res_b,
11519                                   hw_plane_wm->trans_wm.plane_res_l);
11520                 }
11521
11522                 /* DDB */
11523                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11524                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11525
11526                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11527                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11528                                   pipe_name(pipe),
11529                                   sw_ddb_entry->start, sw_ddb_entry->end,
11530                                   hw_ddb_entry->start, hw_ddb_entry->end);
11531                 }
11532         }
11533 }
11534
11535 static void
11536 verify_connector_state(struct drm_device *dev,
11537                        struct drm_atomic_state *state,
11538                        struct drm_crtc *crtc)
11539 {
11540         struct drm_connector *connector;
11541         struct drm_connector_state *new_conn_state;
11542         int i;
11543
11544         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11545                 struct drm_encoder *encoder = connector->encoder;
11546                 struct drm_crtc_state *crtc_state = NULL;
11547
11548                 if (new_conn_state->crtc != crtc)
11549                         continue;
11550
11551                 if (crtc)
11552                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11553
11554                 intel_connector_verify_state(crtc_state, new_conn_state);
11555
11556                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11557                      "connector's atomic encoder doesn't match legacy encoder\n");
11558         }
11559 }
11560
11561 static void
11562 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11563 {
11564         struct intel_encoder *encoder;
11565         struct drm_connector *connector;
11566         struct drm_connector_state *old_conn_state, *new_conn_state;
11567         int i;
11568
11569         for_each_intel_encoder(dev, encoder) {
11570                 bool enabled = false, found = false;
11571                 enum pipe pipe;
11572
11573                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11574                               encoder->base.base.id,
11575                               encoder->base.name);
11576
11577                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11578                                                    new_conn_state, i) {
11579                         if (old_conn_state->best_encoder == &encoder->base)
11580                                 found = true;
11581
11582                         if (new_conn_state->best_encoder != &encoder->base)
11583                                 continue;
11584                         found = enabled = true;
11585
11586                         I915_STATE_WARN(new_conn_state->crtc !=
11587                                         encoder->base.crtc,
11588                              "connector's crtc doesn't match encoder crtc\n");
11589                 }
11590
11591                 if (!found)
11592                         continue;
11593
11594                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11595                      "encoder's enabled state mismatch "
11596                      "(expected %i, found %i)\n",
11597                      !!encoder->base.crtc, enabled);
11598
11599                 if (!encoder->base.crtc) {
11600                         bool active;
11601
11602                         active = encoder->get_hw_state(encoder, &pipe);
11603                         I915_STATE_WARN(active,
11604                              "encoder detached but still enabled on pipe %c.\n",
11605                              pipe_name(pipe));
11606                 }
11607         }
11608 }
11609
11610 static void
11611 verify_crtc_state(struct drm_crtc *crtc,
11612                   struct drm_crtc_state *old_crtc_state,
11613                   struct drm_crtc_state *new_crtc_state)
11614 {
11615         struct drm_device *dev = crtc->dev;
11616         struct drm_i915_private *dev_priv = to_i915(dev);
11617         struct intel_encoder *encoder;
11618         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11619         struct intel_crtc_state *pipe_config, *sw_config;
11620         struct drm_atomic_state *old_state;
11621         bool active;
11622
11623         old_state = old_crtc_state->state;
11624         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11625         pipe_config = to_intel_crtc_state(old_crtc_state);
11626         memset(pipe_config, 0, sizeof(*pipe_config));
11627         pipe_config->base.crtc = crtc;
11628         pipe_config->base.state = old_state;
11629
11630         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11631
11632         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11633
11634         /* we keep both pipes enabled on 830 */
11635         if (IS_I830(dev_priv))
11636                 active = new_crtc_state->active;
11637
11638         I915_STATE_WARN(new_crtc_state->active != active,
11639              "crtc active state doesn't match with hw state "
11640              "(expected %i, found %i)\n", new_crtc_state->active, active);
11641
11642         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11643              "transitional active state does not match atomic hw state "
11644              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11645
11646         for_each_encoder_on_crtc(dev, crtc, encoder) {
11647                 enum pipe pipe;
11648
11649                 active = encoder->get_hw_state(encoder, &pipe);
11650                 I915_STATE_WARN(active != new_crtc_state->active,
11651                         "[ENCODER:%i] active %i with crtc active %i\n",
11652                         encoder->base.base.id, active, new_crtc_state->active);
11653
11654                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11655                                 "Encoder connected to wrong pipe %c\n",
11656                                 pipe_name(pipe));
11657
11658                 if (active)
11659                         encoder->get_config(encoder, pipe_config);
11660         }
11661
11662         intel_crtc_compute_pixel_rate(pipe_config);
11663
11664         if (!new_crtc_state->active)
11665                 return;
11666
11667         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11668
11669         sw_config = to_intel_crtc_state(new_crtc_state);
11670         if (!intel_pipe_config_compare(dev_priv, sw_config,
11671                                        pipe_config, false)) {
11672                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11673                 intel_dump_pipe_config(intel_crtc, pipe_config,
11674                                        "[hw state]");
11675                 intel_dump_pipe_config(intel_crtc, sw_config,
11676                                        "[sw state]");
11677         }
11678 }
11679
11680 static void
11681 intel_verify_planes(struct intel_atomic_state *state)
11682 {
11683         struct intel_plane *plane;
11684         const struct intel_plane_state *plane_state;
11685         int i;
11686
11687         for_each_new_intel_plane_in_state(state, plane,
11688                                           plane_state, i)
11689                 assert_plane(plane, plane_state->base.visible);
11690 }
11691
11692 static void
11693 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11694                          struct intel_shared_dpll *pll,
11695                          struct drm_crtc *crtc,
11696                          struct drm_crtc_state *new_state)
11697 {
11698         struct intel_dpll_hw_state dpll_hw_state;
11699         unsigned crtc_mask;
11700         bool active;
11701
11702         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11703
11704         DRM_DEBUG_KMS("%s\n", pll->info->name);
11705
11706         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
11707
11708         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
11709                 I915_STATE_WARN(!pll->on && pll->active_mask,
11710                      "pll in active use but not on in sw tracking\n");
11711                 I915_STATE_WARN(pll->on && !pll->active_mask,
11712                      "pll is on but not used by any active crtc\n");
11713                 I915_STATE_WARN(pll->on != active,
11714                      "pll on state mismatch (expected %i, found %i)\n",
11715                      pll->on, active);
11716         }
11717
11718         if (!crtc) {
11719                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11720                                 "more active pll users than references: %x vs %x\n",
11721                                 pll->active_mask, pll->state.crtc_mask);
11722
11723                 return;
11724         }
11725
11726         crtc_mask = 1 << drm_crtc_index(crtc);
11727
11728         if (new_state->active)
11729                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11730                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11731                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11732         else
11733                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11734                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11735                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11736
11737         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11738                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11739                         crtc_mask, pll->state.crtc_mask);
11740
11741         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11742                                           &dpll_hw_state,
11743                                           sizeof(dpll_hw_state)),
11744                         "pll hw state mismatch\n");
11745 }
11746
11747 static void
11748 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11749                          struct drm_crtc_state *old_crtc_state,
11750                          struct drm_crtc_state *new_crtc_state)
11751 {
11752         struct drm_i915_private *dev_priv = to_i915(dev);
11753         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11754         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11755
11756         if (new_state->shared_dpll)
11757                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11758
11759         if (old_state->shared_dpll &&
11760             old_state->shared_dpll != new_state->shared_dpll) {
11761                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
11762                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11763
11764                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11765                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11766                                 pipe_name(drm_crtc_index(crtc)));
11767                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11768                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11769                                 pipe_name(drm_crtc_index(crtc)));
11770         }
11771 }
11772
11773 static void
11774 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11775                           struct drm_atomic_state *state,
11776                           struct drm_crtc_state *old_state,
11777                           struct drm_crtc_state *new_state)
11778 {
11779         if (!needs_modeset(new_state) &&
11780             !to_intel_crtc_state(new_state)->update_pipe)
11781                 return;
11782
11783         verify_wm_state(crtc, new_state);
11784         verify_connector_state(crtc->dev, state, crtc);
11785         verify_crtc_state(crtc, old_state, new_state);
11786         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11787 }
11788
11789 static void
11790 verify_disabled_dpll_state(struct drm_device *dev)
11791 {
11792         struct drm_i915_private *dev_priv = to_i915(dev);
11793         int i;
11794
11795         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11796                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
11797 }
11798
11799 static void
11800 intel_modeset_verify_disabled(struct drm_device *dev,
11801                               struct drm_atomic_state *state)
11802 {
11803         verify_encoder_state(dev, state);
11804         verify_connector_state(dev, state, NULL);
11805         verify_disabled_dpll_state(dev);
11806 }
11807
11808 static void update_scanline_offset(struct intel_crtc *crtc)
11809 {
11810         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11811
11812         /*
11813          * The scanline counter increments at the leading edge of hsync.
11814          *
11815          * On most platforms it starts counting from vtotal-1 on the
11816          * first active line. That means the scanline counter value is
11817          * always one less than what we would expect. Ie. just after
11818          * start of vblank, which also occurs at start of hsync (on the
11819          * last active line), the scanline counter will read vblank_start-1.
11820          *
11821          * On gen2 the scanline counter starts counting from 1 instead
11822          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11823          * to keep the value positive), instead of adding one.
11824          *
11825          * On HSW+ the behaviour of the scanline counter depends on the output
11826          * type. For DP ports it behaves like most other platforms, but on HDMI
11827          * there's an extra 1 line difference. So we need to add two instead of
11828          * one to the value.
11829          *
11830          * On VLV/CHV DSI the scanline counter would appear to increment
11831          * approx. 1/3 of a scanline before start of vblank. Unfortunately
11832          * that means we can't tell whether we're in vblank or not while
11833          * we're on that particular line. We must still set scanline_offset
11834          * to 1 so that the vblank timestamps come out correct when we query
11835          * the scanline counter from within the vblank interrupt handler.
11836          * However if queried just before the start of vblank we'll get an
11837          * answer that's slightly in the future.
11838          */
11839         if (IS_GEN2(dev_priv)) {
11840                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
11841                 int vtotal;
11842
11843                 vtotal = adjusted_mode->crtc_vtotal;
11844                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
11845                         vtotal /= 2;
11846
11847                 crtc->scanline_offset = vtotal - 1;
11848         } else if (HAS_DDI(dev_priv) &&
11849                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
11850                 crtc->scanline_offset = 2;
11851         } else
11852                 crtc->scanline_offset = 1;
11853 }
11854
11855 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
11856 {
11857         struct drm_device *dev = state->dev;
11858         struct drm_i915_private *dev_priv = to_i915(dev);
11859         struct drm_crtc *crtc;
11860         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11861         int i;
11862
11863         if (!dev_priv->display.crtc_compute_clock)
11864                 return;
11865
11866         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11867                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11868                 struct intel_shared_dpll *old_dpll =
11869                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
11870
11871                 if (!needs_modeset(new_crtc_state))
11872                         continue;
11873
11874                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
11875
11876                 if (!old_dpll)
11877                         continue;
11878
11879                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
11880         }
11881 }
11882
11883 /*
11884  * This implements the workaround described in the "notes" section of the mode
11885  * set sequence documentation. When going from no pipes or single pipe to
11886  * multiple pipes, and planes are enabled after the pipe, we need to wait at
11887  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
11888  */
11889 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
11890 {
11891         struct drm_crtc_state *crtc_state;
11892         struct intel_crtc *intel_crtc;
11893         struct drm_crtc *crtc;
11894         struct intel_crtc_state *first_crtc_state = NULL;
11895         struct intel_crtc_state *other_crtc_state = NULL;
11896         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
11897         int i;
11898
11899         /* look at all crtc's that are going to be enabled in during modeset */
11900         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
11901                 intel_crtc = to_intel_crtc(crtc);
11902
11903                 if (!crtc_state->active || !needs_modeset(crtc_state))
11904                         continue;
11905
11906                 if (first_crtc_state) {
11907                         other_crtc_state = to_intel_crtc_state(crtc_state);
11908                         break;
11909                 } else {
11910                         first_crtc_state = to_intel_crtc_state(crtc_state);
11911                         first_pipe = intel_crtc->pipe;
11912                 }
11913         }
11914
11915         /* No workaround needed? */
11916         if (!first_crtc_state)
11917                 return 0;
11918
11919         /* w/a possibly needed, check how many crtc's are already enabled. */
11920         for_each_intel_crtc(state->dev, intel_crtc) {
11921                 struct intel_crtc_state *pipe_config;
11922
11923                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
11924                 if (IS_ERR(pipe_config))
11925                         return PTR_ERR(pipe_config);
11926
11927                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
11928
11929                 if (!pipe_config->base.active ||
11930                     needs_modeset(&pipe_config->base))
11931                         continue;
11932
11933                 /* 2 or more enabled crtcs means no need for w/a */
11934                 if (enabled_pipe != INVALID_PIPE)
11935                         return 0;
11936
11937                 enabled_pipe = intel_crtc->pipe;
11938         }
11939
11940         if (enabled_pipe != INVALID_PIPE)
11941                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
11942         else if (other_crtc_state)
11943                 other_crtc_state->hsw_workaround_pipe = first_pipe;
11944
11945         return 0;
11946 }
11947
11948 static int intel_lock_all_pipes(struct drm_atomic_state *state)
11949 {
11950         struct drm_crtc *crtc;
11951
11952         /* Add all pipes to the state */
11953         for_each_crtc(state->dev, crtc) {
11954                 struct drm_crtc_state *crtc_state;
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
11961         return 0;
11962 }
11963
11964 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
11965 {
11966         struct drm_crtc *crtc;
11967
11968         /*
11969          * Add all pipes to the state, and force
11970          * a modeset on all the active ones.
11971          */
11972         for_each_crtc(state->dev, crtc) {
11973                 struct drm_crtc_state *crtc_state;
11974                 int ret;
11975
11976                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11977                 if (IS_ERR(crtc_state))
11978                         return PTR_ERR(crtc_state);
11979
11980                 if (!crtc_state->active || needs_modeset(crtc_state))
11981                         continue;
11982
11983                 crtc_state->mode_changed = true;
11984
11985                 ret = drm_atomic_add_affected_connectors(state, crtc);
11986                 if (ret)
11987                         return ret;
11988
11989                 ret = drm_atomic_add_affected_planes(state, crtc);
11990                 if (ret)
11991                         return ret;
11992         }
11993
11994         return 0;
11995 }
11996
11997 static int intel_modeset_checks(struct drm_atomic_state *state)
11998 {
11999         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12000         struct drm_i915_private *dev_priv = to_i915(state->dev);
12001         struct drm_crtc *crtc;
12002         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12003         int ret = 0, i;
12004
12005         if (!check_digital_port_conflicts(state)) {
12006                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12007                 return -EINVAL;
12008         }
12009
12010         intel_state->modeset = true;
12011         intel_state->active_crtcs = dev_priv->active_crtcs;
12012         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12013         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12014
12015         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12016                 if (new_crtc_state->active)
12017                         intel_state->active_crtcs |= 1 << i;
12018                 else
12019                         intel_state->active_crtcs &= ~(1 << i);
12020
12021                 if (old_crtc_state->active != new_crtc_state->active)
12022                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12023         }
12024
12025         /*
12026          * See if the config requires any additional preparation, e.g.
12027          * to adjust global state with pipes off.  We need to do this
12028          * here so we can get the modeset_pipe updated config for the new
12029          * mode set on this crtc.  For other crtcs we need to use the
12030          * adjusted_mode bits in the crtc directly.
12031          */
12032         if (dev_priv->display.modeset_calc_cdclk) {
12033                 ret = dev_priv->display.modeset_calc_cdclk(state);
12034                 if (ret < 0)
12035                         return ret;
12036
12037                 /*
12038                  * Writes to dev_priv->cdclk.logical must protected by
12039                  * holding all the crtc locks, even if we don't end up
12040                  * touching the hardware
12041                  */
12042                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12043                                         &intel_state->cdclk.logical)) {
12044                         ret = intel_lock_all_pipes(state);
12045                         if (ret < 0)
12046                                 return ret;
12047                 }
12048
12049                 /* All pipes must be switched off while we change the cdclk. */
12050                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12051                                               &intel_state->cdclk.actual)) {
12052                         ret = intel_modeset_all_pipes(state);
12053                         if (ret < 0)
12054                                 return ret;
12055                 }
12056
12057                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12058                               intel_state->cdclk.logical.cdclk,
12059                               intel_state->cdclk.actual.cdclk);
12060                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12061                               intel_state->cdclk.logical.voltage_level,
12062                               intel_state->cdclk.actual.voltage_level);
12063         } else {
12064                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12065         }
12066
12067         intel_modeset_clear_plls(state);
12068
12069         if (IS_HASWELL(dev_priv))
12070                 return haswell_mode_set_planes_workaround(state);
12071
12072         return 0;
12073 }
12074
12075 /*
12076  * Handle calculation of various watermark data at the end of the atomic check
12077  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12078  * handlers to ensure that all derived state has been updated.
12079  */
12080 static int calc_watermark_data(struct drm_atomic_state *state)
12081 {
12082         struct drm_device *dev = state->dev;
12083         struct drm_i915_private *dev_priv = to_i915(dev);
12084
12085         /* Is there platform-specific watermark information to calculate? */
12086         if (dev_priv->display.compute_global_watermarks)
12087                 return dev_priv->display.compute_global_watermarks(state);
12088
12089         return 0;
12090 }
12091
12092 /**
12093  * intel_atomic_check - validate state object
12094  * @dev: drm device
12095  * @state: state to validate
12096  */
12097 static int intel_atomic_check(struct drm_device *dev,
12098                               struct drm_atomic_state *state)
12099 {
12100         struct drm_i915_private *dev_priv = to_i915(dev);
12101         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12102         struct drm_crtc *crtc;
12103         struct drm_crtc_state *old_crtc_state, *crtc_state;
12104         int ret, i;
12105         bool any_ms = false;
12106
12107         /* Catch I915_MODE_FLAG_INHERITED */
12108         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12109                                       crtc_state, i) {
12110                 if (crtc_state->mode.private_flags !=
12111                     old_crtc_state->mode.private_flags)
12112                         crtc_state->mode_changed = true;
12113         }
12114
12115         ret = drm_atomic_helper_check_modeset(dev, state);
12116         if (ret)
12117                 return ret;
12118
12119         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12120                 struct intel_crtc_state *pipe_config =
12121                         to_intel_crtc_state(crtc_state);
12122
12123                 if (!needs_modeset(crtc_state))
12124                         continue;
12125
12126                 if (!crtc_state->enable) {
12127                         any_ms = true;
12128                         continue;
12129                 }
12130
12131                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12132                 if (ret) {
12133                         intel_dump_pipe_config(to_intel_crtc(crtc),
12134                                                pipe_config, "[failed]");
12135                         return ret;
12136                 }
12137
12138                 if (i915_modparams.fastboot &&
12139                     intel_pipe_config_compare(dev_priv,
12140                                         to_intel_crtc_state(old_crtc_state),
12141                                         pipe_config, true)) {
12142                         crtc_state->mode_changed = false;
12143                         pipe_config->update_pipe = true;
12144                 }
12145
12146                 if (needs_modeset(crtc_state))
12147                         any_ms = true;
12148
12149                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12150                                        needs_modeset(crtc_state) ?
12151                                        "[modeset]" : "[fastset]");
12152         }
12153
12154         if (any_ms) {
12155                 ret = intel_modeset_checks(state);
12156
12157                 if (ret)
12158                         return ret;
12159         } else {
12160                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12161         }
12162
12163         ret = drm_atomic_helper_check_planes(dev, state);
12164         if (ret)
12165                 return ret;
12166
12167         intel_fbc_choose_crtc(dev_priv, intel_state);
12168         return calc_watermark_data(state);
12169 }
12170
12171 static int intel_atomic_prepare_commit(struct drm_device *dev,
12172                                        struct drm_atomic_state *state)
12173 {
12174         return drm_atomic_helper_prepare_planes(dev, state);
12175 }
12176
12177 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12178 {
12179         struct drm_device *dev = crtc->base.dev;
12180
12181         if (!dev->max_vblank_count)
12182                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12183
12184         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12185 }
12186
12187 static void intel_update_crtc(struct drm_crtc *crtc,
12188                               struct drm_atomic_state *state,
12189                               struct drm_crtc_state *old_crtc_state,
12190                               struct drm_crtc_state *new_crtc_state)
12191 {
12192         struct drm_device *dev = crtc->dev;
12193         struct drm_i915_private *dev_priv = to_i915(dev);
12194         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12195         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12196         bool modeset = needs_modeset(new_crtc_state);
12197         struct intel_plane_state *new_plane_state =
12198                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12199                                                  to_intel_plane(crtc->primary));
12200
12201         if (modeset) {
12202                 update_scanline_offset(intel_crtc);
12203                 dev_priv->display.crtc_enable(pipe_config, state);
12204
12205                 /* vblanks work again, re-enable pipe CRC. */
12206                 intel_crtc_enable_pipe_crc(intel_crtc);
12207         } else {
12208                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12209                                        pipe_config);
12210         }
12211
12212         if (new_plane_state)
12213                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12214
12215         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12216 }
12217
12218 static void intel_update_crtcs(struct drm_atomic_state *state)
12219 {
12220         struct drm_crtc *crtc;
12221         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12222         int i;
12223
12224         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12225                 if (!new_crtc_state->active)
12226                         continue;
12227
12228                 intel_update_crtc(crtc, state, old_crtc_state,
12229                                   new_crtc_state);
12230         }
12231 }
12232
12233 static void skl_update_crtcs(struct drm_atomic_state *state)
12234 {
12235         struct drm_i915_private *dev_priv = to_i915(state->dev);
12236         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12237         struct drm_crtc *crtc;
12238         struct intel_crtc *intel_crtc;
12239         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12240         struct intel_crtc_state *cstate;
12241         unsigned int updated = 0;
12242         bool progress;
12243         enum pipe pipe;
12244         int i;
12245
12246         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12247
12248         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12249                 /* ignore allocations for crtc's that have been turned off. */
12250                 if (new_crtc_state->active)
12251                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12252
12253         /*
12254          * Whenever the number of active pipes changes, we need to make sure we
12255          * update the pipes in the right order so that their ddb allocations
12256          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12257          * cause pipe underruns and other bad stuff.
12258          */
12259         do {
12260                 progress = false;
12261
12262                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12263                         bool vbl_wait = false;
12264                         unsigned int cmask = drm_crtc_mask(crtc);
12265
12266                         intel_crtc = to_intel_crtc(crtc);
12267                         cstate = to_intel_crtc_state(new_crtc_state);
12268                         pipe = intel_crtc->pipe;
12269
12270                         if (updated & cmask || !cstate->base.active)
12271                                 continue;
12272
12273                         if (skl_ddb_allocation_overlaps(dev_priv,
12274                                                         entries,
12275                                                         &cstate->wm.skl.ddb,
12276                                                         i))
12277                                 continue;
12278
12279                         updated |= cmask;
12280                         entries[i] = &cstate->wm.skl.ddb;
12281
12282                         /*
12283                          * If this is an already active pipe, it's DDB changed,
12284                          * and this isn't the last pipe that needs updating
12285                          * then we need to wait for a vblank to pass for the
12286                          * new ddb allocation to take effect.
12287                          */
12288                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12289                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12290                             !new_crtc_state->active_changed &&
12291                             intel_state->wm_results.dirty_pipes != updated)
12292                                 vbl_wait = true;
12293
12294                         intel_update_crtc(crtc, state, old_crtc_state,
12295                                           new_crtc_state);
12296
12297                         if (vbl_wait)
12298                                 intel_wait_for_vblank(dev_priv, pipe);
12299
12300                         progress = true;
12301                 }
12302         } while (progress);
12303 }
12304
12305 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12306 {
12307         struct intel_atomic_state *state, *next;
12308         struct llist_node *freed;
12309
12310         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12311         llist_for_each_entry_safe(state, next, freed, freed)
12312                 drm_atomic_state_put(&state->base);
12313 }
12314
12315 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12316 {
12317         struct drm_i915_private *dev_priv =
12318                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12319
12320         intel_atomic_helper_free_state(dev_priv);
12321 }
12322
12323 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12324 {
12325         struct wait_queue_entry wait_fence, wait_reset;
12326         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12327
12328         init_wait_entry(&wait_fence, 0);
12329         init_wait_entry(&wait_reset, 0);
12330         for (;;) {
12331                 prepare_to_wait(&intel_state->commit_ready.wait,
12332                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12333                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12334                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12335
12336
12337                 if (i915_sw_fence_done(&intel_state->commit_ready)
12338                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12339                         break;
12340
12341                 schedule();
12342         }
12343         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12344         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12345 }
12346
12347 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12348 {
12349         struct drm_device *dev = state->dev;
12350         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12351         struct drm_i915_private *dev_priv = to_i915(dev);
12352         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12353         struct drm_crtc *crtc;
12354         struct intel_crtc_state *intel_cstate;
12355         u64 put_domains[I915_MAX_PIPES] = {};
12356         int i;
12357
12358         intel_atomic_commit_fence_wait(intel_state);
12359
12360         drm_atomic_helper_wait_for_dependencies(state);
12361
12362         if (intel_state->modeset)
12363                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12364
12365         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12366                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12367
12368                 if (needs_modeset(new_crtc_state) ||
12369                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12370
12371                         put_domains[to_intel_crtc(crtc)->pipe] =
12372                                 modeset_get_crtc_power_domains(crtc,
12373                                         to_intel_crtc_state(new_crtc_state));
12374                 }
12375
12376                 if (!needs_modeset(new_crtc_state))
12377                         continue;
12378
12379                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12380                                        to_intel_crtc_state(new_crtc_state));
12381
12382                 if (old_crtc_state->active) {
12383                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12384
12385                         /*
12386                          * We need to disable pipe CRC before disabling the pipe,
12387                          * or we race against vblank off.
12388                          */
12389                         intel_crtc_disable_pipe_crc(intel_crtc);
12390
12391                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12392                         intel_crtc->active = false;
12393                         intel_fbc_disable(intel_crtc);
12394                         intel_disable_shared_dpll(intel_crtc);
12395
12396                         /*
12397                          * Underruns don't always raise
12398                          * interrupts, so check manually.
12399                          */
12400                         intel_check_cpu_fifo_underruns(dev_priv);
12401                         intel_check_pch_fifo_underruns(dev_priv);
12402
12403                         if (!new_crtc_state->active) {
12404                                 /*
12405                                  * Make sure we don't call initial_watermarks
12406                                  * for ILK-style watermark updates.
12407                                  *
12408                                  * No clue what this is supposed to achieve.
12409                                  */
12410                                 if (INTEL_GEN(dev_priv) >= 9)
12411                                         dev_priv->display.initial_watermarks(intel_state,
12412                                                                              to_intel_crtc_state(new_crtc_state));
12413                         }
12414                 }
12415         }
12416
12417         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12418         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12419                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12420
12421         if (intel_state->modeset) {
12422                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12423
12424                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12425
12426                 /*
12427                  * SKL workaround: bspec recommends we disable the SAGV when we
12428                  * have more then one pipe enabled
12429                  */
12430                 if (!intel_can_enable_sagv(state))
12431                         intel_disable_sagv(dev_priv);
12432
12433                 intel_modeset_verify_disabled(dev, state);
12434         }
12435
12436         /* Complete the events for pipes that have now been disabled */
12437         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12438                 bool modeset = needs_modeset(new_crtc_state);
12439
12440                 /* Complete events for now disable pipes here. */
12441                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12442                         spin_lock_irq(&dev->event_lock);
12443                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12444                         spin_unlock_irq(&dev->event_lock);
12445
12446                         new_crtc_state->event = NULL;
12447                 }
12448         }
12449
12450         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12451         dev_priv->display.update_crtcs(state);
12452
12453         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12454          * already, but still need the state for the delayed optimization. To
12455          * fix this:
12456          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12457          * - schedule that vblank worker _before_ calling hw_done
12458          * - at the start of commit_tail, cancel it _synchrously
12459          * - switch over to the vblank wait helper in the core after that since
12460          *   we don't need out special handling any more.
12461          */
12462         drm_atomic_helper_wait_for_flip_done(dev, state);
12463
12464         /*
12465          * Now that the vblank has passed, we can go ahead and program the
12466          * optimal watermarks on platforms that need two-step watermark
12467          * programming.
12468          *
12469          * TODO: Move this (and other cleanup) to an async worker eventually.
12470          */
12471         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12472                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12473
12474                 if (dev_priv->display.optimize_watermarks)
12475                         dev_priv->display.optimize_watermarks(intel_state,
12476                                                               intel_cstate);
12477         }
12478
12479         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12480                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12481
12482                 if (put_domains[i])
12483                         modeset_put_power_domains(dev_priv, put_domains[i]);
12484
12485                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12486         }
12487
12488         if (intel_state->modeset)
12489                 intel_verify_planes(intel_state);
12490
12491         if (intel_state->modeset && intel_can_enable_sagv(state))
12492                 intel_enable_sagv(dev_priv);
12493
12494         drm_atomic_helper_commit_hw_done(state);
12495
12496         if (intel_state->modeset) {
12497                 /* As one of the primary mmio accessors, KMS has a high
12498                  * likelihood of triggering bugs in unclaimed access. After we
12499                  * finish modesetting, see if an error has been flagged, and if
12500                  * so enable debugging for the next modeset - and hope we catch
12501                  * the culprit.
12502                  */
12503                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12504                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12505         }
12506
12507         drm_atomic_helper_cleanup_planes(dev, state);
12508
12509         drm_atomic_helper_commit_cleanup_done(state);
12510
12511         drm_atomic_state_put(state);
12512
12513         intel_atomic_helper_free_state(dev_priv);
12514 }
12515
12516 static void intel_atomic_commit_work(struct work_struct *work)
12517 {
12518         struct drm_atomic_state *state =
12519                 container_of(work, struct drm_atomic_state, commit_work);
12520
12521         intel_atomic_commit_tail(state);
12522 }
12523
12524 static int __i915_sw_fence_call
12525 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12526                           enum i915_sw_fence_notify notify)
12527 {
12528         struct intel_atomic_state *state =
12529                 container_of(fence, struct intel_atomic_state, commit_ready);
12530
12531         switch (notify) {
12532         case FENCE_COMPLETE:
12533                 /* we do blocking waits in the worker, nothing to do here */
12534                 break;
12535         case FENCE_FREE:
12536                 {
12537                         struct intel_atomic_helper *helper =
12538                                 &to_i915(state->base.dev)->atomic_helper;
12539
12540                         if (llist_add(&state->freed, &helper->free_list))
12541                                 schedule_work(&helper->free_work);
12542                         break;
12543                 }
12544         }
12545
12546         return NOTIFY_DONE;
12547 }
12548
12549 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12550 {
12551         struct drm_plane_state *old_plane_state, *new_plane_state;
12552         struct drm_plane *plane;
12553         int i;
12554
12555         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12556                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12557                                   intel_fb_obj(new_plane_state->fb),
12558                                   to_intel_plane(plane)->frontbuffer_bit);
12559 }
12560
12561 /**
12562  * intel_atomic_commit - commit validated state object
12563  * @dev: DRM device
12564  * @state: the top-level driver state object
12565  * @nonblock: nonblocking commit
12566  *
12567  * This function commits a top-level state object that has been validated
12568  * with drm_atomic_helper_check().
12569  *
12570  * RETURNS
12571  * Zero for success or -errno.
12572  */
12573 static int intel_atomic_commit(struct drm_device *dev,
12574                                struct drm_atomic_state *state,
12575                                bool nonblock)
12576 {
12577         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12578         struct drm_i915_private *dev_priv = to_i915(dev);
12579         int ret = 0;
12580
12581         drm_atomic_state_get(state);
12582         i915_sw_fence_init(&intel_state->commit_ready,
12583                            intel_atomic_commit_ready);
12584
12585         /*
12586          * The intel_legacy_cursor_update() fast path takes care
12587          * of avoiding the vblank waits for simple cursor
12588          * movement and flips. For cursor on/off and size changes,
12589          * we want to perform the vblank waits so that watermark
12590          * updates happen during the correct frames. Gen9+ have
12591          * double buffered watermarks and so shouldn't need this.
12592          *
12593          * Unset state->legacy_cursor_update before the call to
12594          * drm_atomic_helper_setup_commit() because otherwise
12595          * drm_atomic_helper_wait_for_flip_done() is a noop and
12596          * we get FIFO underruns because we didn't wait
12597          * for vblank.
12598          *
12599          * FIXME doing watermarks and fb cleanup from a vblank worker
12600          * (assuming we had any) would solve these problems.
12601          */
12602         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12603                 struct intel_crtc_state *new_crtc_state;
12604                 struct intel_crtc *crtc;
12605                 int i;
12606
12607                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12608                         if (new_crtc_state->wm.need_postvbl_update ||
12609                             new_crtc_state->update_wm_post)
12610                                 state->legacy_cursor_update = false;
12611         }
12612
12613         ret = intel_atomic_prepare_commit(dev, state);
12614         if (ret) {
12615                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12616                 i915_sw_fence_commit(&intel_state->commit_ready);
12617                 return ret;
12618         }
12619
12620         ret = drm_atomic_helper_setup_commit(state, nonblock);
12621         if (!ret)
12622                 ret = drm_atomic_helper_swap_state(state, true);
12623
12624         if (ret) {
12625                 i915_sw_fence_commit(&intel_state->commit_ready);
12626
12627                 drm_atomic_helper_cleanup_planes(dev, state);
12628                 return ret;
12629         }
12630         dev_priv->wm.distrust_bios_wm = false;
12631         intel_shared_dpll_swap_state(state);
12632         intel_atomic_track_fbs(state);
12633
12634         if (intel_state->modeset) {
12635                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12636                        sizeof(intel_state->min_cdclk));
12637                 memcpy(dev_priv->min_voltage_level,
12638                        intel_state->min_voltage_level,
12639                        sizeof(intel_state->min_voltage_level));
12640                 dev_priv->active_crtcs = intel_state->active_crtcs;
12641                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12642                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12643         }
12644
12645         drm_atomic_state_get(state);
12646         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12647
12648         i915_sw_fence_commit(&intel_state->commit_ready);
12649         if (nonblock && intel_state->modeset) {
12650                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12651         } else if (nonblock) {
12652                 queue_work(system_unbound_wq, &state->commit_work);
12653         } else {
12654                 if (intel_state->modeset)
12655                         flush_workqueue(dev_priv->modeset_wq);
12656                 intel_atomic_commit_tail(state);
12657         }
12658
12659         return 0;
12660 }
12661
12662 static const struct drm_crtc_funcs intel_crtc_funcs = {
12663         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12664         .set_config = drm_atomic_helper_set_config,
12665         .destroy = intel_crtc_destroy,
12666         .page_flip = drm_atomic_helper_page_flip,
12667         .atomic_duplicate_state = intel_crtc_duplicate_state,
12668         .atomic_destroy_state = intel_crtc_destroy_state,
12669         .set_crc_source = intel_crtc_set_crc_source,
12670 };
12671
12672 struct wait_rps_boost {
12673         struct wait_queue_entry wait;
12674
12675         struct drm_crtc *crtc;
12676         struct i915_request *request;
12677 };
12678
12679 static int do_rps_boost(struct wait_queue_entry *_wait,
12680                         unsigned mode, int sync, void *key)
12681 {
12682         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12683         struct i915_request *rq = wait->request;
12684
12685         /*
12686          * If we missed the vblank, but the request is already running it
12687          * is reasonable to assume that it will complete before the next
12688          * vblank without our intervention, so leave RPS alone.
12689          */
12690         if (!i915_request_started(rq))
12691                 gen6_rps_boost(rq, NULL);
12692         i915_request_put(rq);
12693
12694         drm_crtc_vblank_put(wait->crtc);
12695
12696         list_del(&wait->wait.entry);
12697         kfree(wait);
12698         return 1;
12699 }
12700
12701 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12702                                        struct dma_fence *fence)
12703 {
12704         struct wait_rps_boost *wait;
12705
12706         if (!dma_fence_is_i915(fence))
12707                 return;
12708
12709         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12710                 return;
12711
12712         if (drm_crtc_vblank_get(crtc))
12713                 return;
12714
12715         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12716         if (!wait) {
12717                 drm_crtc_vblank_put(crtc);
12718                 return;
12719         }
12720
12721         wait->request = to_request(dma_fence_get(fence));
12722         wait->crtc = crtc;
12723
12724         wait->wait.func = do_rps_boost;
12725         wait->wait.flags = 0;
12726
12727         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12728 }
12729
12730 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
12731 {
12732         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
12733         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12734         struct drm_framebuffer *fb = plane_state->base.fb;
12735         struct i915_vma *vma;
12736
12737         if (plane->id == PLANE_CURSOR &&
12738             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12739                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12740                 const int align = intel_cursor_alignment(dev_priv);
12741
12742                 return i915_gem_object_attach_phys(obj, align);
12743         }
12744
12745         vma = intel_pin_and_fence_fb_obj(fb,
12746                                          plane_state->base.rotation,
12747                                          intel_plane_uses_fence(plane_state),
12748                                          &plane_state->flags);
12749         if (IS_ERR(vma))
12750                 return PTR_ERR(vma);
12751
12752         plane_state->vma = vma;
12753
12754         return 0;
12755 }
12756
12757 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
12758 {
12759         struct i915_vma *vma;
12760
12761         vma = fetch_and_zero(&old_plane_state->vma);
12762         if (vma)
12763                 intel_unpin_fb_vma(vma, old_plane_state->flags);
12764 }
12765
12766 /**
12767  * intel_prepare_plane_fb - Prepare fb for usage on plane
12768  * @plane: drm plane to prepare for
12769  * @new_state: the plane state being prepared
12770  *
12771  * Prepares a framebuffer for usage on a display plane.  Generally this
12772  * involves pinning the underlying object and updating the frontbuffer tracking
12773  * bits.  Some older platforms need special physical address handling for
12774  * cursor planes.
12775  *
12776  * Must be called with struct_mutex held.
12777  *
12778  * Returns 0 on success, negative error code on failure.
12779  */
12780 int
12781 intel_prepare_plane_fb(struct drm_plane *plane,
12782                        struct drm_plane_state *new_state)
12783 {
12784         struct intel_atomic_state *intel_state =
12785                 to_intel_atomic_state(new_state->state);
12786         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12787         struct drm_framebuffer *fb = new_state->fb;
12788         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12789         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
12790         int ret;
12791
12792         if (old_obj) {
12793                 struct drm_crtc_state *crtc_state =
12794                         drm_atomic_get_new_crtc_state(new_state->state,
12795                                                       plane->state->crtc);
12796
12797                 /* Big Hammer, we also need to ensure that any pending
12798                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
12799                  * current scanout is retired before unpinning the old
12800                  * framebuffer. Note that we rely on userspace rendering
12801                  * into the buffer attached to the pipe they are waiting
12802                  * on. If not, userspace generates a GPU hang with IPEHR
12803                  * point to the MI_WAIT_FOR_EVENT.
12804                  *
12805                  * This should only fail upon a hung GPU, in which case we
12806                  * can safely continue.
12807                  */
12808                 if (needs_modeset(crtc_state)) {
12809                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12810                                                               old_obj->resv, NULL,
12811                                                               false, 0,
12812                                                               GFP_KERNEL);
12813                         if (ret < 0)
12814                                 return ret;
12815                 }
12816         }
12817
12818         if (new_state->fence) { /* explicit fencing */
12819                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
12820                                                     new_state->fence,
12821                                                     I915_FENCE_TIMEOUT,
12822                                                     GFP_KERNEL);
12823                 if (ret < 0)
12824                         return ret;
12825         }
12826
12827         if (!obj)
12828                 return 0;
12829
12830         ret = i915_gem_object_pin_pages(obj);
12831         if (ret)
12832                 return ret;
12833
12834         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
12835         if (ret) {
12836                 i915_gem_object_unpin_pages(obj);
12837                 return ret;
12838         }
12839
12840         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
12841
12842         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12843
12844         mutex_unlock(&dev_priv->drm.struct_mutex);
12845         i915_gem_object_unpin_pages(obj);
12846         if (ret)
12847                 return ret;
12848
12849         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
12850
12851         if (!new_state->fence) { /* implicit fencing */
12852                 struct dma_fence *fence;
12853
12854                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12855                                                       obj->resv, NULL,
12856                                                       false, I915_FENCE_TIMEOUT,
12857                                                       GFP_KERNEL);
12858                 if (ret < 0)
12859                         return ret;
12860
12861                 fence = reservation_object_get_excl_rcu(obj->resv);
12862                 if (fence) {
12863                         add_rps_boost_after_vblank(new_state->crtc, fence);
12864                         dma_fence_put(fence);
12865                 }
12866         } else {
12867                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
12868         }
12869
12870         return 0;
12871 }
12872
12873 /**
12874  * intel_cleanup_plane_fb - Cleans up an fb after plane use
12875  * @plane: drm plane to clean up for
12876  * @old_state: the state from the previous modeset
12877  *
12878  * Cleans up a framebuffer that has just been removed from a plane.
12879  *
12880  * Must be called with struct_mutex held.
12881  */
12882 void
12883 intel_cleanup_plane_fb(struct drm_plane *plane,
12884                        struct drm_plane_state *old_state)
12885 {
12886         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12887
12888         /* Should only be called after a successful intel_prepare_plane_fb()! */
12889         mutex_lock(&dev_priv->drm.struct_mutex);
12890         intel_plane_unpin_fb(to_intel_plane_state(old_state));
12891         mutex_unlock(&dev_priv->drm.struct_mutex);
12892 }
12893
12894 int
12895 skl_max_scale(struct intel_crtc *intel_crtc,
12896               struct intel_crtc_state *crtc_state,
12897               uint32_t pixel_format)
12898 {
12899         struct drm_i915_private *dev_priv;
12900         int max_scale, mult;
12901         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
12902
12903         if (!intel_crtc || !crtc_state->base.enable)
12904                 return DRM_PLANE_HELPER_NO_SCALING;
12905
12906         dev_priv = to_i915(intel_crtc->base.dev);
12907
12908         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
12909         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
12910
12911         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
12912                 max_dotclk *= 2;
12913
12914         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
12915                 return DRM_PLANE_HELPER_NO_SCALING;
12916
12917         /*
12918          * skl max scale is lower of:
12919          *    close to 3 but not 3, -1 is for that purpose
12920          *            or
12921          *    cdclk/crtc_clock
12922          */
12923         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
12924         tmpclk1 = (1 << 16) * mult - 1;
12925         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
12926         max_scale = min(tmpclk1, tmpclk2);
12927
12928         return max_scale;
12929 }
12930
12931 static int
12932 intel_check_primary_plane(struct intel_plane *plane,
12933                           struct intel_crtc_state *crtc_state,
12934                           struct intel_plane_state *state)
12935 {
12936         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12937         struct drm_crtc *crtc = state->base.crtc;
12938         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
12939         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
12940         bool can_position = false;
12941         int ret;
12942         uint32_t pixel_format = 0;
12943
12944         if (INTEL_GEN(dev_priv) >= 9) {
12945                 /* use scaler when colorkey is not required */
12946                 if (!state->ckey.flags) {
12947                         min_scale = 1;
12948                         if (state->base.fb)
12949                                 pixel_format = state->base.fb->format->format;
12950                         max_scale = skl_max_scale(to_intel_crtc(crtc),
12951                                                   crtc_state, pixel_format);
12952                 }
12953                 can_position = true;
12954         }
12955
12956         ret = drm_atomic_helper_check_plane_state(&state->base,
12957                                                   &crtc_state->base,
12958                                                   min_scale, max_scale,
12959                                                   can_position, true);
12960         if (ret)
12961                 return ret;
12962
12963         if (!state->base.fb)
12964                 return 0;
12965
12966         if (INTEL_GEN(dev_priv) >= 9) {
12967                 ret = skl_check_plane_surface(crtc_state, state);
12968                 if (ret)
12969                         return ret;
12970
12971                 state->ctl = skl_plane_ctl(crtc_state, state);
12972         } else {
12973                 ret = i9xx_check_plane_surface(state);
12974                 if (ret)
12975                         return ret;
12976
12977                 state->ctl = i9xx_plane_ctl(crtc_state, state);
12978         }
12979
12980         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
12981                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
12982
12983         return 0;
12984 }
12985
12986 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
12987                                     struct drm_crtc_state *old_crtc_state)
12988 {
12989         struct drm_device *dev = crtc->dev;
12990         struct drm_i915_private *dev_priv = to_i915(dev);
12991         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12992         struct intel_crtc_state *old_intel_cstate =
12993                 to_intel_crtc_state(old_crtc_state);
12994         struct intel_atomic_state *old_intel_state =
12995                 to_intel_atomic_state(old_crtc_state->state);
12996         struct intel_crtc_state *intel_cstate =
12997                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12998         bool modeset = needs_modeset(&intel_cstate->base);
12999
13000         if (!modeset &&
13001             (intel_cstate->base.color_mgmt_changed ||
13002              intel_cstate->update_pipe)) {
13003                 intel_color_set_csc(&intel_cstate->base);
13004                 intel_color_load_luts(&intel_cstate->base);
13005         }
13006
13007         /* Perform vblank evasion around commit operation */
13008         intel_pipe_update_start(intel_cstate);
13009
13010         if (modeset)
13011                 goto out;
13012
13013         if (intel_cstate->update_pipe)
13014                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13015         else if (INTEL_GEN(dev_priv) >= 9)
13016                 skl_detach_scalers(intel_crtc);
13017
13018 out:
13019         if (dev_priv->display.atomic_update_watermarks)
13020                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13021                                                            intel_cstate);
13022 }
13023
13024 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13025                                   struct intel_crtc_state *crtc_state)
13026 {
13027         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13028
13029         if (!IS_GEN2(dev_priv))
13030                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13031
13032         if (crtc_state->has_pch_encoder) {
13033                 enum pipe pch_transcoder =
13034                         intel_crtc_pch_transcoder(crtc);
13035
13036                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13037         }
13038 }
13039
13040 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13041                                      struct drm_crtc_state *old_crtc_state)
13042 {
13043         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13044         struct intel_atomic_state *old_intel_state =
13045                 to_intel_atomic_state(old_crtc_state->state);
13046         struct intel_crtc_state *new_crtc_state =
13047                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13048
13049         intel_pipe_update_end(new_crtc_state);
13050
13051         if (new_crtc_state->update_pipe &&
13052             !needs_modeset(&new_crtc_state->base) &&
13053             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13054                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13055 }
13056
13057 /**
13058  * intel_plane_destroy - destroy a plane
13059  * @plane: plane to destroy
13060  *
13061  * Common destruction function for all types of planes (primary, cursor,
13062  * sprite).
13063  */
13064 void intel_plane_destroy(struct drm_plane *plane)
13065 {
13066         drm_plane_cleanup(plane);
13067         kfree(to_intel_plane(plane));
13068 }
13069
13070 static bool i8xx_mod_supported(uint32_t format, uint64_t modifier)
13071 {
13072         switch (format) {
13073         case DRM_FORMAT_C8:
13074         case DRM_FORMAT_RGB565:
13075         case DRM_FORMAT_XRGB1555:
13076         case DRM_FORMAT_XRGB8888:
13077                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13078                         modifier == I915_FORMAT_MOD_X_TILED;
13079         default:
13080                 return false;
13081         }
13082 }
13083
13084 static bool i965_mod_supported(uint32_t format, uint64_t modifier)
13085 {
13086         switch (format) {
13087         case DRM_FORMAT_C8:
13088         case DRM_FORMAT_RGB565:
13089         case DRM_FORMAT_XRGB8888:
13090         case DRM_FORMAT_XBGR8888:
13091         case DRM_FORMAT_XRGB2101010:
13092         case DRM_FORMAT_XBGR2101010:
13093                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13094                         modifier == I915_FORMAT_MOD_X_TILED;
13095         default:
13096                 return false;
13097         }
13098 }
13099
13100 static bool skl_mod_supported(uint32_t format, uint64_t modifier)
13101 {
13102         switch (format) {
13103         case DRM_FORMAT_XRGB8888:
13104         case DRM_FORMAT_XBGR8888:
13105         case DRM_FORMAT_ARGB8888:
13106         case DRM_FORMAT_ABGR8888:
13107                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
13108                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
13109                         return true;
13110                 /* fall through */
13111         case DRM_FORMAT_RGB565:
13112         case DRM_FORMAT_XRGB2101010:
13113         case DRM_FORMAT_XBGR2101010:
13114         case DRM_FORMAT_YUYV:
13115         case DRM_FORMAT_YVYU:
13116         case DRM_FORMAT_UYVY:
13117         case DRM_FORMAT_VYUY:
13118                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13119                         return true;
13120                 /* fall through */
13121         case DRM_FORMAT_C8:
13122                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13123                     modifier == I915_FORMAT_MOD_X_TILED ||
13124                     modifier == I915_FORMAT_MOD_Y_TILED)
13125                         return true;
13126                 /* fall through */
13127         default:
13128                 return false;
13129         }
13130 }
13131
13132 static bool intel_primary_plane_format_mod_supported(struct drm_plane *plane,
13133                                                      uint32_t format,
13134                                                      uint64_t modifier)
13135 {
13136         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13137
13138         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13139                 return false;
13140
13141         if ((modifier >> 56) != DRM_FORMAT_MOD_VENDOR_INTEL &&
13142             modifier != DRM_FORMAT_MOD_LINEAR)
13143                 return false;
13144
13145         if (INTEL_GEN(dev_priv) >= 9)
13146                 return skl_mod_supported(format, modifier);
13147         else if (INTEL_GEN(dev_priv) >= 4)
13148                 return i965_mod_supported(format, modifier);
13149         else
13150                 return i8xx_mod_supported(format, modifier);
13151 }
13152
13153 static bool intel_cursor_plane_format_mod_supported(struct drm_plane *plane,
13154                                                     uint32_t format,
13155                                                     uint64_t modifier)
13156 {
13157         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13158                 return false;
13159
13160         return modifier == DRM_FORMAT_MOD_LINEAR && format == DRM_FORMAT_ARGB8888;
13161 }
13162
13163 static struct drm_plane_funcs intel_plane_funcs = {
13164         .update_plane = drm_atomic_helper_update_plane,
13165         .disable_plane = drm_atomic_helper_disable_plane,
13166         .destroy = intel_plane_destroy,
13167         .atomic_get_property = intel_plane_atomic_get_property,
13168         .atomic_set_property = intel_plane_atomic_set_property,
13169         .atomic_duplicate_state = intel_plane_duplicate_state,
13170         .atomic_destroy_state = intel_plane_destroy_state,
13171         .format_mod_supported = intel_primary_plane_format_mod_supported,
13172 };
13173
13174 static int
13175 intel_legacy_cursor_update(struct drm_plane *plane,
13176                            struct drm_crtc *crtc,
13177                            struct drm_framebuffer *fb,
13178                            int crtc_x, int crtc_y,
13179                            unsigned int crtc_w, unsigned int crtc_h,
13180                            uint32_t src_x, uint32_t src_y,
13181                            uint32_t src_w, uint32_t src_h,
13182                            struct drm_modeset_acquire_ctx *ctx)
13183 {
13184         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13185         int ret;
13186         struct drm_plane_state *old_plane_state, *new_plane_state;
13187         struct intel_plane *intel_plane = to_intel_plane(plane);
13188         struct drm_framebuffer *old_fb;
13189         struct drm_crtc_state *crtc_state = crtc->state;
13190
13191         /*
13192          * When crtc is inactive or there is a modeset pending,
13193          * wait for it to complete in the slowpath
13194          */
13195         if (!crtc_state->active || needs_modeset(crtc_state) ||
13196             to_intel_crtc_state(crtc_state)->update_pipe)
13197                 goto slow;
13198
13199         old_plane_state = plane->state;
13200         /*
13201          * Don't do an async update if there is an outstanding commit modifying
13202          * the plane.  This prevents our async update's changes from getting
13203          * overridden by a previous synchronous update's state.
13204          */
13205         if (old_plane_state->commit &&
13206             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13207                 goto slow;
13208
13209         /*
13210          * If any parameters change that may affect watermarks,
13211          * take the slowpath. Only changing fb or position should be
13212          * in the fastpath.
13213          */
13214         if (old_plane_state->crtc != crtc ||
13215             old_plane_state->src_w != src_w ||
13216             old_plane_state->src_h != src_h ||
13217             old_plane_state->crtc_w != crtc_w ||
13218             old_plane_state->crtc_h != crtc_h ||
13219             !old_plane_state->fb != !fb)
13220                 goto slow;
13221
13222         new_plane_state = intel_plane_duplicate_state(plane);
13223         if (!new_plane_state)
13224                 return -ENOMEM;
13225
13226         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13227
13228         new_plane_state->src_x = src_x;
13229         new_plane_state->src_y = src_y;
13230         new_plane_state->src_w = src_w;
13231         new_plane_state->src_h = src_h;
13232         new_plane_state->crtc_x = crtc_x;
13233         new_plane_state->crtc_y = crtc_y;
13234         new_plane_state->crtc_w = crtc_w;
13235         new_plane_state->crtc_h = crtc_h;
13236
13237         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13238                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13239                                                   to_intel_plane_state(plane->state),
13240                                                   to_intel_plane_state(new_plane_state));
13241         if (ret)
13242                 goto out_free;
13243
13244         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13245         if (ret)
13246                 goto out_free;
13247
13248         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13249         if (ret)
13250                 goto out_unlock;
13251
13252         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13253
13254         old_fb = old_plane_state->fb;
13255         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13256                           intel_plane->frontbuffer_bit);
13257
13258         /* Swap plane state */
13259         plane->state = new_plane_state;
13260
13261         if (plane->state->visible) {
13262                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13263                 intel_plane->update_plane(intel_plane,
13264                                           to_intel_crtc_state(crtc->state),
13265                                           to_intel_plane_state(plane->state));
13266         } else {
13267                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13268                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13269         }
13270
13271         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13272
13273 out_unlock:
13274         mutex_unlock(&dev_priv->drm.struct_mutex);
13275 out_free:
13276         if (ret)
13277                 intel_plane_destroy_state(plane, new_plane_state);
13278         else
13279                 intel_plane_destroy_state(plane, old_plane_state);
13280         return ret;
13281
13282 slow:
13283         return drm_atomic_helper_update_plane(plane, crtc, fb,
13284                                               crtc_x, crtc_y, crtc_w, crtc_h,
13285                                               src_x, src_y, src_w, src_h, ctx);
13286 }
13287
13288 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13289         .update_plane = intel_legacy_cursor_update,
13290         .disable_plane = drm_atomic_helper_disable_plane,
13291         .destroy = intel_plane_destroy,
13292         .atomic_get_property = intel_plane_atomic_get_property,
13293         .atomic_set_property = intel_plane_atomic_set_property,
13294         .atomic_duplicate_state = intel_plane_duplicate_state,
13295         .atomic_destroy_state = intel_plane_destroy_state,
13296         .format_mod_supported = intel_cursor_plane_format_mod_supported,
13297 };
13298
13299 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13300                                enum i9xx_plane_id i9xx_plane)
13301 {
13302         if (!HAS_FBC(dev_priv))
13303                 return false;
13304
13305         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13306                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13307         else if (IS_IVYBRIDGE(dev_priv))
13308                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13309                         i9xx_plane == PLANE_C;
13310         else if (INTEL_GEN(dev_priv) >= 4)
13311                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13312         else
13313                 return i9xx_plane == PLANE_A;
13314 }
13315
13316 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13317                               enum pipe pipe, enum plane_id plane_id)
13318 {
13319         if (!HAS_FBC(dev_priv))
13320                 return false;
13321
13322         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13323 }
13324
13325 static struct intel_plane *
13326 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13327 {
13328         struct intel_plane *primary = NULL;
13329         struct intel_plane_state *state = NULL;
13330         const uint32_t *intel_primary_formats;
13331         unsigned int supported_rotations;
13332         unsigned int num_formats;
13333         const uint64_t *modifiers;
13334         int ret;
13335
13336         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13337         if (!primary) {
13338                 ret = -ENOMEM;
13339                 goto fail;
13340         }
13341
13342         state = intel_create_plane_state(&primary->base);
13343         if (!state) {
13344                 ret = -ENOMEM;
13345                 goto fail;
13346         }
13347
13348         primary->base.state = &state->base;
13349
13350         primary->can_scale = false;
13351         primary->max_downscale = 1;
13352         if (INTEL_GEN(dev_priv) >= 9) {
13353                 primary->can_scale = true;
13354                 state->scaler_id = -1;
13355         }
13356         primary->pipe = pipe;
13357         /*
13358          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13359          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13360          */
13361         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13362                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13363         else
13364                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13365         primary->id = PLANE_PRIMARY;
13366         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13367
13368         if (INTEL_GEN(dev_priv) >= 9)
13369                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13370                                                      primary->pipe,
13371                                                      primary->id);
13372         else
13373                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13374                                                       primary->i9xx_plane);
13375
13376         if (primary->has_fbc) {
13377                 struct intel_fbc *fbc = &dev_priv->fbc;
13378
13379                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13380         }
13381
13382         primary->check_plane = intel_check_primary_plane;
13383
13384         if (INTEL_GEN(dev_priv) >= 9) {
13385                 intel_primary_formats = skl_primary_formats;
13386                 num_formats = ARRAY_SIZE(skl_primary_formats);
13387
13388                 if (skl_plane_has_ccs(dev_priv, pipe, PLANE_PRIMARY))
13389                         modifiers = skl_format_modifiers_ccs;
13390                 else
13391                         modifiers = skl_format_modifiers_noccs;
13392
13393                 primary->update_plane = skl_update_plane;
13394                 primary->disable_plane = skl_disable_plane;
13395                 primary->get_hw_state = skl_plane_get_hw_state;
13396         } else if (INTEL_GEN(dev_priv) >= 4) {
13397                 intel_primary_formats = i965_primary_formats;
13398                 num_formats = ARRAY_SIZE(i965_primary_formats);
13399                 modifiers = i9xx_format_modifiers;
13400
13401                 primary->update_plane = i9xx_update_plane;
13402                 primary->disable_plane = i9xx_disable_plane;
13403                 primary->get_hw_state = i9xx_plane_get_hw_state;
13404         } else {
13405                 intel_primary_formats = i8xx_primary_formats;
13406                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13407                 modifiers = i9xx_format_modifiers;
13408
13409                 primary->update_plane = i9xx_update_plane;
13410                 primary->disable_plane = i9xx_disable_plane;
13411                 primary->get_hw_state = i9xx_plane_get_hw_state;
13412         }
13413
13414         if (INTEL_GEN(dev_priv) >= 9)
13415                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13416                                                0, &intel_plane_funcs,
13417                                                intel_primary_formats, num_formats,
13418                                                modifiers,
13419                                                DRM_PLANE_TYPE_PRIMARY,
13420                                                "plane 1%c", pipe_name(pipe));
13421         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13422                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13423                                                0, &intel_plane_funcs,
13424                                                intel_primary_formats, num_formats,
13425                                                modifiers,
13426                                                DRM_PLANE_TYPE_PRIMARY,
13427                                                "primary %c", pipe_name(pipe));
13428         else
13429                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13430                                                0, &intel_plane_funcs,
13431                                                intel_primary_formats, num_formats,
13432                                                modifiers,
13433                                                DRM_PLANE_TYPE_PRIMARY,
13434                                                "plane %c",
13435                                                plane_name(primary->i9xx_plane));
13436         if (ret)
13437                 goto fail;
13438
13439         if (INTEL_GEN(dev_priv) >= 10) {
13440                 supported_rotations =
13441                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13442                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13443                         DRM_MODE_REFLECT_X;
13444         } else if (INTEL_GEN(dev_priv) >= 9) {
13445                 supported_rotations =
13446                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13447                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13448         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13449                 supported_rotations =
13450                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13451                         DRM_MODE_REFLECT_X;
13452         } else if (INTEL_GEN(dev_priv) >= 4) {
13453                 supported_rotations =
13454                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13455         } else {
13456                 supported_rotations = DRM_MODE_ROTATE_0;
13457         }
13458
13459         if (INTEL_GEN(dev_priv) >= 4)
13460                 drm_plane_create_rotation_property(&primary->base,
13461                                                    DRM_MODE_ROTATE_0,
13462                                                    supported_rotations);
13463
13464         if (INTEL_GEN(dev_priv) >= 9)
13465                 drm_plane_create_color_properties(&primary->base,
13466                                                   BIT(DRM_COLOR_YCBCR_BT601) |
13467                                                   BIT(DRM_COLOR_YCBCR_BT709),
13468                                                   BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
13469                                                   BIT(DRM_COLOR_YCBCR_FULL_RANGE),
13470                                                   DRM_COLOR_YCBCR_BT709,
13471                                                   DRM_COLOR_YCBCR_LIMITED_RANGE);
13472
13473         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13474
13475         return primary;
13476
13477 fail:
13478         kfree(state);
13479         kfree(primary);
13480
13481         return ERR_PTR(ret);
13482 }
13483
13484 static struct intel_plane *
13485 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13486                           enum pipe pipe)
13487 {
13488         struct intel_plane *cursor = NULL;
13489         struct intel_plane_state *state = NULL;
13490         int ret;
13491
13492         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13493         if (!cursor) {
13494                 ret = -ENOMEM;
13495                 goto fail;
13496         }
13497
13498         state = intel_create_plane_state(&cursor->base);
13499         if (!state) {
13500                 ret = -ENOMEM;
13501                 goto fail;
13502         }
13503
13504         cursor->base.state = &state->base;
13505
13506         cursor->can_scale = false;
13507         cursor->max_downscale = 1;
13508         cursor->pipe = pipe;
13509         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13510         cursor->id = PLANE_CURSOR;
13511         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13512
13513         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13514                 cursor->update_plane = i845_update_cursor;
13515                 cursor->disable_plane = i845_disable_cursor;
13516                 cursor->get_hw_state = i845_cursor_get_hw_state;
13517                 cursor->check_plane = i845_check_cursor;
13518         } else {
13519                 cursor->update_plane = i9xx_update_cursor;
13520                 cursor->disable_plane = i9xx_disable_cursor;
13521                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13522                 cursor->check_plane = i9xx_check_cursor;
13523         }
13524
13525         cursor->cursor.base = ~0;
13526         cursor->cursor.cntl = ~0;
13527
13528         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13529                 cursor->cursor.size = ~0;
13530
13531         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13532                                        0, &intel_cursor_plane_funcs,
13533                                        intel_cursor_formats,
13534                                        ARRAY_SIZE(intel_cursor_formats),
13535                                        cursor_format_modifiers,
13536                                        DRM_PLANE_TYPE_CURSOR,
13537                                        "cursor %c", pipe_name(pipe));
13538         if (ret)
13539                 goto fail;
13540
13541         if (INTEL_GEN(dev_priv) >= 4)
13542                 drm_plane_create_rotation_property(&cursor->base,
13543                                                    DRM_MODE_ROTATE_0,
13544                                                    DRM_MODE_ROTATE_0 |
13545                                                    DRM_MODE_ROTATE_180);
13546
13547         if (INTEL_GEN(dev_priv) >= 9)
13548                 state->scaler_id = -1;
13549
13550         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13551
13552         return cursor;
13553
13554 fail:
13555         kfree(state);
13556         kfree(cursor);
13557
13558         return ERR_PTR(ret);
13559 }
13560
13561 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13562                                     struct intel_crtc_state *crtc_state)
13563 {
13564         struct intel_crtc_scaler_state *scaler_state =
13565                 &crtc_state->scaler_state;
13566         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13567         int i;
13568
13569         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13570         if (!crtc->num_scalers)
13571                 return;
13572
13573         for (i = 0; i < crtc->num_scalers; i++) {
13574                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13575
13576                 scaler->in_use = 0;
13577                 scaler->mode = PS_SCALER_MODE_DYN;
13578         }
13579
13580         scaler_state->scaler_id = -1;
13581 }
13582
13583 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13584 {
13585         struct intel_crtc *intel_crtc;
13586         struct intel_crtc_state *crtc_state = NULL;
13587         struct intel_plane *primary = NULL;
13588         struct intel_plane *cursor = NULL;
13589         int sprite, ret;
13590
13591         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13592         if (!intel_crtc)
13593                 return -ENOMEM;
13594
13595         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13596         if (!crtc_state) {
13597                 ret = -ENOMEM;
13598                 goto fail;
13599         }
13600         intel_crtc->config = crtc_state;
13601         intel_crtc->base.state = &crtc_state->base;
13602         crtc_state->base.crtc = &intel_crtc->base;
13603
13604         primary = intel_primary_plane_create(dev_priv, pipe);
13605         if (IS_ERR(primary)) {
13606                 ret = PTR_ERR(primary);
13607                 goto fail;
13608         }
13609         intel_crtc->plane_ids_mask |= BIT(primary->id);
13610
13611         for_each_sprite(dev_priv, pipe, sprite) {
13612                 struct intel_plane *plane;
13613
13614                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13615                 if (IS_ERR(plane)) {
13616                         ret = PTR_ERR(plane);
13617                         goto fail;
13618                 }
13619                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13620         }
13621
13622         cursor = intel_cursor_plane_create(dev_priv, pipe);
13623         if (IS_ERR(cursor)) {
13624                 ret = PTR_ERR(cursor);
13625                 goto fail;
13626         }
13627         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13628
13629         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13630                                         &primary->base, &cursor->base,
13631                                         &intel_crtc_funcs,
13632                                         "pipe %c", pipe_name(pipe));
13633         if (ret)
13634                 goto fail;
13635
13636         intel_crtc->pipe = pipe;
13637
13638         /* initialize shared scalers */
13639         intel_crtc_init_scalers(intel_crtc, crtc_state);
13640
13641         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
13642                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
13643         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
13644
13645         if (INTEL_GEN(dev_priv) < 9) {
13646                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
13647
13648                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13649                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
13650                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
13651         }
13652
13653         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13654
13655         intel_color_init(&intel_crtc->base);
13656
13657         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13658
13659         return 0;
13660
13661 fail:
13662         /*
13663          * drm_mode_config_cleanup() will free up any
13664          * crtcs/planes already initialized.
13665          */
13666         kfree(crtc_state);
13667         kfree(intel_crtc);
13668
13669         return ret;
13670 }
13671
13672 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13673 {
13674         struct drm_device *dev = connector->base.dev;
13675
13676         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13677
13678         if (!connector->base.state->crtc)
13679                 return INVALID_PIPE;
13680
13681         return to_intel_crtc(connector->base.state->crtc)->pipe;
13682 }
13683
13684 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
13685                                       struct drm_file *file)
13686 {
13687         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13688         struct drm_crtc *drmmode_crtc;
13689         struct intel_crtc *crtc;
13690
13691         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13692         if (!drmmode_crtc)
13693                 return -ENOENT;
13694
13695         crtc = to_intel_crtc(drmmode_crtc);
13696         pipe_from_crtc_id->pipe = crtc->pipe;
13697
13698         return 0;
13699 }
13700
13701 static int intel_encoder_clones(struct intel_encoder *encoder)
13702 {
13703         struct drm_device *dev = encoder->base.dev;
13704         struct intel_encoder *source_encoder;
13705         int index_mask = 0;
13706         int entry = 0;
13707
13708         for_each_intel_encoder(dev, source_encoder) {
13709                 if (encoders_cloneable(encoder, source_encoder))
13710                         index_mask |= (1 << entry);
13711
13712                 entry++;
13713         }
13714
13715         return index_mask;
13716 }
13717
13718 static bool has_edp_a(struct drm_i915_private *dev_priv)
13719 {
13720         if (!IS_MOBILE(dev_priv))
13721                 return false;
13722
13723         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13724                 return false;
13725
13726         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13727                 return false;
13728
13729         return true;
13730 }
13731
13732 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13733 {
13734         if (INTEL_GEN(dev_priv) >= 9)
13735                 return false;
13736
13737         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13738                 return false;
13739
13740         if (IS_CHERRYVIEW(dev_priv))
13741                 return false;
13742
13743         if (HAS_PCH_LPT_H(dev_priv) &&
13744             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13745                 return false;
13746
13747         /* DDI E can't be used if DDI A requires 4 lanes */
13748         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13749                 return false;
13750
13751         if (!dev_priv->vbt.int_crt_support)
13752                 return false;
13753
13754         return true;
13755 }
13756
13757 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13758 {
13759         int pps_num;
13760         int pps_idx;
13761
13762         if (HAS_DDI(dev_priv))
13763                 return;
13764         /*
13765          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13766          * everywhere where registers can be write protected.
13767          */
13768         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13769                 pps_num = 2;
13770         else
13771                 pps_num = 1;
13772
13773         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13774                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13775
13776                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13777                 I915_WRITE(PP_CONTROL(pps_idx), val);
13778         }
13779 }
13780
13781 static void intel_pps_init(struct drm_i915_private *dev_priv)
13782 {
13783         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13784                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13785         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13786                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13787         else
13788                 dev_priv->pps_mmio_base = PPS_BASE;
13789
13790         intel_pps_unlock_regs_wa(dev_priv);
13791 }
13792
13793 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13794 {
13795         struct intel_encoder *encoder;
13796         bool dpd_is_edp = false;
13797
13798         intel_pps_init(dev_priv);
13799
13800         /*
13801          * intel_edp_init_connector() depends on this completing first, to
13802          * prevent the registeration of both eDP and LVDS and the incorrect
13803          * sharing of the PPS.
13804          */
13805         intel_lvds_init(dev_priv);
13806
13807         if (intel_crt_present(dev_priv))
13808                 intel_crt_init(dev_priv);
13809
13810         if (IS_GEN9_LP(dev_priv)) {
13811                 /*
13812                  * FIXME: Broxton doesn't support port detection via the
13813                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13814                  * detect the ports.
13815                  */
13816                 intel_ddi_init(dev_priv, PORT_A);
13817                 intel_ddi_init(dev_priv, PORT_B);
13818                 intel_ddi_init(dev_priv, PORT_C);
13819
13820                 intel_dsi_init(dev_priv);
13821         } else if (HAS_DDI(dev_priv)) {
13822                 int found;
13823
13824                 /*
13825                  * Haswell uses DDI functions to detect digital outputs.
13826                  * On SKL pre-D0 the strap isn't connected, so we assume
13827                  * it's there.
13828                  */
13829                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13830                 /* WaIgnoreDDIAStrap: skl */
13831                 if (found || IS_GEN9_BC(dev_priv))
13832                         intel_ddi_init(dev_priv, PORT_A);
13833
13834                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
13835                  * register */
13836                 found = I915_READ(SFUSE_STRAP);
13837
13838                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13839                         intel_ddi_init(dev_priv, PORT_B);
13840                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13841                         intel_ddi_init(dev_priv, PORT_C);
13842                 if (found & SFUSE_STRAP_DDID_DETECTED)
13843                         intel_ddi_init(dev_priv, PORT_D);
13844                 if (found & SFUSE_STRAP_DDIF_DETECTED)
13845                         intel_ddi_init(dev_priv, PORT_F);
13846                 /*
13847                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13848                  */
13849                 if (IS_GEN9_BC(dev_priv) &&
13850                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13851                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13852                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13853                         intel_ddi_init(dev_priv, PORT_E);
13854
13855         } else if (HAS_PCH_SPLIT(dev_priv)) {
13856                 int found;
13857                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
13858
13859                 if (has_edp_a(dev_priv))
13860                         intel_dp_init(dev_priv, DP_A, PORT_A);
13861
13862                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13863                         /* PCH SDVOB multiplex with HDMIB */
13864                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
13865                         if (!found)
13866                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
13867                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13868                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
13869                 }
13870
13871                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13872                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
13873
13874                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13875                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
13876
13877                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13878                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
13879
13880                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13881                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
13882         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
13883                 bool has_edp, has_port;
13884
13885                 /*
13886                  * The DP_DETECTED bit is the latched state of the DDC
13887                  * SDA pin at boot. However since eDP doesn't require DDC
13888                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13889                  * eDP ports may have been muxed to an alternate function.
13890                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13891                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13892                  * detect eDP ports.
13893                  *
13894                  * Sadly the straps seem to be missing sometimes even for HDMI
13895                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
13896                  * and VBT for the presence of the port. Additionally we can't
13897                  * trust the port type the VBT declares as we've seen at least
13898                  * HDMI ports that the VBT claim are DP or eDP.
13899                  */
13900                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
13901                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
13902                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
13903                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
13904                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
13905                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
13906
13907                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
13908                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
13909                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
13910                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
13911                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
13912                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
13913
13914                 if (IS_CHERRYVIEW(dev_priv)) {
13915                         /*
13916                          * eDP not supported on port D,
13917                          * so no need to worry about it
13918                          */
13919                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
13920                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
13921                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
13922                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
13923                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
13924                 }
13925
13926                 intel_dsi_init(dev_priv);
13927         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
13928                 bool found = false;
13929
13930                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13931                         DRM_DEBUG_KMS("probing SDVOB\n");
13932                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
13933                         if (!found && IS_G4X(dev_priv)) {
13934                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13935                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
13936                         }
13937
13938                         if (!found && IS_G4X(dev_priv))
13939                                 intel_dp_init(dev_priv, DP_B, PORT_B);
13940                 }
13941
13942                 /* Before G4X SDVOC doesn't have its own detect register */
13943
13944                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13945                         DRM_DEBUG_KMS("probing SDVOC\n");
13946                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
13947                 }
13948
13949                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13950
13951                         if (IS_G4X(dev_priv)) {
13952                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13953                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
13954                         }
13955                         if (IS_G4X(dev_priv))
13956                                 intel_dp_init(dev_priv, DP_C, PORT_C);
13957                 }
13958
13959                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
13960                         intel_dp_init(dev_priv, DP_D, PORT_D);
13961         } else if (IS_GEN2(dev_priv))
13962                 intel_dvo_init(dev_priv);
13963
13964         if (SUPPORTS_TV(dev_priv))
13965                 intel_tv_init(dev_priv);
13966
13967         intel_psr_init(dev_priv);
13968
13969         for_each_intel_encoder(&dev_priv->drm, encoder) {
13970                 encoder->base.possible_crtcs = encoder->crtc_mask;
13971                 encoder->base.possible_clones =
13972                         intel_encoder_clones(encoder);
13973         }
13974
13975         intel_init_pch_refclk(dev_priv);
13976
13977         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
13978 }
13979
13980 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13981 {
13982         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13983
13984         drm_framebuffer_cleanup(fb);
13985
13986         i915_gem_object_lock(intel_fb->obj);
13987         WARN_ON(!intel_fb->obj->framebuffer_references--);
13988         i915_gem_object_unlock(intel_fb->obj);
13989
13990         i915_gem_object_put(intel_fb->obj);
13991
13992         kfree(intel_fb);
13993 }
13994
13995 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13996                                                 struct drm_file *file,
13997                                                 unsigned int *handle)
13998 {
13999         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14000         struct drm_i915_gem_object *obj = intel_fb->obj;
14001
14002         if (obj->userptr.mm) {
14003                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14004                 return -EINVAL;
14005         }
14006
14007         return drm_gem_handle_create(file, &obj->base, handle);
14008 }
14009
14010 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14011                                         struct drm_file *file,
14012                                         unsigned flags, unsigned color,
14013                                         struct drm_clip_rect *clips,
14014                                         unsigned num_clips)
14015 {
14016         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14017
14018         i915_gem_object_flush_if_display(obj);
14019         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14020
14021         return 0;
14022 }
14023
14024 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14025         .destroy = intel_user_framebuffer_destroy,
14026         .create_handle = intel_user_framebuffer_create_handle,
14027         .dirty = intel_user_framebuffer_dirty,
14028 };
14029
14030 static
14031 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14032                          uint64_t fb_modifier, uint32_t pixel_format)
14033 {
14034         u32 gen = INTEL_GEN(dev_priv);
14035
14036         if (gen >= 9) {
14037                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14038
14039                 /* "The stride in bytes must not exceed the of the size of 8K
14040                  *  pixels and 32K bytes."
14041                  */
14042                 return min(8192 * cpp, 32768);
14043         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
14044                 return 32*1024;
14045         } else if (gen >= 4) {
14046                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14047                         return 16*1024;
14048                 else
14049                         return 32*1024;
14050         } else if (gen >= 3) {
14051                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14052                         return 8*1024;
14053                 else
14054                         return 16*1024;
14055         } else {
14056                 /* XXX DSPC is limited to 4k tiled */
14057                 return 8*1024;
14058         }
14059 }
14060
14061 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14062                                   struct drm_i915_gem_object *obj,
14063                                   struct drm_mode_fb_cmd2 *mode_cmd)
14064 {
14065         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14066         struct drm_framebuffer *fb = &intel_fb->base;
14067         struct drm_format_name_buf format_name;
14068         u32 pitch_limit;
14069         unsigned int tiling, stride;
14070         int ret = -EINVAL;
14071         int i;
14072
14073         i915_gem_object_lock(obj);
14074         obj->framebuffer_references++;
14075         tiling = i915_gem_object_get_tiling(obj);
14076         stride = i915_gem_object_get_stride(obj);
14077         i915_gem_object_unlock(obj);
14078
14079         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14080                 /*
14081                  * If there's a fence, enforce that
14082                  * the fb modifier and tiling mode match.
14083                  */
14084                 if (tiling != I915_TILING_NONE &&
14085                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14086                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14087                         goto err;
14088                 }
14089         } else {
14090                 if (tiling == I915_TILING_X) {
14091                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14092                 } else if (tiling == I915_TILING_Y) {
14093                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14094                         goto err;
14095                 }
14096         }
14097
14098         /* Passed in modifier sanity checking. */
14099         switch (mode_cmd->modifier[0]) {
14100         case I915_FORMAT_MOD_Y_TILED_CCS:
14101         case I915_FORMAT_MOD_Yf_TILED_CCS:
14102                 switch (mode_cmd->pixel_format) {
14103                 case DRM_FORMAT_XBGR8888:
14104                 case DRM_FORMAT_ABGR8888:
14105                 case DRM_FORMAT_XRGB8888:
14106                 case DRM_FORMAT_ARGB8888:
14107                         break;
14108                 default:
14109                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14110                         goto err;
14111                 }
14112                 /* fall through */
14113         case I915_FORMAT_MOD_Y_TILED:
14114         case I915_FORMAT_MOD_Yf_TILED:
14115                 if (INTEL_GEN(dev_priv) < 9) {
14116                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14117                                       mode_cmd->modifier[0]);
14118                         goto err;
14119                 }
14120         case DRM_FORMAT_MOD_LINEAR:
14121         case I915_FORMAT_MOD_X_TILED:
14122                 break;
14123         default:
14124                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14125                               mode_cmd->modifier[0]);
14126                 goto err;
14127         }
14128
14129         /*
14130          * gen2/3 display engine uses the fence if present,
14131          * so the tiling mode must match the fb modifier exactly.
14132          */
14133         if (INTEL_GEN(dev_priv) < 4 &&
14134             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14135                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14136                 goto err;
14137         }
14138
14139         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14140                                            mode_cmd->pixel_format);
14141         if (mode_cmd->pitches[0] > pitch_limit) {
14142                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14143                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14144                               "tiled" : "linear",
14145                               mode_cmd->pitches[0], pitch_limit);
14146                 goto err;
14147         }
14148
14149         /*
14150          * If there's a fence, enforce that
14151          * the fb pitch and fence stride match.
14152          */
14153         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14154                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14155                               mode_cmd->pitches[0], stride);
14156                 goto err;
14157         }
14158
14159         /* Reject formats not supported by any plane early. */
14160         switch (mode_cmd->pixel_format) {
14161         case DRM_FORMAT_C8:
14162         case DRM_FORMAT_RGB565:
14163         case DRM_FORMAT_XRGB8888:
14164         case DRM_FORMAT_ARGB8888:
14165                 break;
14166         case DRM_FORMAT_XRGB1555:
14167                 if (INTEL_GEN(dev_priv) > 3) {
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         case DRM_FORMAT_ABGR8888:
14174                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14175                     INTEL_GEN(dev_priv) < 9) {
14176                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14177                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14178                         goto err;
14179                 }
14180                 break;
14181         case DRM_FORMAT_XBGR8888:
14182         case DRM_FORMAT_XRGB2101010:
14183         case DRM_FORMAT_XBGR2101010:
14184                 if (INTEL_GEN(dev_priv) < 4) {
14185                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14186                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14187                         goto err;
14188                 }
14189                 break;
14190         case DRM_FORMAT_ABGR2101010:
14191                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14192                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14193                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14194                         goto err;
14195                 }
14196                 break;
14197         case DRM_FORMAT_YUYV:
14198         case DRM_FORMAT_UYVY:
14199         case DRM_FORMAT_YVYU:
14200         case DRM_FORMAT_VYUY:
14201                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14202                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14203                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14204                         goto err;
14205                 }
14206                 break;
14207         default:
14208                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14209                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14210                 goto err;
14211         }
14212
14213         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14214         if (mode_cmd->offsets[0] != 0)
14215                 goto err;
14216
14217         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14218
14219         for (i = 0; i < fb->format->num_planes; i++) {
14220                 u32 stride_alignment;
14221
14222                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14223                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14224                         goto err;
14225                 }
14226
14227                 stride_alignment = intel_fb_stride_alignment(fb, i);
14228
14229                 /*
14230                  * Display WA #0531: skl,bxt,kbl,glk
14231                  *
14232                  * Render decompression and plane width > 3840
14233                  * combined with horizontal panning requires the
14234                  * plane stride to be a multiple of 4. We'll just
14235                  * require the entire fb to accommodate that to avoid
14236                  * potential runtime errors at plane configuration time.
14237                  */
14238                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14239                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14240                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14241                         stride_alignment *= 4;
14242
14243                 if (fb->pitches[i] & (stride_alignment - 1)) {
14244                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14245                                       i, fb->pitches[i], stride_alignment);
14246                         goto err;
14247                 }
14248         }
14249
14250         intel_fb->obj = obj;
14251
14252         ret = intel_fill_fb_info(dev_priv, fb);
14253         if (ret)
14254                 goto err;
14255
14256         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14257         if (ret) {
14258                 DRM_ERROR("framebuffer init failed %d\n", ret);
14259                 goto err;
14260         }
14261
14262         return 0;
14263
14264 err:
14265         i915_gem_object_lock(obj);
14266         obj->framebuffer_references--;
14267         i915_gem_object_unlock(obj);
14268         return ret;
14269 }
14270
14271 static struct drm_framebuffer *
14272 intel_user_framebuffer_create(struct drm_device *dev,
14273                               struct drm_file *filp,
14274                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14275 {
14276         struct drm_framebuffer *fb;
14277         struct drm_i915_gem_object *obj;
14278         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14279
14280         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14281         if (!obj)
14282                 return ERR_PTR(-ENOENT);
14283
14284         fb = intel_framebuffer_create(obj, &mode_cmd);
14285         if (IS_ERR(fb))
14286                 i915_gem_object_put(obj);
14287
14288         return fb;
14289 }
14290
14291 static void intel_atomic_state_free(struct drm_atomic_state *state)
14292 {
14293         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14294
14295         drm_atomic_state_default_release(state);
14296
14297         i915_sw_fence_fini(&intel_state->commit_ready);
14298
14299         kfree(state);
14300 }
14301
14302 static enum drm_mode_status
14303 intel_mode_valid(struct drm_device *dev,
14304                  const struct drm_display_mode *mode)
14305 {
14306         if (mode->vscan > 1)
14307                 return MODE_NO_VSCAN;
14308
14309         if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
14310                 return MODE_NO_DBLESCAN;
14311
14312         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14313                 return MODE_H_ILLEGAL;
14314
14315         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14316                            DRM_MODE_FLAG_NCSYNC |
14317                            DRM_MODE_FLAG_PCSYNC))
14318                 return MODE_HSYNC;
14319
14320         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14321                            DRM_MODE_FLAG_PIXMUX |
14322                            DRM_MODE_FLAG_CLKDIV2))
14323                 return MODE_BAD;
14324
14325         return MODE_OK;
14326 }
14327
14328 static const struct drm_mode_config_funcs intel_mode_funcs = {
14329         .fb_create = intel_user_framebuffer_create,
14330         .get_format_info = intel_get_format_info,
14331         .output_poll_changed = intel_fbdev_output_poll_changed,
14332         .mode_valid = intel_mode_valid,
14333         .atomic_check = intel_atomic_check,
14334         .atomic_commit = intel_atomic_commit,
14335         .atomic_state_alloc = intel_atomic_state_alloc,
14336         .atomic_state_clear = intel_atomic_state_clear,
14337         .atomic_state_free = intel_atomic_state_free,
14338 };
14339
14340 /**
14341  * intel_init_display_hooks - initialize the display modesetting hooks
14342  * @dev_priv: device private
14343  */
14344 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14345 {
14346         intel_init_cdclk_hooks(dev_priv);
14347
14348         if (INTEL_GEN(dev_priv) >= 9) {
14349                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14350                 dev_priv->display.get_initial_plane_config =
14351                         skylake_get_initial_plane_config;
14352                 dev_priv->display.crtc_compute_clock =
14353                         haswell_crtc_compute_clock;
14354                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14355                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14356         } else if (HAS_DDI(dev_priv)) {
14357                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14358                 dev_priv->display.get_initial_plane_config =
14359                         i9xx_get_initial_plane_config;
14360                 dev_priv->display.crtc_compute_clock =
14361                         haswell_crtc_compute_clock;
14362                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14363                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14364         } else if (HAS_PCH_SPLIT(dev_priv)) {
14365                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14366                 dev_priv->display.get_initial_plane_config =
14367                         i9xx_get_initial_plane_config;
14368                 dev_priv->display.crtc_compute_clock =
14369                         ironlake_crtc_compute_clock;
14370                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14371                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14372         } else if (IS_CHERRYVIEW(dev_priv)) {
14373                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14374                 dev_priv->display.get_initial_plane_config =
14375                         i9xx_get_initial_plane_config;
14376                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14377                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14378                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14379         } else if (IS_VALLEYVIEW(dev_priv)) {
14380                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14381                 dev_priv->display.get_initial_plane_config =
14382                         i9xx_get_initial_plane_config;
14383                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14384                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14385                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14386         } else if (IS_G4X(dev_priv)) {
14387                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14388                 dev_priv->display.get_initial_plane_config =
14389                         i9xx_get_initial_plane_config;
14390                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14391                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14392                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14393         } else if (IS_PINEVIEW(dev_priv)) {
14394                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14395                 dev_priv->display.get_initial_plane_config =
14396                         i9xx_get_initial_plane_config;
14397                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14398                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14399                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14400         } else if (!IS_GEN2(dev_priv)) {
14401                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14402                 dev_priv->display.get_initial_plane_config =
14403                         i9xx_get_initial_plane_config;
14404                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14405                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14406                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14407         } else {
14408                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14409                 dev_priv->display.get_initial_plane_config =
14410                         i9xx_get_initial_plane_config;
14411                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14412                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14413                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14414         }
14415
14416         if (IS_GEN5(dev_priv)) {
14417                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14418         } else if (IS_GEN6(dev_priv)) {
14419                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14420         } else if (IS_IVYBRIDGE(dev_priv)) {
14421                 /* FIXME: detect B0+ stepping and use auto training */
14422                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14423         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14424                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14425         }
14426
14427         if (INTEL_GEN(dev_priv) >= 9)
14428                 dev_priv->display.update_crtcs = skl_update_crtcs;
14429         else
14430                 dev_priv->display.update_crtcs = intel_update_crtcs;
14431 }
14432
14433 /*
14434  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14435  */
14436 static void quirk_ssc_force_disable(struct drm_device *dev)
14437 {
14438         struct drm_i915_private *dev_priv = to_i915(dev);
14439         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14440         DRM_INFO("applying lvds SSC disable quirk\n");
14441 }
14442
14443 /*
14444  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14445  * brightness value
14446  */
14447 static void quirk_invert_brightness(struct drm_device *dev)
14448 {
14449         struct drm_i915_private *dev_priv = to_i915(dev);
14450         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14451         DRM_INFO("applying inverted panel brightness quirk\n");
14452 }
14453
14454 /* Some VBT's incorrectly indicate no backlight is present */
14455 static void quirk_backlight_present(struct drm_device *dev)
14456 {
14457         struct drm_i915_private *dev_priv = to_i915(dev);
14458         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14459         DRM_INFO("applying backlight present quirk\n");
14460 }
14461
14462 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14463  * which is 300 ms greater than eDP spec T12 min.
14464  */
14465 static void quirk_increase_t12_delay(struct drm_device *dev)
14466 {
14467         struct drm_i915_private *dev_priv = to_i915(dev);
14468
14469         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14470         DRM_INFO("Applying T12 delay quirk\n");
14471 }
14472
14473 struct intel_quirk {
14474         int device;
14475         int subsystem_vendor;
14476         int subsystem_device;
14477         void (*hook)(struct drm_device *dev);
14478 };
14479
14480 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14481 struct intel_dmi_quirk {
14482         void (*hook)(struct drm_device *dev);
14483         const struct dmi_system_id (*dmi_id_list)[];
14484 };
14485
14486 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14487 {
14488         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14489         return 1;
14490 }
14491
14492 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14493         {
14494                 .dmi_id_list = &(const struct dmi_system_id[]) {
14495                         {
14496                                 .callback = intel_dmi_reverse_brightness,
14497                                 .ident = "NCR Corporation",
14498                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14499                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14500                                 },
14501                         },
14502                         { }  /* terminating entry */
14503                 },
14504                 .hook = quirk_invert_brightness,
14505         },
14506 };
14507
14508 static struct intel_quirk intel_quirks[] = {
14509         /* Lenovo U160 cannot use SSC on LVDS */
14510         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14511
14512         /* Sony Vaio Y cannot use SSC on LVDS */
14513         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14514
14515         /* Acer Aspire 5734Z must invert backlight brightness */
14516         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14517
14518         /* Acer/eMachines G725 */
14519         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14520
14521         /* Acer/eMachines e725 */
14522         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14523
14524         /* Acer/Packard Bell NCL20 */
14525         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14526
14527         /* Acer Aspire 4736Z */
14528         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14529
14530         /* Acer Aspire 5336 */
14531         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14532
14533         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14534         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14535
14536         /* Acer C720 Chromebook (Core i3 4005U) */
14537         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14538
14539         /* Apple Macbook 2,1 (Core 2 T7400) */
14540         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14541
14542         /* Apple Macbook 4,1 */
14543         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14544
14545         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14546         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14547
14548         /* HP Chromebook 14 (Celeron 2955U) */
14549         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14550
14551         /* Dell Chromebook 11 */
14552         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14553
14554         /* Dell Chromebook 11 (2015 version) */
14555         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14556
14557         /* Toshiba Satellite P50-C-18C */
14558         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14559 };
14560
14561 static void intel_init_quirks(struct drm_device *dev)
14562 {
14563         struct pci_dev *d = dev->pdev;
14564         int i;
14565
14566         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14567                 struct intel_quirk *q = &intel_quirks[i];
14568
14569                 if (d->device == q->device &&
14570                     (d->subsystem_vendor == q->subsystem_vendor ||
14571                      q->subsystem_vendor == PCI_ANY_ID) &&
14572                     (d->subsystem_device == q->subsystem_device ||
14573                      q->subsystem_device == PCI_ANY_ID))
14574                         q->hook(dev);
14575         }
14576         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14577                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14578                         intel_dmi_quirks[i].hook(dev);
14579         }
14580 }
14581
14582 /* Disable the VGA plane that we never use */
14583 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14584 {
14585         struct pci_dev *pdev = dev_priv->drm.pdev;
14586         u8 sr1;
14587         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14588
14589         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14590         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14591         outb(SR01, VGA_SR_INDEX);
14592         sr1 = inb(VGA_SR_DATA);
14593         outb(sr1 | 1<<5, VGA_SR_DATA);
14594         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14595         udelay(300);
14596
14597         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14598         POSTING_READ(vga_reg);
14599 }
14600
14601 void intel_modeset_init_hw(struct drm_device *dev)
14602 {
14603         struct drm_i915_private *dev_priv = to_i915(dev);
14604
14605         intel_update_cdclk(dev_priv);
14606         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14607         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14608 }
14609
14610 /*
14611  * Calculate what we think the watermarks should be for the state we've read
14612  * out of the hardware and then immediately program those watermarks so that
14613  * we ensure the hardware settings match our internal state.
14614  *
14615  * We can calculate what we think WM's should be by creating a duplicate of the
14616  * current state (which was constructed during hardware readout) and running it
14617  * through the atomic check code to calculate new watermark values in the
14618  * state object.
14619  */
14620 static void sanitize_watermarks(struct drm_device *dev)
14621 {
14622         struct drm_i915_private *dev_priv = to_i915(dev);
14623         struct drm_atomic_state *state;
14624         struct intel_atomic_state *intel_state;
14625         struct drm_crtc *crtc;
14626         struct drm_crtc_state *cstate;
14627         struct drm_modeset_acquire_ctx ctx;
14628         int ret;
14629         int i;
14630
14631         /* Only supported on platforms that use atomic watermark design */
14632         if (!dev_priv->display.optimize_watermarks)
14633                 return;
14634
14635         /*
14636          * We need to hold connection_mutex before calling duplicate_state so
14637          * that the connector loop is protected.
14638          */
14639         drm_modeset_acquire_init(&ctx, 0);
14640 retry:
14641         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14642         if (ret == -EDEADLK) {
14643                 drm_modeset_backoff(&ctx);
14644                 goto retry;
14645         } else if (WARN_ON(ret)) {
14646                 goto fail;
14647         }
14648
14649         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14650         if (WARN_ON(IS_ERR(state)))
14651                 goto fail;
14652
14653         intel_state = to_intel_atomic_state(state);
14654
14655         /*
14656          * Hardware readout is the only time we don't want to calculate
14657          * intermediate watermarks (since we don't trust the current
14658          * watermarks).
14659          */
14660         if (!HAS_GMCH_DISPLAY(dev_priv))
14661                 intel_state->skip_intermediate_wm = true;
14662
14663         ret = intel_atomic_check(dev, state);
14664         if (ret) {
14665                 /*
14666                  * If we fail here, it means that the hardware appears to be
14667                  * programmed in a way that shouldn't be possible, given our
14668                  * understanding of watermark requirements.  This might mean a
14669                  * mistake in the hardware readout code or a mistake in the
14670                  * watermark calculations for a given platform.  Raise a WARN
14671                  * so that this is noticeable.
14672                  *
14673                  * If this actually happens, we'll have to just leave the
14674                  * BIOS-programmed watermarks untouched and hope for the best.
14675                  */
14676                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14677                 goto put_state;
14678         }
14679
14680         /* Write calculated watermark values back */
14681         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14682                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14683
14684                 cs->wm.need_postvbl_update = true;
14685                 dev_priv->display.optimize_watermarks(intel_state, cs);
14686
14687                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14688         }
14689
14690 put_state:
14691         drm_atomic_state_put(state);
14692 fail:
14693         drm_modeset_drop_locks(&ctx);
14694         drm_modeset_acquire_fini(&ctx);
14695 }
14696
14697 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14698 {
14699         if (IS_GEN5(dev_priv)) {
14700                 u32 fdi_pll_clk =
14701                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14702
14703                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14704         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14705                 dev_priv->fdi_pll_freq = 270000;
14706         } else {
14707                 return;
14708         }
14709
14710         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14711 }
14712
14713 int intel_modeset_init(struct drm_device *dev)
14714 {
14715         struct drm_i915_private *dev_priv = to_i915(dev);
14716         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14717         enum pipe pipe;
14718         struct intel_crtc *crtc;
14719
14720         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
14721
14722         drm_mode_config_init(dev);
14723
14724         dev->mode_config.min_width = 0;
14725         dev->mode_config.min_height = 0;
14726
14727         dev->mode_config.preferred_depth = 24;
14728         dev->mode_config.prefer_shadow = 1;
14729
14730         dev->mode_config.allow_fb_modifiers = true;
14731
14732         dev->mode_config.funcs = &intel_mode_funcs;
14733
14734         init_llist_head(&dev_priv->atomic_helper.free_list);
14735         INIT_WORK(&dev_priv->atomic_helper.free_work,
14736                   intel_atomic_helper_free_state_worker);
14737
14738         intel_init_quirks(dev);
14739
14740         intel_init_pm(dev_priv);
14741
14742         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14743                 return 0;
14744
14745         /*
14746          * There may be no VBT; and if the BIOS enabled SSC we can
14747          * just keep using it to avoid unnecessary flicker.  Whereas if the
14748          * BIOS isn't using it, don't assume it will work even if the VBT
14749          * indicates as much.
14750          */
14751         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
14752                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14753                                             DREF_SSC1_ENABLE);
14754
14755                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14756                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14757                                      bios_lvds_use_ssc ? "en" : "dis",
14758                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14759                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14760                 }
14761         }
14762
14763         if (IS_GEN2(dev_priv)) {
14764                 dev->mode_config.max_width = 2048;
14765                 dev->mode_config.max_height = 2048;
14766         } else if (IS_GEN3(dev_priv)) {
14767                 dev->mode_config.max_width = 4096;
14768                 dev->mode_config.max_height = 4096;
14769         } else {
14770                 dev->mode_config.max_width = 8192;
14771                 dev->mode_config.max_height = 8192;
14772         }
14773
14774         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14775                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
14776                 dev->mode_config.cursor_height = 1023;
14777         } else if (IS_GEN2(dev_priv)) {
14778                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14779                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14780         } else {
14781                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14782                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14783         }
14784
14785         dev->mode_config.fb_base = ggtt->gmadr.start;
14786
14787         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14788                       INTEL_INFO(dev_priv)->num_pipes,
14789                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
14790
14791         for_each_pipe(dev_priv, pipe) {
14792                 int ret;
14793
14794                 ret = intel_crtc_init(dev_priv, pipe);
14795                 if (ret) {
14796                         drm_mode_config_cleanup(dev);
14797                         return ret;
14798                 }
14799         }
14800
14801         intel_shared_dpll_init(dev);
14802         intel_update_fdi_pll_freq(dev_priv);
14803
14804         intel_update_czclk(dev_priv);
14805         intel_modeset_init_hw(dev);
14806
14807         if (dev_priv->max_cdclk_freq == 0)
14808                 intel_update_max_cdclk(dev_priv);
14809
14810         /* Just disable it once at startup */
14811         i915_disable_vga(dev_priv);
14812         intel_setup_outputs(dev_priv);
14813
14814         drm_modeset_lock_all(dev);
14815         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
14816         drm_modeset_unlock_all(dev);
14817
14818         for_each_intel_crtc(dev, crtc) {
14819                 struct intel_initial_plane_config plane_config = {};
14820
14821                 if (!crtc->active)
14822                         continue;
14823
14824                 /*
14825                  * Note that reserving the BIOS fb up front prevents us
14826                  * from stuffing other stolen allocations like the ring
14827                  * on top.  This prevents some ugliness at boot time, and
14828                  * can even allow for smooth boot transitions if the BIOS
14829                  * fb is large enough for the active pipe configuration.
14830                  */
14831                 dev_priv->display.get_initial_plane_config(crtc,
14832                                                            &plane_config);
14833
14834                 /*
14835                  * If the fb is shared between multiple heads, we'll
14836                  * just get the first one.
14837                  */
14838                 intel_find_initial_plane_obj(crtc, &plane_config);
14839         }
14840
14841         /*
14842          * Make sure hardware watermarks really match the state we read out.
14843          * Note that we need to do this after reconstructing the BIOS fb's
14844          * since the watermark calculation done here will use pstate->fb.
14845          */
14846         if (!HAS_GMCH_DISPLAY(dev_priv))
14847                 sanitize_watermarks(dev);
14848
14849         return 0;
14850 }
14851
14852 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14853 {
14854         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14855         /* 640x480@60Hz, ~25175 kHz */
14856         struct dpll clock = {
14857                 .m1 = 18,
14858                 .m2 = 7,
14859                 .p1 = 13,
14860                 .p2 = 4,
14861                 .n = 2,
14862         };
14863         u32 dpll, fp;
14864         int i;
14865
14866         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
14867
14868         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
14869                       pipe_name(pipe), clock.vco, clock.dot);
14870
14871         fp = i9xx_dpll_compute_fp(&clock);
14872         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
14873                 DPLL_VGA_MODE_DIS |
14874                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
14875                 PLL_P2_DIVIDE_BY_4 |
14876                 PLL_REF_INPUT_DREFCLK |
14877                 DPLL_VCO_ENABLE;
14878
14879         I915_WRITE(FP0(pipe), fp);
14880         I915_WRITE(FP1(pipe), fp);
14881
14882         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
14883         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
14884         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
14885         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
14886         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
14887         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
14888         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
14889
14890         /*
14891          * Apparently we need to have VGA mode enabled prior to changing
14892          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
14893          * dividers, even though the register value does change.
14894          */
14895         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
14896         I915_WRITE(DPLL(pipe), dpll);
14897
14898         /* Wait for the clocks to stabilize. */
14899         POSTING_READ(DPLL(pipe));
14900         udelay(150);
14901
14902         /* The pixel multiplier can only be updated once the
14903          * DPLL is enabled and the clocks are stable.
14904          *
14905          * So write it again.
14906          */
14907         I915_WRITE(DPLL(pipe), dpll);
14908
14909         /* We do this three times for luck */
14910         for (i = 0; i < 3 ; i++) {
14911                 I915_WRITE(DPLL(pipe), dpll);
14912                 POSTING_READ(DPLL(pipe));
14913                 udelay(150); /* wait for warmup */
14914         }
14915
14916         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
14917         POSTING_READ(PIPECONF(pipe));
14918
14919         intel_wait_for_pipe_scanline_moving(crtc);
14920 }
14921
14922 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14923 {
14924         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14925
14926         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
14927                       pipe_name(pipe));
14928
14929         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
14930         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
14931         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
14932         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & CURSOR_MODE);
14933         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & CURSOR_MODE);
14934
14935         I915_WRITE(PIPECONF(pipe), 0);
14936         POSTING_READ(PIPECONF(pipe));
14937
14938         intel_wait_for_pipe_scanline_stopped(crtc);
14939
14940         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
14941         POSTING_READ(DPLL(pipe));
14942 }
14943
14944 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
14945                                    struct intel_plane *plane)
14946 {
14947         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14948         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
14949         u32 val = I915_READ(DSPCNTR(i9xx_plane));
14950
14951         return (val & DISPLAY_PLANE_ENABLE) == 0 ||
14952                 (val & DISPPLANE_SEL_PIPE_MASK) == DISPPLANE_SEL_PIPE(crtc->pipe);
14953 }
14954
14955 static void
14956 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
14957 {
14958         struct intel_crtc *crtc;
14959
14960         if (INTEL_GEN(dev_priv) >= 4)
14961                 return;
14962
14963         for_each_intel_crtc(&dev_priv->drm, crtc) {
14964                 struct intel_plane *plane =
14965                         to_intel_plane(crtc->base.primary);
14966
14967                 if (intel_plane_mapping_ok(crtc, plane))
14968                         continue;
14969
14970                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
14971                               plane->base.name);
14972                 intel_plane_disable_noatomic(crtc, plane);
14973         }
14974 }
14975
14976 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14977 {
14978         struct drm_device *dev = crtc->base.dev;
14979         struct intel_encoder *encoder;
14980
14981         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14982                 return true;
14983
14984         return false;
14985 }
14986
14987 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
14988 {
14989         struct drm_device *dev = encoder->base.dev;
14990         struct intel_connector *connector;
14991
14992         for_each_connector_on_encoder(dev, &encoder->base, connector)
14993                 return connector;
14994
14995         return NULL;
14996 }
14997
14998 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
14999                               enum pipe pch_transcoder)
15000 {
15001         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15002                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15003 }
15004
15005 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15006                                 struct drm_modeset_acquire_ctx *ctx)
15007 {
15008         struct drm_device *dev = crtc->base.dev;
15009         struct drm_i915_private *dev_priv = to_i915(dev);
15010         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15011
15012         /* Clear any frame start delays used for debugging left by the BIOS */
15013         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15014                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15015
15016                 I915_WRITE(reg,
15017                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15018         }
15019
15020         /* restore vblank interrupts to correct state */
15021         drm_crtc_vblank_reset(&crtc->base);
15022         if (crtc->active) {
15023                 struct intel_plane *plane;
15024
15025                 drm_crtc_vblank_on(&crtc->base);
15026
15027                 /* Disable everything but the primary plane */
15028                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15029                         const struct intel_plane_state *plane_state =
15030                                 to_intel_plane_state(plane->base.state);
15031
15032                         if (plane_state->base.visible &&
15033                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15034                                 intel_plane_disable_noatomic(crtc, plane);
15035                 }
15036         }
15037
15038         /* Adjust the state of the output pipe according to whether we
15039          * have active connectors/encoders. */
15040         if (crtc->active && !intel_crtc_has_encoders(crtc))
15041                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15042
15043         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15044                 /*
15045                  * We start out with underrun reporting disabled to avoid races.
15046                  * For correct bookkeeping mark this on active crtcs.
15047                  *
15048                  * Also on gmch platforms we dont have any hardware bits to
15049                  * disable the underrun reporting. Which means we need to start
15050                  * out with underrun reporting disabled also on inactive pipes,
15051                  * since otherwise we'll complain about the garbage we read when
15052                  * e.g. coming up after runtime pm.
15053                  *
15054                  * No protection against concurrent access is required - at
15055                  * worst a fifo underrun happens which also sets this to false.
15056                  */
15057                 crtc->cpu_fifo_underrun_disabled = true;
15058                 /*
15059                  * We track the PCH trancoder underrun reporting state
15060                  * within the crtc. With crtc for pipe A housing the underrun
15061                  * reporting state for PCH transcoder A, crtc for pipe B housing
15062                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15063                  * and marking underrun reporting as disabled for the non-existing
15064                  * PCH transcoders B and C would prevent enabling the south
15065                  * error interrupt (see cpt_can_enable_serr_int()).
15066                  */
15067                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15068                         crtc->pch_fifo_underrun_disabled = true;
15069         }
15070 }
15071
15072 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15073 {
15074         struct intel_connector *connector;
15075
15076         /* We need to check both for a crtc link (meaning that the
15077          * encoder is active and trying to read from a pipe) and the
15078          * pipe itself being active. */
15079         bool has_active_crtc = encoder->base.crtc &&
15080                 to_intel_crtc(encoder->base.crtc)->active;
15081
15082         connector = intel_encoder_find_connector(encoder);
15083         if (connector && !has_active_crtc) {
15084                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15085                               encoder->base.base.id,
15086                               encoder->base.name);
15087
15088                 /* Connector is active, but has no active pipe. This is
15089                  * fallout from our resume register restoring. Disable
15090                  * the encoder manually again. */
15091                 if (encoder->base.crtc) {
15092                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15093
15094                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15095                                       encoder->base.base.id,
15096                                       encoder->base.name);
15097                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15098                         if (encoder->post_disable)
15099                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15100                 }
15101                 encoder->base.crtc = NULL;
15102
15103                 /* Inconsistent output/port/pipe state happens presumably due to
15104                  * a bug in one of the get_hw_state functions. Or someplace else
15105                  * in our code, like the register restore mess on resume. Clamp
15106                  * things to off as a safer default. */
15107
15108                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15109                 connector->base.encoder = NULL;
15110         }
15111 }
15112
15113 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15114 {
15115         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15116
15117         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15118                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15119                 i915_disable_vga(dev_priv);
15120         }
15121 }
15122
15123 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15124 {
15125         /* This function can be called both from intel_modeset_setup_hw_state or
15126          * at a very early point in our resume sequence, where the power well
15127          * structures are not yet restored. Since this function is at a very
15128          * paranoid "someone might have enabled VGA while we were not looking"
15129          * level, just check if the power well is enabled instead of trying to
15130          * follow the "don't touch the power well if we don't need it" policy
15131          * the rest of the driver uses. */
15132         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15133                 return;
15134
15135         i915_redisable_vga_power_on(dev_priv);
15136
15137         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15138 }
15139
15140 /* FIXME read out full plane state for all planes */
15141 static void readout_plane_state(struct intel_crtc *crtc)
15142 {
15143         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15144         struct intel_crtc_state *crtc_state =
15145                 to_intel_crtc_state(crtc->base.state);
15146         struct intel_plane *plane;
15147
15148         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
15149                 struct intel_plane_state *plane_state =
15150                         to_intel_plane_state(plane->base.state);
15151                 bool visible = plane->get_hw_state(plane);
15152
15153                 intel_set_plane_visible(crtc_state, plane_state, visible);
15154         }
15155 }
15156
15157 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15158 {
15159         struct drm_i915_private *dev_priv = to_i915(dev);
15160         enum pipe pipe;
15161         struct intel_crtc *crtc;
15162         struct intel_encoder *encoder;
15163         struct intel_connector *connector;
15164         struct drm_connector_list_iter conn_iter;
15165         int i;
15166
15167         dev_priv->active_crtcs = 0;
15168
15169         for_each_intel_crtc(dev, crtc) {
15170                 struct intel_crtc_state *crtc_state =
15171                         to_intel_crtc_state(crtc->base.state);
15172
15173                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15174                 memset(crtc_state, 0, sizeof(*crtc_state));
15175                 crtc_state->base.crtc = &crtc->base;
15176
15177                 crtc_state->base.active = crtc_state->base.enable =
15178                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15179
15180                 crtc->base.enabled = crtc_state->base.enable;
15181                 crtc->active = crtc_state->base.active;
15182
15183                 if (crtc_state->base.active)
15184                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15185
15186                 readout_plane_state(crtc);
15187
15188                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15189                               crtc->base.base.id, crtc->base.name,
15190                               enableddisabled(crtc_state->base.active));
15191         }
15192
15193         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15194                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15195
15196                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15197                                                         &pll->state.hw_state);
15198                 pll->state.crtc_mask = 0;
15199                 for_each_intel_crtc(dev, crtc) {
15200                         struct intel_crtc_state *crtc_state =
15201                                 to_intel_crtc_state(crtc->base.state);
15202
15203                         if (crtc_state->base.active &&
15204                             crtc_state->shared_dpll == pll)
15205                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15206                 }
15207                 pll->active_mask = pll->state.crtc_mask;
15208
15209                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15210                               pll->info->name, pll->state.crtc_mask, pll->on);
15211         }
15212
15213         for_each_intel_encoder(dev, encoder) {
15214                 pipe = 0;
15215
15216                 if (encoder->get_hw_state(encoder, &pipe)) {
15217                         struct intel_crtc_state *crtc_state;
15218
15219                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15220                         crtc_state = to_intel_crtc_state(crtc->base.state);
15221
15222                         encoder->base.crtc = &crtc->base;
15223                         encoder->get_config(encoder, crtc_state);
15224                 } else {
15225                         encoder->base.crtc = NULL;
15226                 }
15227
15228                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15229                               encoder->base.base.id, encoder->base.name,
15230                               enableddisabled(encoder->base.crtc),
15231                               pipe_name(pipe));
15232         }
15233
15234         drm_connector_list_iter_begin(dev, &conn_iter);
15235         for_each_intel_connector_iter(connector, &conn_iter) {
15236                 if (connector->get_hw_state(connector)) {
15237                         connector->base.dpms = DRM_MODE_DPMS_ON;
15238
15239                         encoder = connector->encoder;
15240                         connector->base.encoder = &encoder->base;
15241
15242                         if (encoder->base.crtc &&
15243                             encoder->base.crtc->state->active) {
15244                                 /*
15245                                  * This has to be done during hardware readout
15246                                  * because anything calling .crtc_disable may
15247                                  * rely on the connector_mask being accurate.
15248                                  */
15249                                 encoder->base.crtc->state->connector_mask |=
15250                                         1 << drm_connector_index(&connector->base);
15251                                 encoder->base.crtc->state->encoder_mask |=
15252                                         1 << drm_encoder_index(&encoder->base);
15253                         }
15254
15255                 } else {
15256                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15257                         connector->base.encoder = NULL;
15258                 }
15259                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15260                               connector->base.base.id, connector->base.name,
15261                               enableddisabled(connector->base.encoder));
15262         }
15263         drm_connector_list_iter_end(&conn_iter);
15264
15265         for_each_intel_crtc(dev, crtc) {
15266                 struct intel_crtc_state *crtc_state =
15267                         to_intel_crtc_state(crtc->base.state);
15268                 int min_cdclk = 0;
15269
15270                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15271                 if (crtc_state->base.active) {
15272                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15273                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15274                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15275
15276                         /*
15277                          * The initial mode needs to be set in order to keep
15278                          * the atomic core happy. It wants a valid mode if the
15279                          * crtc's enabled, so we do the above call.
15280                          *
15281                          * But we don't set all the derived state fully, hence
15282                          * set a flag to indicate that a full recalculation is
15283                          * needed on the next commit.
15284                          */
15285                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15286
15287                         intel_crtc_compute_pixel_rate(crtc_state);
15288
15289                         if (dev_priv->display.modeset_calc_cdclk) {
15290                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15291                                 if (WARN_ON(min_cdclk < 0))
15292                                         min_cdclk = 0;
15293                         }
15294
15295                         drm_calc_timestamping_constants(&crtc->base,
15296                                                         &crtc_state->base.adjusted_mode);
15297                         update_scanline_offset(crtc);
15298                 }
15299
15300                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15301                 dev_priv->min_voltage_level[crtc->pipe] =
15302                         crtc_state->min_voltage_level;
15303
15304                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15305         }
15306 }
15307
15308 static void
15309 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15310 {
15311         struct intel_encoder *encoder;
15312
15313         for_each_intel_encoder(&dev_priv->drm, encoder) {
15314                 u64 get_domains;
15315                 enum intel_display_power_domain domain;
15316
15317                 if (!encoder->get_power_domains)
15318                         continue;
15319
15320                 get_domains = encoder->get_power_domains(encoder);
15321                 for_each_power_domain(domain, get_domains)
15322                         intel_display_power_get(dev_priv, domain);
15323         }
15324 }
15325
15326 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15327 {
15328         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15329         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15330                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15331                            DARBF_GATING_DIS);
15332
15333         if (IS_HASWELL(dev_priv)) {
15334                 /*
15335                  * WaRsPkgCStateDisplayPMReq:hsw
15336                  * System hang if this isn't done before disabling all planes!
15337                  */
15338                 I915_WRITE(CHICKEN_PAR1_1,
15339                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15340         }
15341 }
15342
15343 /* Scan out the current hw modeset state,
15344  * and sanitizes it to the current state
15345  */
15346 static void
15347 intel_modeset_setup_hw_state(struct drm_device *dev,
15348                              struct drm_modeset_acquire_ctx *ctx)
15349 {
15350         struct drm_i915_private *dev_priv = to_i915(dev);
15351         enum pipe pipe;
15352         struct intel_crtc *crtc;
15353         struct intel_encoder *encoder;
15354         int i;
15355
15356         intel_early_display_was(dev_priv);
15357         intel_modeset_readout_hw_state(dev);
15358
15359         /* HW state is read out, now we need to sanitize this mess. */
15360         get_encoder_power_domains(dev_priv);
15361
15362         intel_sanitize_plane_mapping(dev_priv);
15363
15364         for_each_intel_encoder(dev, encoder) {
15365                 intel_sanitize_encoder(encoder);
15366         }
15367
15368         for_each_pipe(dev_priv, pipe) {
15369                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15370
15371                 intel_sanitize_crtc(crtc, ctx);
15372                 intel_dump_pipe_config(crtc, crtc->config,
15373                                        "[setup_hw_state]");
15374         }
15375
15376         intel_modeset_update_connector_atomic_state(dev);
15377
15378         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15379                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15380
15381                 if (!pll->on || pll->active_mask)
15382                         continue;
15383
15384                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15385                               pll->info->name);
15386
15387                 pll->info->funcs->disable(dev_priv, pll);
15388                 pll->on = false;
15389         }
15390
15391         if (IS_G4X(dev_priv)) {
15392                 g4x_wm_get_hw_state(dev);
15393                 g4x_wm_sanitize(dev_priv);
15394         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15395                 vlv_wm_get_hw_state(dev);
15396                 vlv_wm_sanitize(dev_priv);
15397         } else if (INTEL_GEN(dev_priv) >= 9) {
15398                 skl_wm_get_hw_state(dev);
15399         } else if (HAS_PCH_SPLIT(dev_priv)) {
15400                 ilk_wm_get_hw_state(dev);
15401         }
15402
15403         for_each_intel_crtc(dev, crtc) {
15404                 u64 put_domains;
15405
15406                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15407                 if (WARN_ON(put_domains))
15408                         modeset_put_power_domains(dev_priv, put_domains);
15409         }
15410         intel_display_set_init_power(dev_priv, false);
15411
15412         intel_power_domains_verify_state(dev_priv);
15413
15414         intel_fbc_init_pipe_state(dev_priv);
15415 }
15416
15417 void intel_display_resume(struct drm_device *dev)
15418 {
15419         struct drm_i915_private *dev_priv = to_i915(dev);
15420         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15421         struct drm_modeset_acquire_ctx ctx;
15422         int ret;
15423
15424         dev_priv->modeset_restore_state = NULL;
15425         if (state)
15426                 state->acquire_ctx = &ctx;
15427
15428         drm_modeset_acquire_init(&ctx, 0);
15429
15430         while (1) {
15431                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15432                 if (ret != -EDEADLK)
15433                         break;
15434
15435                 drm_modeset_backoff(&ctx);
15436         }
15437
15438         if (!ret)
15439                 ret = __intel_display_resume(dev, state, &ctx);
15440
15441         intel_enable_ipc(dev_priv);
15442         drm_modeset_drop_locks(&ctx);
15443         drm_modeset_acquire_fini(&ctx);
15444
15445         if (ret)
15446                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15447         if (state)
15448                 drm_atomic_state_put(state);
15449 }
15450
15451 int intel_connector_register(struct drm_connector *connector)
15452 {
15453         struct intel_connector *intel_connector = to_intel_connector(connector);
15454         int ret;
15455
15456         ret = intel_backlight_device_register(intel_connector);
15457         if (ret)
15458                 goto err;
15459
15460         return 0;
15461
15462 err:
15463         return ret;
15464 }
15465
15466 void intel_connector_unregister(struct drm_connector *connector)
15467 {
15468         struct intel_connector *intel_connector = to_intel_connector(connector);
15469
15470         intel_backlight_device_unregister(intel_connector);
15471         intel_panel_destroy_backlight(connector);
15472 }
15473
15474 static void intel_hpd_poll_fini(struct drm_device *dev)
15475 {
15476         struct intel_connector *connector;
15477         struct drm_connector_list_iter conn_iter;
15478
15479         /* Kill all the work that may have been queued by hpd. */
15480         drm_connector_list_iter_begin(dev, &conn_iter);
15481         for_each_intel_connector_iter(connector, &conn_iter) {
15482                 if (connector->modeset_retry_work.func)
15483                         cancel_work_sync(&connector->modeset_retry_work);
15484                 if (connector->hdcp_shim) {
15485                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15486                         cancel_work_sync(&connector->hdcp_prop_work);
15487                 }
15488         }
15489         drm_connector_list_iter_end(&conn_iter);
15490 }
15491
15492 void intel_modeset_cleanup(struct drm_device *dev)
15493 {
15494         struct drm_i915_private *dev_priv = to_i915(dev);
15495
15496         flush_work(&dev_priv->atomic_helper.free_work);
15497         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15498
15499         intel_disable_gt_powersave(dev_priv);
15500
15501         /*
15502          * Interrupts and polling as the first thing to avoid creating havoc.
15503          * Too much stuff here (turning of connectors, ...) would
15504          * experience fancy races otherwise.
15505          */
15506         intel_irq_uninstall(dev_priv);
15507
15508         /*
15509          * Due to the hpd irq storm handling the hotplug work can re-arm the
15510          * poll handlers. Hence disable polling after hpd handling is shut down.
15511          */
15512         intel_hpd_poll_fini(dev);
15513
15514         /* poll work can call into fbdev, hence clean that up afterwards */
15515         intel_fbdev_fini(dev_priv);
15516
15517         intel_unregister_dsm_handler();
15518
15519         intel_fbc_global_disable(dev_priv);
15520
15521         /* flush any delayed tasks or pending work */
15522         flush_scheduled_work();
15523
15524         drm_mode_config_cleanup(dev);
15525
15526         intel_cleanup_overlay(dev_priv);
15527
15528         intel_cleanup_gt_powersave(dev_priv);
15529
15530         intel_teardown_gmbus(dev_priv);
15531
15532         destroy_workqueue(dev_priv->modeset_wq);
15533 }
15534
15535 void intel_connector_attach_encoder(struct intel_connector *connector,
15536                                     struct intel_encoder *encoder)
15537 {
15538         connector->encoder = encoder;
15539         drm_mode_connector_attach_encoder(&connector->base,
15540                                           &encoder->base);
15541 }
15542
15543 /*
15544  * set vga decode state - true == enable VGA decode
15545  */
15546 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15547 {
15548         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15549         u16 gmch_ctrl;
15550
15551         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15552                 DRM_ERROR("failed to read control word\n");
15553                 return -EIO;
15554         }
15555
15556         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15557                 return 0;
15558
15559         if (state)
15560                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15561         else
15562                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15563
15564         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15565                 DRM_ERROR("failed to write control word\n");
15566                 return -EIO;
15567         }
15568
15569         return 0;
15570 }
15571
15572 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15573
15574 struct intel_display_error_state {
15575
15576         u32 power_well_driver;
15577
15578         int num_transcoders;
15579
15580         struct intel_cursor_error_state {
15581                 u32 control;
15582                 u32 position;
15583                 u32 base;
15584                 u32 size;
15585         } cursor[I915_MAX_PIPES];
15586
15587         struct intel_pipe_error_state {
15588                 bool power_domain_on;
15589                 u32 source;
15590                 u32 stat;
15591         } pipe[I915_MAX_PIPES];
15592
15593         struct intel_plane_error_state {
15594                 u32 control;
15595                 u32 stride;
15596                 u32 size;
15597                 u32 pos;
15598                 u32 addr;
15599                 u32 surface;
15600                 u32 tile_offset;
15601         } plane[I915_MAX_PIPES];
15602
15603         struct intel_transcoder_error_state {
15604                 bool power_domain_on;
15605                 enum transcoder cpu_transcoder;
15606
15607                 u32 conf;
15608
15609                 u32 htotal;
15610                 u32 hblank;
15611                 u32 hsync;
15612                 u32 vtotal;
15613                 u32 vblank;
15614                 u32 vsync;
15615         } transcoder[4];
15616 };
15617
15618 struct intel_display_error_state *
15619 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15620 {
15621         struct intel_display_error_state *error;
15622         int transcoders[] = {
15623                 TRANSCODER_A,
15624                 TRANSCODER_B,
15625                 TRANSCODER_C,
15626                 TRANSCODER_EDP,
15627         };
15628         int i;
15629
15630         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15631                 return NULL;
15632
15633         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15634         if (error == NULL)
15635                 return NULL;
15636
15637         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15638                 error->power_well_driver =
15639                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
15640
15641         for_each_pipe(dev_priv, i) {
15642                 error->pipe[i].power_domain_on =
15643                         __intel_display_power_is_enabled(dev_priv,
15644                                                          POWER_DOMAIN_PIPE(i));
15645                 if (!error->pipe[i].power_domain_on)
15646                         continue;
15647
15648                 error->cursor[i].control = I915_READ(CURCNTR(i));
15649                 error->cursor[i].position = I915_READ(CURPOS(i));
15650                 error->cursor[i].base = I915_READ(CURBASE(i));
15651
15652                 error->plane[i].control = I915_READ(DSPCNTR(i));
15653                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15654                 if (INTEL_GEN(dev_priv) <= 3) {
15655                         error->plane[i].size = I915_READ(DSPSIZE(i));
15656                         error->plane[i].pos = I915_READ(DSPPOS(i));
15657                 }
15658                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15659                         error->plane[i].addr = I915_READ(DSPADDR(i));
15660                 if (INTEL_GEN(dev_priv) >= 4) {
15661                         error->plane[i].surface = I915_READ(DSPSURF(i));
15662                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15663                 }
15664
15665                 error->pipe[i].source = I915_READ(PIPESRC(i));
15666
15667                 if (HAS_GMCH_DISPLAY(dev_priv))
15668                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15669         }
15670
15671         /* Note: this does not include DSI transcoders. */
15672         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15673         if (HAS_DDI(dev_priv))
15674                 error->num_transcoders++; /* Account for eDP. */
15675
15676         for (i = 0; i < error->num_transcoders; i++) {
15677                 enum transcoder cpu_transcoder = transcoders[i];
15678
15679                 error->transcoder[i].power_domain_on =
15680                         __intel_display_power_is_enabled(dev_priv,
15681                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15682                 if (!error->transcoder[i].power_domain_on)
15683                         continue;
15684
15685                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15686
15687                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15688                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15689                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15690                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15691                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15692                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15693                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15694         }
15695
15696         return error;
15697 }
15698
15699 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15700
15701 void
15702 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15703                                 struct intel_display_error_state *error)
15704 {
15705         struct drm_i915_private *dev_priv = m->i915;
15706         int i;
15707
15708         if (!error)
15709                 return;
15710
15711         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15712         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15713                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15714                            error->power_well_driver);
15715         for_each_pipe(dev_priv, i) {
15716                 err_printf(m, "Pipe [%d]:\n", i);
15717                 err_printf(m, "  Power: %s\n",
15718                            onoff(error->pipe[i].power_domain_on));
15719                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15720                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15721
15722                 err_printf(m, "Plane [%d]:\n", i);
15723                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15724                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15725                 if (INTEL_GEN(dev_priv) <= 3) {
15726                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15727                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15728                 }
15729                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15730                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15731                 if (INTEL_GEN(dev_priv) >= 4) {
15732                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15733                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15734                 }
15735
15736                 err_printf(m, "Cursor [%d]:\n", i);
15737                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15738                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15739                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15740         }
15741
15742         for (i = 0; i < error->num_transcoders; i++) {
15743                 err_printf(m, "CPU transcoder: %s\n",
15744                            transcoder_name(error->transcoder[i].cpu_transcoder));
15745                 err_printf(m, "  Power: %s\n",
15746                            onoff(error->transcoder[i].power_domain_on));
15747                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15748                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15749                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15750                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15751                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15752                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15753                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15754         }
15755 }
15756
15757 #endif