Merge branch 'sched-core-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[linux-2.6-microblaze.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_clflush.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 /* Primary plane formats for gen <= 3 */
53 static const uint32_t i8xx_primary_formats[] = {
54         DRM_FORMAT_C8,
55         DRM_FORMAT_RGB565,
56         DRM_FORMAT_XRGB1555,
57         DRM_FORMAT_XRGB8888,
58 };
59
60 /* Primary plane formats for gen >= 4 */
61 static const uint32_t i965_primary_formats[] = {
62         DRM_FORMAT_C8,
63         DRM_FORMAT_RGB565,
64         DRM_FORMAT_XRGB8888,
65         DRM_FORMAT_XBGR8888,
66         DRM_FORMAT_XRGB2101010,
67         DRM_FORMAT_XBGR2101010,
68 };
69
70 static const uint64_t i9xx_format_modifiers[] = {
71         I915_FORMAT_MOD_X_TILED,
72         DRM_FORMAT_MOD_LINEAR,
73         DRM_FORMAT_MOD_INVALID
74 };
75
76 static const uint32_t skl_primary_formats[] = {
77         DRM_FORMAT_C8,
78         DRM_FORMAT_RGB565,
79         DRM_FORMAT_XRGB8888,
80         DRM_FORMAT_XBGR8888,
81         DRM_FORMAT_ARGB8888,
82         DRM_FORMAT_ABGR8888,
83         DRM_FORMAT_XRGB2101010,
84         DRM_FORMAT_XBGR2101010,
85         DRM_FORMAT_YUYV,
86         DRM_FORMAT_YVYU,
87         DRM_FORMAT_UYVY,
88         DRM_FORMAT_VYUY,
89 };
90
91 static const uint32_t skl_pri_planar_formats[] = {
92         DRM_FORMAT_C8,
93         DRM_FORMAT_RGB565,
94         DRM_FORMAT_XRGB8888,
95         DRM_FORMAT_XBGR8888,
96         DRM_FORMAT_ARGB8888,
97         DRM_FORMAT_ABGR8888,
98         DRM_FORMAT_XRGB2101010,
99         DRM_FORMAT_XBGR2101010,
100         DRM_FORMAT_YUYV,
101         DRM_FORMAT_YVYU,
102         DRM_FORMAT_UYVY,
103         DRM_FORMAT_VYUY,
104         DRM_FORMAT_NV12,
105 };
106
107 static const uint64_t skl_format_modifiers_noccs[] = {
108         I915_FORMAT_MOD_Yf_TILED,
109         I915_FORMAT_MOD_Y_TILED,
110         I915_FORMAT_MOD_X_TILED,
111         DRM_FORMAT_MOD_LINEAR,
112         DRM_FORMAT_MOD_INVALID
113 };
114
115 static const uint64_t skl_format_modifiers_ccs[] = {
116         I915_FORMAT_MOD_Yf_TILED_CCS,
117         I915_FORMAT_MOD_Y_TILED_CCS,
118         I915_FORMAT_MOD_Yf_TILED,
119         I915_FORMAT_MOD_Y_TILED,
120         I915_FORMAT_MOD_X_TILED,
121         DRM_FORMAT_MOD_LINEAR,
122         DRM_FORMAT_MOD_INVALID
123 };
124
125 /* Cursor formats */
126 static const uint32_t intel_cursor_formats[] = {
127         DRM_FORMAT_ARGB8888,
128 };
129
130 static const uint64_t cursor_format_modifiers[] = {
131         DRM_FORMAT_MOD_LINEAR,
132         DRM_FORMAT_MOD_INVALID
133 };
134
135 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
136                                 struct intel_crtc_state *pipe_config);
137 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
138                                    struct intel_crtc_state *pipe_config);
139
140 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
141                                   struct drm_i915_gem_object *obj,
142                                   struct drm_mode_fb_cmd2 *mode_cmd);
143 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
144 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
145 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
146 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
147                                          struct intel_link_m_n *m_n,
148                                          struct intel_link_m_n *m2_n2);
149 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
150 static void haswell_set_pipeconf(struct drm_crtc *crtc);
151 static void haswell_set_pipemisc(struct drm_crtc *crtc);
152 static void vlv_prepare_pll(struct intel_crtc *crtc,
153                             const struct intel_crtc_state *pipe_config);
154 static void chv_prepare_pll(struct intel_crtc *crtc,
155                             const struct intel_crtc_state *pipe_config);
156 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
157 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
158 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
159                                     struct intel_crtc_state *crtc_state);
160 static void skylake_pfit_enable(struct intel_crtc *crtc);
161 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
162 static void ironlake_pfit_enable(struct intel_crtc *crtc);
163 static void intel_modeset_setup_hw_state(struct drm_device *dev,
164                                          struct drm_modeset_acquire_ctx *ctx);
165 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
166
167 struct intel_limit {
168         struct {
169                 int min, max;
170         } dot, vco, n, m, m1, m2, p, p1;
171
172         struct {
173                 int dot_limit;
174                 int p2_slow, p2_fast;
175         } p2;
176 };
177
178 /* returns HPLL frequency in kHz */
179 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
180 {
181         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
182
183         /* Obtain SKU information */
184         mutex_lock(&dev_priv->sb_lock);
185         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
186                 CCK_FUSE_HPLL_FREQ_MASK;
187         mutex_unlock(&dev_priv->sb_lock);
188
189         return vco_freq[hpll_freq] * 1000;
190 }
191
192 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
193                       const char *name, u32 reg, int ref_freq)
194 {
195         u32 val;
196         int divider;
197
198         mutex_lock(&dev_priv->sb_lock);
199         val = vlv_cck_read(dev_priv, reg);
200         mutex_unlock(&dev_priv->sb_lock);
201
202         divider = val & CCK_FREQUENCY_VALUES;
203
204         WARN((val & CCK_FREQUENCY_STATUS) !=
205              (divider << CCK_FREQUENCY_STATUS_SHIFT),
206              "%s change in progress\n", name);
207
208         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
209 }
210
211 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
212                            const char *name, u32 reg)
213 {
214         if (dev_priv->hpll_freq == 0)
215                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
216
217         return vlv_get_cck_clock(dev_priv, name, reg,
218                                  dev_priv->hpll_freq);
219 }
220
221 static void intel_update_czclk(struct drm_i915_private *dev_priv)
222 {
223         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
224                 return;
225
226         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
227                                                       CCK_CZ_CLOCK_CONTROL);
228
229         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
230 }
231
232 static inline u32 /* units of 100MHz */
233 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
234                     const struct intel_crtc_state *pipe_config)
235 {
236         if (HAS_DDI(dev_priv))
237                 return pipe_config->port_clock; /* SPLL */
238         else
239                 return dev_priv->fdi_pll_freq;
240 }
241
242 static const struct intel_limit intel_limits_i8xx_dac = {
243         .dot = { .min = 25000, .max = 350000 },
244         .vco = { .min = 908000, .max = 1512000 },
245         .n = { .min = 2, .max = 16 },
246         .m = { .min = 96, .max = 140 },
247         .m1 = { .min = 18, .max = 26 },
248         .m2 = { .min = 6, .max = 16 },
249         .p = { .min = 4, .max = 128 },
250         .p1 = { .min = 2, .max = 33 },
251         .p2 = { .dot_limit = 165000,
252                 .p2_slow = 4, .p2_fast = 2 },
253 };
254
255 static const struct intel_limit intel_limits_i8xx_dvo = {
256         .dot = { .min = 25000, .max = 350000 },
257         .vco = { .min = 908000, .max = 1512000 },
258         .n = { .min = 2, .max = 16 },
259         .m = { .min = 96, .max = 140 },
260         .m1 = { .min = 18, .max = 26 },
261         .m2 = { .min = 6, .max = 16 },
262         .p = { .min = 4, .max = 128 },
263         .p1 = { .min = 2, .max = 33 },
264         .p2 = { .dot_limit = 165000,
265                 .p2_slow = 4, .p2_fast = 4 },
266 };
267
268 static const struct intel_limit intel_limits_i8xx_lvds = {
269         .dot = { .min = 25000, .max = 350000 },
270         .vco = { .min = 908000, .max = 1512000 },
271         .n = { .min = 2, .max = 16 },
272         .m = { .min = 96, .max = 140 },
273         .m1 = { .min = 18, .max = 26 },
274         .m2 = { .min = 6, .max = 16 },
275         .p = { .min = 4, .max = 128 },
276         .p1 = { .min = 1, .max = 6 },
277         .p2 = { .dot_limit = 165000,
278                 .p2_slow = 14, .p2_fast = 7 },
279 };
280
281 static const struct intel_limit intel_limits_i9xx_sdvo = {
282         .dot = { .min = 20000, .max = 400000 },
283         .vco = { .min = 1400000, .max = 2800000 },
284         .n = { .min = 1, .max = 6 },
285         .m = { .min = 70, .max = 120 },
286         .m1 = { .min = 8, .max = 18 },
287         .m2 = { .min = 3, .max = 7 },
288         .p = { .min = 5, .max = 80 },
289         .p1 = { .min = 1, .max = 8 },
290         .p2 = { .dot_limit = 200000,
291                 .p2_slow = 10, .p2_fast = 5 },
292 };
293
294 static const struct intel_limit intel_limits_i9xx_lvds = {
295         .dot = { .min = 20000, .max = 400000 },
296         .vco = { .min = 1400000, .max = 2800000 },
297         .n = { .min = 1, .max = 6 },
298         .m = { .min = 70, .max = 120 },
299         .m1 = { .min = 8, .max = 18 },
300         .m2 = { .min = 3, .max = 7 },
301         .p = { .min = 7, .max = 98 },
302         .p1 = { .min = 1, .max = 8 },
303         .p2 = { .dot_limit = 112000,
304                 .p2_slow = 14, .p2_fast = 7 },
305 };
306
307
308 static const struct intel_limit intel_limits_g4x_sdvo = {
309         .dot = { .min = 25000, .max = 270000 },
310         .vco = { .min = 1750000, .max = 3500000},
311         .n = { .min = 1, .max = 4 },
312         .m = { .min = 104, .max = 138 },
313         .m1 = { .min = 17, .max = 23 },
314         .m2 = { .min = 5, .max = 11 },
315         .p = { .min = 10, .max = 30 },
316         .p1 = { .min = 1, .max = 3},
317         .p2 = { .dot_limit = 270000,
318                 .p2_slow = 10,
319                 .p2_fast = 10
320         },
321 };
322
323 static const struct intel_limit intel_limits_g4x_hdmi = {
324         .dot = { .min = 22000, .max = 400000 },
325         .vco = { .min = 1750000, .max = 3500000},
326         .n = { .min = 1, .max = 4 },
327         .m = { .min = 104, .max = 138 },
328         .m1 = { .min = 16, .max = 23 },
329         .m2 = { .min = 5, .max = 11 },
330         .p = { .min = 5, .max = 80 },
331         .p1 = { .min = 1, .max = 8},
332         .p2 = { .dot_limit = 165000,
333                 .p2_slow = 10, .p2_fast = 5 },
334 };
335
336 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
337         .dot = { .min = 20000, .max = 115000 },
338         .vco = { .min = 1750000, .max = 3500000 },
339         .n = { .min = 1, .max = 3 },
340         .m = { .min = 104, .max = 138 },
341         .m1 = { .min = 17, .max = 23 },
342         .m2 = { .min = 5, .max = 11 },
343         .p = { .min = 28, .max = 112 },
344         .p1 = { .min = 2, .max = 8 },
345         .p2 = { .dot_limit = 0,
346                 .p2_slow = 14, .p2_fast = 14
347         },
348 };
349
350 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
351         .dot = { .min = 80000, .max = 224000 },
352         .vco = { .min = 1750000, .max = 3500000 },
353         .n = { .min = 1, .max = 3 },
354         .m = { .min = 104, .max = 138 },
355         .m1 = { .min = 17, .max = 23 },
356         .m2 = { .min = 5, .max = 11 },
357         .p = { .min = 14, .max = 42 },
358         .p1 = { .min = 2, .max = 6 },
359         .p2 = { .dot_limit = 0,
360                 .p2_slow = 7, .p2_fast = 7
361         },
362 };
363
364 static const struct intel_limit intel_limits_pineview_sdvo = {
365         .dot = { .min = 20000, .max = 400000},
366         .vco = { .min = 1700000, .max = 3500000 },
367         /* Pineview's Ncounter is a ring counter */
368         .n = { .min = 3, .max = 6 },
369         .m = { .min = 2, .max = 256 },
370         /* Pineview only has one combined m divider, which we treat as m2. */
371         .m1 = { .min = 0, .max = 0 },
372         .m2 = { .min = 0, .max = 254 },
373         .p = { .min = 5, .max = 80 },
374         .p1 = { .min = 1, .max = 8 },
375         .p2 = { .dot_limit = 200000,
376                 .p2_slow = 10, .p2_fast = 5 },
377 };
378
379 static const struct intel_limit intel_limits_pineview_lvds = {
380         .dot = { .min = 20000, .max = 400000 },
381         .vco = { .min = 1700000, .max = 3500000 },
382         .n = { .min = 3, .max = 6 },
383         .m = { .min = 2, .max = 256 },
384         .m1 = { .min = 0, .max = 0 },
385         .m2 = { .min = 0, .max = 254 },
386         .p = { .min = 7, .max = 112 },
387         .p1 = { .min = 1, .max = 8 },
388         .p2 = { .dot_limit = 112000,
389                 .p2_slow = 14, .p2_fast = 14 },
390 };
391
392 /* Ironlake / Sandybridge
393  *
394  * We calculate clock using (register_value + 2) for N/M1/M2, so here
395  * the range value for them is (actual_value - 2).
396  */
397 static const struct intel_limit intel_limits_ironlake_dac = {
398         .dot = { .min = 25000, .max = 350000 },
399         .vco = { .min = 1760000, .max = 3510000 },
400         .n = { .min = 1, .max = 5 },
401         .m = { .min = 79, .max = 127 },
402         .m1 = { .min = 12, .max = 22 },
403         .m2 = { .min = 5, .max = 9 },
404         .p = { .min = 5, .max = 80 },
405         .p1 = { .min = 1, .max = 8 },
406         .p2 = { .dot_limit = 225000,
407                 .p2_slow = 10, .p2_fast = 5 },
408 };
409
410 static const struct intel_limit intel_limits_ironlake_single_lvds = {
411         .dot = { .min = 25000, .max = 350000 },
412         .vco = { .min = 1760000, .max = 3510000 },
413         .n = { .min = 1, .max = 3 },
414         .m = { .min = 79, .max = 118 },
415         .m1 = { .min = 12, .max = 22 },
416         .m2 = { .min = 5, .max = 9 },
417         .p = { .min = 28, .max = 112 },
418         .p1 = { .min = 2, .max = 8 },
419         .p2 = { .dot_limit = 225000,
420                 .p2_slow = 14, .p2_fast = 14 },
421 };
422
423 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
424         .dot = { .min = 25000, .max = 350000 },
425         .vco = { .min = 1760000, .max = 3510000 },
426         .n = { .min = 1, .max = 3 },
427         .m = { .min = 79, .max = 127 },
428         .m1 = { .min = 12, .max = 22 },
429         .m2 = { .min = 5, .max = 9 },
430         .p = { .min = 14, .max = 56 },
431         .p1 = { .min = 2, .max = 8 },
432         .p2 = { .dot_limit = 225000,
433                 .p2_slow = 7, .p2_fast = 7 },
434 };
435
436 /* LVDS 100mhz refclk limits. */
437 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
438         .dot = { .min = 25000, .max = 350000 },
439         .vco = { .min = 1760000, .max = 3510000 },
440         .n = { .min = 1, .max = 2 },
441         .m = { .min = 79, .max = 126 },
442         .m1 = { .min = 12, .max = 22 },
443         .m2 = { .min = 5, .max = 9 },
444         .p = { .min = 28, .max = 112 },
445         .p1 = { .min = 2, .max = 8 },
446         .p2 = { .dot_limit = 225000,
447                 .p2_slow = 14, .p2_fast = 14 },
448 };
449
450 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
451         .dot = { .min = 25000, .max = 350000 },
452         .vco = { .min = 1760000, .max = 3510000 },
453         .n = { .min = 1, .max = 3 },
454         .m = { .min = 79, .max = 126 },
455         .m1 = { .min = 12, .max = 22 },
456         .m2 = { .min = 5, .max = 9 },
457         .p = { .min = 14, .max = 42 },
458         .p1 = { .min = 2, .max = 6 },
459         .p2 = { .dot_limit = 225000,
460                 .p2_slow = 7, .p2_fast = 7 },
461 };
462
463 static const struct intel_limit intel_limits_vlv = {
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 = 270000 * 5 },
471         .vco = { .min = 4000000, .max = 6000000 },
472         .n = { .min = 1, .max = 7 },
473         .m1 = { .min = 2, .max = 3 },
474         .m2 = { .min = 11, .max = 156 },
475         .p1 = { .min = 2, .max = 3 },
476         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
477 };
478
479 static const struct intel_limit intel_limits_chv = {
480         /*
481          * These are the data rate limits (measured in fast clocks)
482          * since those are the strictest limits we have.  The fast
483          * clock and actual rate limits are more relaxed, so checking
484          * them would make no difference.
485          */
486         .dot = { .min = 25000 * 5, .max = 540000 * 5},
487         .vco = { .min = 4800000, .max = 6480000 },
488         .n = { .min = 1, .max = 1 },
489         .m1 = { .min = 2, .max = 2 },
490         .m2 = { .min = 24 << 22, .max = 175 << 22 },
491         .p1 = { .min = 2, .max = 4 },
492         .p2 = { .p2_slow = 1, .p2_fast = 14 },
493 };
494
495 static const struct intel_limit intel_limits_bxt = {
496         /* FIXME: find real dot limits */
497         .dot = { .min = 0, .max = INT_MAX },
498         .vco = { .min = 4800000, .max = 6700000 },
499         .n = { .min = 1, .max = 1 },
500         .m1 = { .min = 2, .max = 2 },
501         /* FIXME: find real m2 limits */
502         .m2 = { .min = 2 << 22, .max = 255 << 22 },
503         .p1 = { .min = 2, .max = 4 },
504         .p2 = { .p2_slow = 1, .p2_fast = 20 },
505 };
506
507 static void
508 skl_wa_528(struct drm_i915_private *dev_priv, int pipe, bool enable)
509 {
510         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
511                 return;
512
513         if (enable)
514                 I915_WRITE(CHICKEN_PIPESL_1(pipe), HSW_FBCQ_DIS);
515         else
516                 I915_WRITE(CHICKEN_PIPESL_1(pipe), 0);
517 }
518
519 static void
520 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
521 {
522         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
523                 return;
524
525         if (enable)
526                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
527                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
528         else
529                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
530                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
531                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
532 }
533
534 static bool
535 needs_modeset(const struct drm_crtc_state *state)
536 {
537         return drm_atomic_crtc_needs_modeset(state);
538 }
539
540 /*
541  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
542  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
543  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
544  * The helpers' return value is the rate of the clock that is fed to the
545  * display engine's pipe which can be the above fast dot clock rate or a
546  * divided-down version of it.
547  */
548 /* m1 is reserved as 0 in Pineview, n is a ring counter */
549 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
550 {
551         clock->m = clock->m2 + 2;
552         clock->p = clock->p1 * clock->p2;
553         if (WARN_ON(clock->n == 0 || clock->p == 0))
554                 return 0;
555         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
556         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
557
558         return clock->dot;
559 }
560
561 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
562 {
563         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
564 }
565
566 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
567 {
568         clock->m = i9xx_dpll_compute_m(clock);
569         clock->p = clock->p1 * clock->p2;
570         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
571                 return 0;
572         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
573         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
574
575         return clock->dot;
576 }
577
578 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
579 {
580         clock->m = clock->m1 * clock->m2;
581         clock->p = clock->p1 * clock->p2;
582         if (WARN_ON(clock->n == 0 || clock->p == 0))
583                 return 0;
584         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
585         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
586
587         return clock->dot / 5;
588 }
589
590 int chv_calc_dpll_params(int refclk, struct dpll *clock)
591 {
592         clock->m = clock->m1 * clock->m2;
593         clock->p = clock->p1 * clock->p2;
594         if (WARN_ON(clock->n == 0 || clock->p == 0))
595                 return 0;
596         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
597                         clock->n << 22);
598         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
599
600         return clock->dot / 5;
601 }
602
603 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
604
605 /*
606  * Returns whether the given set of divisors are valid for a given refclk with
607  * the given connectors.
608  */
609 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
610                                const struct intel_limit *limit,
611                                const struct dpll *clock)
612 {
613         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
614                 INTELPllInvalid("n out of range\n");
615         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
616                 INTELPllInvalid("p1 out of range\n");
617         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
618                 INTELPllInvalid("m2 out of range\n");
619         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
620                 INTELPllInvalid("m1 out of range\n");
621
622         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
623             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
624                 if (clock->m1 <= clock->m2)
625                         INTELPllInvalid("m1 <= m2\n");
626
627         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
628             !IS_GEN9_LP(dev_priv)) {
629                 if (clock->p < limit->p.min || limit->p.max < clock->p)
630                         INTELPllInvalid("p out of range\n");
631                 if (clock->m < limit->m.min || limit->m.max < clock->m)
632                         INTELPllInvalid("m out of range\n");
633         }
634
635         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
636                 INTELPllInvalid("vco out of range\n");
637         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
638          * connector, etc., rather than just a single range.
639          */
640         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
641                 INTELPllInvalid("dot out of range\n");
642
643         return true;
644 }
645
646 static int
647 i9xx_select_p2_div(const struct intel_limit *limit,
648                    const struct intel_crtc_state *crtc_state,
649                    int target)
650 {
651         struct drm_device *dev = crtc_state->base.crtc->dev;
652
653         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
654                 /*
655                  * For LVDS just rely on its current settings for dual-channel.
656                  * We haven't figured out how to reliably set up different
657                  * single/dual channel state, if we even can.
658                  */
659                 if (intel_is_dual_link_lvds(dev))
660                         return limit->p2.p2_fast;
661                 else
662                         return limit->p2.p2_slow;
663         } else {
664                 if (target < limit->p2.dot_limit)
665                         return limit->p2.p2_slow;
666                 else
667                         return limit->p2.p2_fast;
668         }
669 }
670
671 /*
672  * Returns a set of divisors for the desired target clock with the given
673  * refclk, or FALSE.  The returned values represent the clock equation:
674  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
675  *
676  * Target and reference clocks are specified in kHz.
677  *
678  * If match_clock is provided, then best_clock P divider must match the P
679  * divider from @match_clock used for LVDS downclocking.
680  */
681 static bool
682 i9xx_find_best_dpll(const struct intel_limit *limit,
683                     struct intel_crtc_state *crtc_state,
684                     int target, int refclk, struct dpll *match_clock,
685                     struct dpll *best_clock)
686 {
687         struct drm_device *dev = crtc_state->base.crtc->dev;
688         struct dpll clock;
689         int err = target;
690
691         memset(best_clock, 0, sizeof(*best_clock));
692
693         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
694
695         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
696              clock.m1++) {
697                 for (clock.m2 = limit->m2.min;
698                      clock.m2 <= limit->m2.max; clock.m2++) {
699                         if (clock.m2 >= clock.m1)
700                                 break;
701                         for (clock.n = limit->n.min;
702                              clock.n <= limit->n.max; clock.n++) {
703                                 for (clock.p1 = limit->p1.min;
704                                         clock.p1 <= limit->p1.max; clock.p1++) {
705                                         int this_err;
706
707                                         i9xx_calc_dpll_params(refclk, &clock);
708                                         if (!intel_PLL_is_valid(to_i915(dev),
709                                                                 limit,
710                                                                 &clock))
711                                                 continue;
712                                         if (match_clock &&
713                                             clock.p != match_clock->p)
714                                                 continue;
715
716                                         this_err = abs(clock.dot - target);
717                                         if (this_err < err) {
718                                                 *best_clock = clock;
719                                                 err = this_err;
720                                         }
721                                 }
722                         }
723                 }
724         }
725
726         return (err != target);
727 }
728
729 /*
730  * Returns a set of divisors for the desired target clock with the given
731  * refclk, or FALSE.  The returned values represent the clock equation:
732  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
733  *
734  * Target and reference clocks are specified in kHz.
735  *
736  * If match_clock is provided, then best_clock P divider must match the P
737  * divider from @match_clock used for LVDS downclocking.
738  */
739 static bool
740 pnv_find_best_dpll(const struct intel_limit *limit,
741                    struct intel_crtc_state *crtc_state,
742                    int target, int refclk, struct dpll *match_clock,
743                    struct dpll *best_clock)
744 {
745         struct drm_device *dev = crtc_state->base.crtc->dev;
746         struct dpll clock;
747         int err = target;
748
749         memset(best_clock, 0, sizeof(*best_clock));
750
751         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
752
753         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
754              clock.m1++) {
755                 for (clock.m2 = limit->m2.min;
756                      clock.m2 <= limit->m2.max; clock.m2++) {
757                         for (clock.n = limit->n.min;
758                              clock.n <= limit->n.max; clock.n++) {
759                                 for (clock.p1 = limit->p1.min;
760                                         clock.p1 <= limit->p1.max; clock.p1++) {
761                                         int this_err;
762
763                                         pnv_calc_dpll_params(refclk, &clock);
764                                         if (!intel_PLL_is_valid(to_i915(dev),
765                                                                 limit,
766                                                                 &clock))
767                                                 continue;
768                                         if (match_clock &&
769                                             clock.p != match_clock->p)
770                                                 continue;
771
772                                         this_err = abs(clock.dot - target);
773                                         if (this_err < err) {
774                                                 *best_clock = clock;
775                                                 err = this_err;
776                                         }
777                                 }
778                         }
779                 }
780         }
781
782         return (err != target);
783 }
784
785 /*
786  * Returns a set of divisors for the desired target clock with the given
787  * refclk, or FALSE.  The returned values represent the clock equation:
788  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
789  *
790  * Target and reference clocks are specified in kHz.
791  *
792  * If match_clock is provided, then best_clock P divider must match the P
793  * divider from @match_clock used for LVDS downclocking.
794  */
795 static bool
796 g4x_find_best_dpll(const struct intel_limit *limit,
797                    struct intel_crtc_state *crtc_state,
798                    int target, int refclk, struct dpll *match_clock,
799                    struct dpll *best_clock)
800 {
801         struct drm_device *dev = crtc_state->base.crtc->dev;
802         struct dpll clock;
803         int max_n;
804         bool found = false;
805         /* approximately equals target * 0.00585 */
806         int err_most = (target >> 8) + (target >> 9);
807
808         memset(best_clock, 0, sizeof(*best_clock));
809
810         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
811
812         max_n = limit->n.max;
813         /* based on hardware requirement, prefer smaller n to precision */
814         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
815                 /* based on hardware requirement, prefere larger m1,m2 */
816                 for (clock.m1 = limit->m1.max;
817                      clock.m1 >= limit->m1.min; clock.m1--) {
818                         for (clock.m2 = limit->m2.max;
819                              clock.m2 >= limit->m2.min; clock.m2--) {
820                                 for (clock.p1 = limit->p1.max;
821                                      clock.p1 >= limit->p1.min; clock.p1--) {
822                                         int this_err;
823
824                                         i9xx_calc_dpll_params(refclk, &clock);
825                                         if (!intel_PLL_is_valid(to_i915(dev),
826                                                                 limit,
827                                                                 &clock))
828                                                 continue;
829
830                                         this_err = abs(clock.dot - target);
831                                         if (this_err < err_most) {
832                                                 *best_clock = clock;
833                                                 err_most = this_err;
834                                                 max_n = clock.n;
835                                                 found = true;
836                                         }
837                                 }
838                         }
839                 }
840         }
841         return found;
842 }
843
844 /*
845  * Check if the calculated PLL configuration is more optimal compared to the
846  * best configuration and error found so far. Return the calculated error.
847  */
848 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
849                                const struct dpll *calculated_clock,
850                                const struct dpll *best_clock,
851                                unsigned int best_error_ppm,
852                                unsigned int *error_ppm)
853 {
854         /*
855          * For CHV ignore the error and consider only the P value.
856          * Prefer a bigger P value based on HW requirements.
857          */
858         if (IS_CHERRYVIEW(to_i915(dev))) {
859                 *error_ppm = 0;
860
861                 return calculated_clock->p > best_clock->p;
862         }
863
864         if (WARN_ON_ONCE(!target_freq))
865                 return false;
866
867         *error_ppm = div_u64(1000000ULL *
868                                 abs(target_freq - calculated_clock->dot),
869                              target_freq);
870         /*
871          * Prefer a better P value over a better (smaller) error if the error
872          * is small. Ensure this preference for future configurations too by
873          * setting the error to 0.
874          */
875         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
876                 *error_ppm = 0;
877
878                 return true;
879         }
880
881         return *error_ppm + 10 < best_error_ppm;
882 }
883
884 /*
885  * Returns a set of divisors for the desired target clock with the given
886  * refclk, or FALSE.  The returned values represent the clock equation:
887  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
888  */
889 static bool
890 vlv_find_best_dpll(const struct intel_limit *limit,
891                    struct intel_crtc_state *crtc_state,
892                    int target, int refclk, struct dpll *match_clock,
893                    struct dpll *best_clock)
894 {
895         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
896         struct drm_device *dev = crtc->base.dev;
897         struct dpll clock;
898         unsigned int bestppm = 1000000;
899         /* min update 19.2 MHz */
900         int max_n = min(limit->n.max, refclk / 19200);
901         bool found = false;
902
903         target *= 5; /* fast clock */
904
905         memset(best_clock, 0, sizeof(*best_clock));
906
907         /* based on hardware requirement, prefer smaller n to precision */
908         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
909                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
910                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
911                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
912                                 clock.p = clock.p1 * clock.p2;
913                                 /* based on hardware requirement, prefer bigger m1,m2 values */
914                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
915                                         unsigned int ppm;
916
917                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
918                                                                      refclk * clock.m1);
919
920                                         vlv_calc_dpll_params(refclk, &clock);
921
922                                         if (!intel_PLL_is_valid(to_i915(dev),
923                                                                 limit,
924                                                                 &clock))
925                                                 continue;
926
927                                         if (!vlv_PLL_is_optimal(dev, target,
928                                                                 &clock,
929                                                                 best_clock,
930                                                                 bestppm, &ppm))
931                                                 continue;
932
933                                         *best_clock = clock;
934                                         bestppm = ppm;
935                                         found = true;
936                                 }
937                         }
938                 }
939         }
940
941         return found;
942 }
943
944 /*
945  * Returns a set of divisors for the desired target clock with the given
946  * refclk, or FALSE.  The returned values represent the clock equation:
947  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
948  */
949 static bool
950 chv_find_best_dpll(const struct intel_limit *limit,
951                    struct intel_crtc_state *crtc_state,
952                    int target, int refclk, struct dpll *match_clock,
953                    struct dpll *best_clock)
954 {
955         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
956         struct drm_device *dev = crtc->base.dev;
957         unsigned int best_error_ppm;
958         struct dpll clock;
959         uint64_t m2;
960         int found = false;
961
962         memset(best_clock, 0, sizeof(*best_clock));
963         best_error_ppm = 1000000;
964
965         /*
966          * Based on hardware doc, the n always set to 1, and m1 always
967          * set to 2.  If requires to support 200Mhz refclk, we need to
968          * revisit this because n may not 1 anymore.
969          */
970         clock.n = 1, clock.m1 = 2;
971         target *= 5;    /* fast clock */
972
973         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
974                 for (clock.p2 = limit->p2.p2_fast;
975                                 clock.p2 >= limit->p2.p2_slow;
976                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
977                         unsigned int error_ppm;
978
979                         clock.p = clock.p1 * clock.p2;
980
981                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
982                                         clock.n) << 22, refclk * clock.m1);
983
984                         if (m2 > INT_MAX/clock.m1)
985                                 continue;
986
987                         clock.m2 = m2;
988
989                         chv_calc_dpll_params(refclk, &clock);
990
991                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
992                                 continue;
993
994                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
995                                                 best_error_ppm, &error_ppm))
996                                 continue;
997
998                         *best_clock = clock;
999                         best_error_ppm = error_ppm;
1000                         found = true;
1001                 }
1002         }
1003
1004         return found;
1005 }
1006
1007 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1008                         struct dpll *best_clock)
1009 {
1010         int refclk = 100000;
1011         const struct intel_limit *limit = &intel_limits_bxt;
1012
1013         return chv_find_best_dpll(limit, crtc_state,
1014                                   target_clock, refclk, NULL, best_clock);
1015 }
1016
1017 bool intel_crtc_active(struct intel_crtc *crtc)
1018 {
1019         /* Be paranoid as we can arrive here with only partial
1020          * state retrieved from the hardware during setup.
1021          *
1022          * We can ditch the adjusted_mode.crtc_clock check as soon
1023          * as Haswell has gained clock readout/fastboot support.
1024          *
1025          * We can ditch the crtc->primary->fb check as soon as we can
1026          * properly reconstruct framebuffers.
1027          *
1028          * FIXME: The intel_crtc->active here should be switched to
1029          * crtc->state->active once we have proper CRTC states wired up
1030          * for atomic.
1031          */
1032         return crtc->active && crtc->base.primary->state->fb &&
1033                 crtc->config->base.adjusted_mode.crtc_clock;
1034 }
1035
1036 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1037                                              enum pipe pipe)
1038 {
1039         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1040
1041         return crtc->config->cpu_transcoder;
1042 }
1043
1044 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1045                                     enum pipe pipe)
1046 {
1047         i915_reg_t reg = PIPEDSL(pipe);
1048         u32 line1, line2;
1049         u32 line_mask;
1050
1051         if (IS_GEN2(dev_priv))
1052                 line_mask = DSL_LINEMASK_GEN2;
1053         else
1054                 line_mask = DSL_LINEMASK_GEN3;
1055
1056         line1 = I915_READ(reg) & line_mask;
1057         msleep(5);
1058         line2 = I915_READ(reg) & line_mask;
1059
1060         return line1 != line2;
1061 }
1062
1063 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1064 {
1065         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1066         enum pipe pipe = crtc->pipe;
1067
1068         /* Wait for the display line to settle/start moving */
1069         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1070                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1071                           pipe_name(pipe), onoff(state));
1072 }
1073
1074 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1075 {
1076         wait_for_pipe_scanline_moving(crtc, false);
1077 }
1078
1079 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1080 {
1081         wait_for_pipe_scanline_moving(crtc, true);
1082 }
1083
1084 static void
1085 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1086 {
1087         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1088         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1089
1090         if (INTEL_GEN(dev_priv) >= 4) {
1091                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1092                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1093
1094                 /* Wait for the Pipe State to go off */
1095                 if (intel_wait_for_register(dev_priv,
1096                                             reg, I965_PIPECONF_ACTIVE, 0,
1097                                             100))
1098                         WARN(1, "pipe_off wait timed out\n");
1099         } else {
1100                 intel_wait_for_pipe_scanline_stopped(crtc);
1101         }
1102 }
1103
1104 /* Only for pre-ILK configs */
1105 void assert_pll(struct drm_i915_private *dev_priv,
1106                 enum pipe pipe, bool state)
1107 {
1108         u32 val;
1109         bool cur_state;
1110
1111         val = I915_READ(DPLL(pipe));
1112         cur_state = !!(val & DPLL_VCO_ENABLE);
1113         I915_STATE_WARN(cur_state != state,
1114              "PLL state assertion failure (expected %s, current %s)\n",
1115                         onoff(state), onoff(cur_state));
1116 }
1117
1118 /* XXX: the dsi pll is shared between MIPI DSI ports */
1119 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1120 {
1121         u32 val;
1122         bool cur_state;
1123
1124         mutex_lock(&dev_priv->sb_lock);
1125         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1126         mutex_unlock(&dev_priv->sb_lock);
1127
1128         cur_state = val & DSI_PLL_VCO_EN;
1129         I915_STATE_WARN(cur_state != state,
1130              "DSI PLL state assertion failure (expected %s, current %s)\n",
1131                         onoff(state), onoff(cur_state));
1132 }
1133
1134 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1135                           enum pipe pipe, bool state)
1136 {
1137         bool cur_state;
1138         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1139                                                                       pipe);
1140
1141         if (HAS_DDI(dev_priv)) {
1142                 /* DDI does not have a specific FDI_TX register */
1143                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1144                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1145         } else {
1146                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1147                 cur_state = !!(val & FDI_TX_ENABLE);
1148         }
1149         I915_STATE_WARN(cur_state != state,
1150              "FDI TX state assertion failure (expected %s, current %s)\n",
1151                         onoff(state), onoff(cur_state));
1152 }
1153 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1154 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1155
1156 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1157                           enum pipe pipe, bool state)
1158 {
1159         u32 val;
1160         bool cur_state;
1161
1162         val = I915_READ(FDI_RX_CTL(pipe));
1163         cur_state = !!(val & FDI_RX_ENABLE);
1164         I915_STATE_WARN(cur_state != state,
1165              "FDI RX state assertion failure (expected %s, current %s)\n",
1166                         onoff(state), onoff(cur_state));
1167 }
1168 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1169 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1170
1171 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1172                                       enum pipe pipe)
1173 {
1174         u32 val;
1175
1176         /* ILK FDI PLL is always enabled */
1177         if (IS_GEN5(dev_priv))
1178                 return;
1179
1180         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1181         if (HAS_DDI(dev_priv))
1182                 return;
1183
1184         val = I915_READ(FDI_TX_CTL(pipe));
1185         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1186 }
1187
1188 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1189                        enum pipe pipe, bool state)
1190 {
1191         u32 val;
1192         bool cur_state;
1193
1194         val = I915_READ(FDI_RX_CTL(pipe));
1195         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1196         I915_STATE_WARN(cur_state != state,
1197              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1198                         onoff(state), onoff(cur_state));
1199 }
1200
1201 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1202 {
1203         i915_reg_t pp_reg;
1204         u32 val;
1205         enum pipe panel_pipe = PIPE_A;
1206         bool locked = true;
1207
1208         if (WARN_ON(HAS_DDI(dev_priv)))
1209                 return;
1210
1211         if (HAS_PCH_SPLIT(dev_priv)) {
1212                 u32 port_sel;
1213
1214                 pp_reg = PP_CONTROL(0);
1215                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1216
1217                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1218                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1219                         panel_pipe = PIPE_B;
1220                 /* XXX: else fix for eDP */
1221         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1222                 /* presumably write lock depends on pipe, not port select */
1223                 pp_reg = PP_CONTROL(pipe);
1224                 panel_pipe = pipe;
1225         } else {
1226                 pp_reg = PP_CONTROL(0);
1227                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1228                         panel_pipe = PIPE_B;
1229         }
1230
1231         val = I915_READ(pp_reg);
1232         if (!(val & PANEL_POWER_ON) ||
1233             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1234                 locked = false;
1235
1236         I915_STATE_WARN(panel_pipe == pipe && locked,
1237              "panel assertion failure, pipe %c regs locked\n",
1238              pipe_name(pipe));
1239 }
1240
1241 void assert_pipe(struct drm_i915_private *dev_priv,
1242                  enum pipe pipe, bool state)
1243 {
1244         bool cur_state;
1245         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1246                                                                       pipe);
1247         enum intel_display_power_domain power_domain;
1248
1249         /* we keep both pipes enabled on 830 */
1250         if (IS_I830(dev_priv))
1251                 state = true;
1252
1253         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1254         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1255                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1256                 cur_state = !!(val & PIPECONF_ENABLE);
1257
1258                 intel_display_power_put(dev_priv, power_domain);
1259         } else {
1260                 cur_state = false;
1261         }
1262
1263         I915_STATE_WARN(cur_state != state,
1264              "pipe %c assertion failure (expected %s, current %s)\n",
1265                         pipe_name(pipe), onoff(state), onoff(cur_state));
1266 }
1267
1268 static void assert_plane(struct intel_plane *plane, bool state)
1269 {
1270         bool cur_state = plane->get_hw_state(plane);
1271
1272         I915_STATE_WARN(cur_state != state,
1273                         "%s assertion failure (expected %s, current %s)\n",
1274                         plane->base.name, onoff(state), onoff(cur_state));
1275 }
1276
1277 #define assert_plane_enabled(p) assert_plane(p, true)
1278 #define assert_plane_disabled(p) assert_plane(p, false)
1279
1280 static void assert_planes_disabled(struct intel_crtc *crtc)
1281 {
1282         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1283         struct intel_plane *plane;
1284
1285         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1286                 assert_plane_disabled(plane);
1287 }
1288
1289 static void assert_vblank_disabled(struct drm_crtc *crtc)
1290 {
1291         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1292                 drm_crtc_vblank_put(crtc);
1293 }
1294
1295 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1296                                     enum pipe pipe)
1297 {
1298         u32 val;
1299         bool enabled;
1300
1301         val = I915_READ(PCH_TRANSCONF(pipe));
1302         enabled = !!(val & TRANS_ENABLE);
1303         I915_STATE_WARN(enabled,
1304              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1305              pipe_name(pipe));
1306 }
1307
1308 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1309                             enum pipe pipe, u32 port_sel, u32 val)
1310 {
1311         if ((val & DP_PORT_EN) == 0)
1312                 return false;
1313
1314         if (HAS_PCH_CPT(dev_priv)) {
1315                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1316                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1317                         return false;
1318         } else if (IS_CHERRYVIEW(dev_priv)) {
1319                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1320                         return false;
1321         } else {
1322                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1323                         return false;
1324         }
1325         return true;
1326 }
1327
1328 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1329                               enum pipe pipe, u32 val)
1330 {
1331         if ((val & SDVO_ENABLE) == 0)
1332                 return false;
1333
1334         if (HAS_PCH_CPT(dev_priv)) {
1335                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1336                         return false;
1337         } else if (IS_CHERRYVIEW(dev_priv)) {
1338                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1339                         return false;
1340         } else {
1341                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1342                         return false;
1343         }
1344         return true;
1345 }
1346
1347 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1348                               enum pipe pipe, u32 val)
1349 {
1350         if ((val & LVDS_PORT_EN) == 0)
1351                 return false;
1352
1353         if (HAS_PCH_CPT(dev_priv)) {
1354                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1355                         return false;
1356         } else {
1357                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1358                         return false;
1359         }
1360         return true;
1361 }
1362
1363 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1364                               enum pipe pipe, u32 val)
1365 {
1366         if ((val & ADPA_DAC_ENABLE) == 0)
1367                 return false;
1368         if (HAS_PCH_CPT(dev_priv)) {
1369                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1370                         return false;
1371         } else {
1372                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1373                         return false;
1374         }
1375         return true;
1376 }
1377
1378 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1379                                    enum pipe pipe, i915_reg_t reg,
1380                                    u32 port_sel)
1381 {
1382         u32 val = I915_READ(reg);
1383         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1384              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1385              i915_mmio_reg_offset(reg), pipe_name(pipe));
1386
1387         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1388              && (val & DP_PIPEB_SELECT),
1389              "IBX PCH dp port still using transcoder B\n");
1390 }
1391
1392 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1393                                      enum pipe pipe, i915_reg_t reg)
1394 {
1395         u32 val = I915_READ(reg);
1396         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1397              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1398              i915_mmio_reg_offset(reg), pipe_name(pipe));
1399
1400         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1401              && (val & SDVO_PIPE_B_SELECT),
1402              "IBX PCH hdmi port still using transcoder B\n");
1403 }
1404
1405 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1406                                       enum pipe pipe)
1407 {
1408         u32 val;
1409
1410         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1411         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1412         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1413
1414         val = I915_READ(PCH_ADPA);
1415         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1416              "PCH VGA enabled on transcoder %c, should be disabled\n",
1417              pipe_name(pipe));
1418
1419         val = I915_READ(PCH_LVDS);
1420         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1421              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1422              pipe_name(pipe));
1423
1424         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1425         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1426         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1427 }
1428
1429 static void _vlv_enable_pll(struct intel_crtc *crtc,
1430                             const struct intel_crtc_state *pipe_config)
1431 {
1432         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1433         enum pipe pipe = crtc->pipe;
1434
1435         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1436         POSTING_READ(DPLL(pipe));
1437         udelay(150);
1438
1439         if (intel_wait_for_register(dev_priv,
1440                                     DPLL(pipe),
1441                                     DPLL_LOCK_VLV,
1442                                     DPLL_LOCK_VLV,
1443                                     1))
1444                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1445 }
1446
1447 static void vlv_enable_pll(struct intel_crtc *crtc,
1448                            const struct intel_crtc_state *pipe_config)
1449 {
1450         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1451         enum pipe pipe = crtc->pipe;
1452
1453         assert_pipe_disabled(dev_priv, pipe);
1454
1455         /* PLL is protected by panel, make sure we can write it */
1456         assert_panel_unlocked(dev_priv, pipe);
1457
1458         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1459                 _vlv_enable_pll(crtc, pipe_config);
1460
1461         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1462         POSTING_READ(DPLL_MD(pipe));
1463 }
1464
1465
1466 static void _chv_enable_pll(struct intel_crtc *crtc,
1467                             const struct intel_crtc_state *pipe_config)
1468 {
1469         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1470         enum pipe pipe = crtc->pipe;
1471         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1472         u32 tmp;
1473
1474         mutex_lock(&dev_priv->sb_lock);
1475
1476         /* Enable back the 10bit clock to display controller */
1477         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1478         tmp |= DPIO_DCLKP_EN;
1479         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1480
1481         mutex_unlock(&dev_priv->sb_lock);
1482
1483         /*
1484          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1485          */
1486         udelay(1);
1487
1488         /* Enable PLL */
1489         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1490
1491         /* Check PLL is locked */
1492         if (intel_wait_for_register(dev_priv,
1493                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1494                                     1))
1495                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1496 }
1497
1498 static void chv_enable_pll(struct intel_crtc *crtc,
1499                            const struct intel_crtc_state *pipe_config)
1500 {
1501         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1502         enum pipe pipe = crtc->pipe;
1503
1504         assert_pipe_disabled(dev_priv, pipe);
1505
1506         /* PLL is protected by panel, make sure we can write it */
1507         assert_panel_unlocked(dev_priv, pipe);
1508
1509         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1510                 _chv_enable_pll(crtc, pipe_config);
1511
1512         if (pipe != PIPE_A) {
1513                 /*
1514                  * WaPixelRepeatModeFixForC0:chv
1515                  *
1516                  * DPLLCMD is AWOL. Use chicken bits to propagate
1517                  * the value from DPLLBMD to either pipe B or C.
1518                  */
1519                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1520                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1521                 I915_WRITE(CBR4_VLV, 0);
1522                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1523
1524                 /*
1525                  * DPLLB VGA mode also seems to cause problems.
1526                  * We should always have it disabled.
1527                  */
1528                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1529         } else {
1530                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1531                 POSTING_READ(DPLL_MD(pipe));
1532         }
1533 }
1534
1535 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1536 {
1537         struct intel_crtc *crtc;
1538         int count = 0;
1539
1540         for_each_intel_crtc(&dev_priv->drm, crtc) {
1541                 count += crtc->base.state->active &&
1542                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1543         }
1544
1545         return count;
1546 }
1547
1548 static void i9xx_enable_pll(struct intel_crtc *crtc,
1549                             const struct intel_crtc_state *crtc_state)
1550 {
1551         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1552         i915_reg_t reg = DPLL(crtc->pipe);
1553         u32 dpll = crtc_state->dpll_hw_state.dpll;
1554         int i;
1555
1556         assert_pipe_disabled(dev_priv, crtc->pipe);
1557
1558         /* PLL is protected by panel, make sure we can write it */
1559         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1560                 assert_panel_unlocked(dev_priv, crtc->pipe);
1561
1562         /* Enable DVO 2x clock on both PLLs if necessary */
1563         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1564                 /*
1565                  * It appears to be important that we don't enable this
1566                  * for the current pipe before otherwise configuring the
1567                  * PLL. No idea how this should be handled if multiple
1568                  * DVO outputs are enabled simultaneosly.
1569                  */
1570                 dpll |= DPLL_DVO_2X_MODE;
1571                 I915_WRITE(DPLL(!crtc->pipe),
1572                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1573         }
1574
1575         /*
1576          * Apparently we need to have VGA mode enabled prior to changing
1577          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1578          * dividers, even though the register value does change.
1579          */
1580         I915_WRITE(reg, 0);
1581
1582         I915_WRITE(reg, dpll);
1583
1584         /* Wait for the clocks to stabilize. */
1585         POSTING_READ(reg);
1586         udelay(150);
1587
1588         if (INTEL_GEN(dev_priv) >= 4) {
1589                 I915_WRITE(DPLL_MD(crtc->pipe),
1590                            crtc_state->dpll_hw_state.dpll_md);
1591         } else {
1592                 /* The pixel multiplier can only be updated once the
1593                  * DPLL is enabled and the clocks are stable.
1594                  *
1595                  * So write it again.
1596                  */
1597                 I915_WRITE(reg, dpll);
1598         }
1599
1600         /* We do this three times for luck */
1601         for (i = 0; i < 3; i++) {
1602                 I915_WRITE(reg, dpll);
1603                 POSTING_READ(reg);
1604                 udelay(150); /* wait for warmup */
1605         }
1606 }
1607
1608 static void i9xx_disable_pll(struct intel_crtc *crtc)
1609 {
1610         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1611         enum pipe pipe = crtc->pipe;
1612
1613         /* Disable DVO 2x clock on both PLLs if necessary */
1614         if (IS_I830(dev_priv) &&
1615             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1616             !intel_num_dvo_pipes(dev_priv)) {
1617                 I915_WRITE(DPLL(PIPE_B),
1618                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1619                 I915_WRITE(DPLL(PIPE_A),
1620                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1621         }
1622
1623         /* Don't disable pipe or pipe PLLs if needed */
1624         if (IS_I830(dev_priv))
1625                 return;
1626
1627         /* Make sure the pipe isn't still relying on us */
1628         assert_pipe_disabled(dev_priv, pipe);
1629
1630         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1631         POSTING_READ(DPLL(pipe));
1632 }
1633
1634 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1635 {
1636         u32 val;
1637
1638         /* Make sure the pipe isn't still relying on us */
1639         assert_pipe_disabled(dev_priv, pipe);
1640
1641         val = DPLL_INTEGRATED_REF_CLK_VLV |
1642                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1643         if (pipe != PIPE_A)
1644                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1645
1646         I915_WRITE(DPLL(pipe), val);
1647         POSTING_READ(DPLL(pipe));
1648 }
1649
1650 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1651 {
1652         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1653         u32 val;
1654
1655         /* Make sure the pipe isn't still relying on us */
1656         assert_pipe_disabled(dev_priv, pipe);
1657
1658         val = DPLL_SSC_REF_CLK_CHV |
1659                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1660         if (pipe != PIPE_A)
1661                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1662
1663         I915_WRITE(DPLL(pipe), val);
1664         POSTING_READ(DPLL(pipe));
1665
1666         mutex_lock(&dev_priv->sb_lock);
1667
1668         /* Disable 10bit clock to display controller */
1669         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1670         val &= ~DPIO_DCLKP_EN;
1671         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1672
1673         mutex_unlock(&dev_priv->sb_lock);
1674 }
1675
1676 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1677                          struct intel_digital_port *dport,
1678                          unsigned int expected_mask)
1679 {
1680         u32 port_mask;
1681         i915_reg_t dpll_reg;
1682
1683         switch (dport->base.port) {
1684         case PORT_B:
1685                 port_mask = DPLL_PORTB_READY_MASK;
1686                 dpll_reg = DPLL(0);
1687                 break;
1688         case PORT_C:
1689                 port_mask = DPLL_PORTC_READY_MASK;
1690                 dpll_reg = DPLL(0);
1691                 expected_mask <<= 4;
1692                 break;
1693         case PORT_D:
1694                 port_mask = DPLL_PORTD_READY_MASK;
1695                 dpll_reg = DPIO_PHY_STATUS;
1696                 break;
1697         default:
1698                 BUG();
1699         }
1700
1701         if (intel_wait_for_register(dev_priv,
1702                                     dpll_reg, port_mask, expected_mask,
1703                                     1000))
1704                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1705                      port_name(dport->base.port),
1706                      I915_READ(dpll_reg) & port_mask, expected_mask);
1707 }
1708
1709 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1710                                            enum pipe pipe)
1711 {
1712         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1713                                                                 pipe);
1714         i915_reg_t reg;
1715         uint32_t val, pipeconf_val;
1716
1717         /* Make sure PCH DPLL is enabled */
1718         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1719
1720         /* FDI must be feeding us bits for PCH ports */
1721         assert_fdi_tx_enabled(dev_priv, pipe);
1722         assert_fdi_rx_enabled(dev_priv, pipe);
1723
1724         if (HAS_PCH_CPT(dev_priv)) {
1725                 /* Workaround: Set the timing override bit before enabling the
1726                  * pch transcoder. */
1727                 reg = TRANS_CHICKEN2(pipe);
1728                 val = I915_READ(reg);
1729                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1730                 I915_WRITE(reg, val);
1731         }
1732
1733         reg = PCH_TRANSCONF(pipe);
1734         val = I915_READ(reg);
1735         pipeconf_val = I915_READ(PIPECONF(pipe));
1736
1737         if (HAS_PCH_IBX(dev_priv)) {
1738                 /*
1739                  * Make the BPC in transcoder be consistent with
1740                  * that in pipeconf reg. For HDMI we must use 8bpc
1741                  * here for both 8bpc and 12bpc.
1742                  */
1743                 val &= ~PIPECONF_BPC_MASK;
1744                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1745                         val |= PIPECONF_8BPC;
1746                 else
1747                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1748         }
1749
1750         val &= ~TRANS_INTERLACE_MASK;
1751         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1752                 if (HAS_PCH_IBX(dev_priv) &&
1753                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1754                         val |= TRANS_LEGACY_INTERLACED_ILK;
1755                 else
1756                         val |= TRANS_INTERLACED;
1757         else
1758                 val |= TRANS_PROGRESSIVE;
1759
1760         I915_WRITE(reg, val | TRANS_ENABLE);
1761         if (intel_wait_for_register(dev_priv,
1762                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1763                                     100))
1764                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1765 }
1766
1767 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1768                                       enum transcoder cpu_transcoder)
1769 {
1770         u32 val, pipeconf_val;
1771
1772         /* FDI must be feeding us bits for PCH ports */
1773         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1774         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1775
1776         /* Workaround: set timing override bit. */
1777         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1778         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1779         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1780
1781         val = TRANS_ENABLE;
1782         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1783
1784         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1785             PIPECONF_INTERLACED_ILK)
1786                 val |= TRANS_INTERLACED;
1787         else
1788                 val |= TRANS_PROGRESSIVE;
1789
1790         I915_WRITE(LPT_TRANSCONF, val);
1791         if (intel_wait_for_register(dev_priv,
1792                                     LPT_TRANSCONF,
1793                                     TRANS_STATE_ENABLE,
1794                                     TRANS_STATE_ENABLE,
1795                                     100))
1796                 DRM_ERROR("Failed to enable PCH transcoder\n");
1797 }
1798
1799 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1800                                             enum pipe pipe)
1801 {
1802         i915_reg_t reg;
1803         uint32_t val;
1804
1805         /* FDI relies on the transcoder */
1806         assert_fdi_tx_disabled(dev_priv, pipe);
1807         assert_fdi_rx_disabled(dev_priv, pipe);
1808
1809         /* Ports must be off as well */
1810         assert_pch_ports_disabled(dev_priv, pipe);
1811
1812         reg = PCH_TRANSCONF(pipe);
1813         val = I915_READ(reg);
1814         val &= ~TRANS_ENABLE;
1815         I915_WRITE(reg, val);
1816         /* wait for PCH transcoder off, transcoder state */
1817         if (intel_wait_for_register(dev_priv,
1818                                     reg, TRANS_STATE_ENABLE, 0,
1819                                     50))
1820                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1821
1822         if (HAS_PCH_CPT(dev_priv)) {
1823                 /* Workaround: Clear the timing override chicken bit again. */
1824                 reg = TRANS_CHICKEN2(pipe);
1825                 val = I915_READ(reg);
1826                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1827                 I915_WRITE(reg, val);
1828         }
1829 }
1830
1831 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1832 {
1833         u32 val;
1834
1835         val = I915_READ(LPT_TRANSCONF);
1836         val &= ~TRANS_ENABLE;
1837         I915_WRITE(LPT_TRANSCONF, val);
1838         /* wait for PCH transcoder off, transcoder state */
1839         if (intel_wait_for_register(dev_priv,
1840                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1841                                     50))
1842                 DRM_ERROR("Failed to disable PCH transcoder\n");
1843
1844         /* Workaround: clear timing override bit. */
1845         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1846         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1847         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1848 }
1849
1850 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1851 {
1852         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1853
1854         if (HAS_PCH_LPT(dev_priv))
1855                 return PIPE_A;
1856         else
1857                 return crtc->pipe;
1858 }
1859
1860 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1861 {
1862         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1863         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1864         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1865         enum pipe pipe = crtc->pipe;
1866         i915_reg_t reg;
1867         u32 val;
1868
1869         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1870
1871         assert_planes_disabled(crtc);
1872
1873         /*
1874          * A pipe without a PLL won't actually be able to drive bits from
1875          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1876          * need the check.
1877          */
1878         if (HAS_GMCH_DISPLAY(dev_priv)) {
1879                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1880                         assert_dsi_pll_enabled(dev_priv);
1881                 else
1882                         assert_pll_enabled(dev_priv, pipe);
1883         } else {
1884                 if (new_crtc_state->has_pch_encoder) {
1885                         /* if driving the PCH, we need FDI enabled */
1886                         assert_fdi_rx_pll_enabled(dev_priv,
1887                                                   intel_crtc_pch_transcoder(crtc));
1888                         assert_fdi_tx_pll_enabled(dev_priv,
1889                                                   (enum pipe) cpu_transcoder);
1890                 }
1891                 /* FIXME: assert CPU port conditions for SNB+ */
1892         }
1893
1894         reg = PIPECONF(cpu_transcoder);
1895         val = I915_READ(reg);
1896         if (val & PIPECONF_ENABLE) {
1897                 /* we keep both pipes enabled on 830 */
1898                 WARN_ON(!IS_I830(dev_priv));
1899                 return;
1900         }
1901
1902         I915_WRITE(reg, val | PIPECONF_ENABLE);
1903         POSTING_READ(reg);
1904
1905         /*
1906          * Until the pipe starts PIPEDSL reads will return a stale value,
1907          * which causes an apparent vblank timestamp jump when PIPEDSL
1908          * resets to its proper value. That also messes up the frame count
1909          * when it's derived from the timestamps. So let's wait for the
1910          * pipe to start properly before we call drm_crtc_vblank_on()
1911          */
1912         if (dev_priv->drm.max_vblank_count == 0)
1913                 intel_wait_for_pipe_scanline_moving(crtc);
1914 }
1915
1916 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1917 {
1918         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1919         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1920         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1921         enum pipe pipe = crtc->pipe;
1922         i915_reg_t reg;
1923         u32 val;
1924
1925         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1926
1927         /*
1928          * Make sure planes won't keep trying to pump pixels to us,
1929          * or we might hang the display.
1930          */
1931         assert_planes_disabled(crtc);
1932
1933         reg = PIPECONF(cpu_transcoder);
1934         val = I915_READ(reg);
1935         if ((val & PIPECONF_ENABLE) == 0)
1936                 return;
1937
1938         /*
1939          * Double wide has implications for planes
1940          * so best keep it disabled when not needed.
1941          */
1942         if (old_crtc_state->double_wide)
1943                 val &= ~PIPECONF_DOUBLE_WIDE;
1944
1945         /* Don't disable pipe or pipe PLLs if needed */
1946         if (!IS_I830(dev_priv))
1947                 val &= ~PIPECONF_ENABLE;
1948
1949         I915_WRITE(reg, val);
1950         if ((val & PIPECONF_ENABLE) == 0)
1951                 intel_wait_for_pipe_off(old_crtc_state);
1952 }
1953
1954 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1955 {
1956         return IS_GEN2(dev_priv) ? 2048 : 4096;
1957 }
1958
1959 static unsigned int
1960 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1961 {
1962         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1963         unsigned int cpp = fb->format->cpp[plane];
1964
1965         switch (fb->modifier) {
1966         case DRM_FORMAT_MOD_LINEAR:
1967                 return cpp;
1968         case I915_FORMAT_MOD_X_TILED:
1969                 if (IS_GEN2(dev_priv))
1970                         return 128;
1971                 else
1972                         return 512;
1973         case I915_FORMAT_MOD_Y_TILED_CCS:
1974                 if (plane == 1)
1975                         return 128;
1976                 /* fall through */
1977         case I915_FORMAT_MOD_Y_TILED:
1978                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1979                         return 128;
1980                 else
1981                         return 512;
1982         case I915_FORMAT_MOD_Yf_TILED_CCS:
1983                 if (plane == 1)
1984                         return 128;
1985                 /* fall through */
1986         case I915_FORMAT_MOD_Yf_TILED:
1987                 switch (cpp) {
1988                 case 1:
1989                         return 64;
1990                 case 2:
1991                 case 4:
1992                         return 128;
1993                 case 8:
1994                 case 16:
1995                         return 256;
1996                 default:
1997                         MISSING_CASE(cpp);
1998                         return cpp;
1999                 }
2000                 break;
2001         default:
2002                 MISSING_CASE(fb->modifier);
2003                 return cpp;
2004         }
2005 }
2006
2007 static unsigned int
2008 intel_tile_height(const struct drm_framebuffer *fb, int plane)
2009 {
2010         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
2011                 return 1;
2012         else
2013                 return intel_tile_size(to_i915(fb->dev)) /
2014                         intel_tile_width_bytes(fb, plane);
2015 }
2016
2017 /* Return the tile dimensions in pixel units */
2018 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
2019                             unsigned int *tile_width,
2020                             unsigned int *tile_height)
2021 {
2022         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
2023         unsigned int cpp = fb->format->cpp[plane];
2024
2025         *tile_width = tile_width_bytes / cpp;
2026         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
2027 }
2028
2029 unsigned int
2030 intel_fb_align_height(const struct drm_framebuffer *fb,
2031                       int plane, unsigned int height)
2032 {
2033         unsigned int tile_height = intel_tile_height(fb, plane);
2034
2035         return ALIGN(height, tile_height);
2036 }
2037
2038 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2039 {
2040         unsigned int size = 0;
2041         int i;
2042
2043         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2044                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2045
2046         return size;
2047 }
2048
2049 static void
2050 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2051                         const struct drm_framebuffer *fb,
2052                         unsigned int rotation)
2053 {
2054         view->type = I915_GGTT_VIEW_NORMAL;
2055         if (drm_rotation_90_or_270(rotation)) {
2056                 view->type = I915_GGTT_VIEW_ROTATED;
2057                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2058         }
2059 }
2060
2061 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2062 {
2063         if (IS_I830(dev_priv))
2064                 return 16 * 1024;
2065         else if (IS_I85X(dev_priv))
2066                 return 256;
2067         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2068                 return 32;
2069         else
2070                 return 4 * 1024;
2071 }
2072
2073 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2074 {
2075         if (INTEL_GEN(dev_priv) >= 9)
2076                 return 256 * 1024;
2077         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2078                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2079                 return 128 * 1024;
2080         else if (INTEL_GEN(dev_priv) >= 4)
2081                 return 4 * 1024;
2082         else
2083                 return 0;
2084 }
2085
2086 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2087                                          int plane)
2088 {
2089         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2090
2091         /* AUX_DIST needs only 4K alignment */
2092         if (plane == 1)
2093                 return 4096;
2094
2095         switch (fb->modifier) {
2096         case DRM_FORMAT_MOD_LINEAR:
2097                 return intel_linear_alignment(dev_priv);
2098         case I915_FORMAT_MOD_X_TILED:
2099                 if (INTEL_GEN(dev_priv) >= 9)
2100                         return 256 * 1024;
2101                 return 0;
2102         case I915_FORMAT_MOD_Y_TILED_CCS:
2103         case I915_FORMAT_MOD_Yf_TILED_CCS:
2104         case I915_FORMAT_MOD_Y_TILED:
2105         case I915_FORMAT_MOD_Yf_TILED:
2106                 return 1 * 1024 * 1024;
2107         default:
2108                 MISSING_CASE(fb->modifier);
2109                 return 0;
2110         }
2111 }
2112
2113 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2114 {
2115         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2116         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2117
2118         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2119 }
2120
2121 struct i915_vma *
2122 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2123                            unsigned int rotation,
2124                            bool uses_fence,
2125                            unsigned long *out_flags)
2126 {
2127         struct drm_device *dev = fb->dev;
2128         struct drm_i915_private *dev_priv = to_i915(dev);
2129         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2130         struct i915_ggtt_view view;
2131         struct i915_vma *vma;
2132         unsigned int pinctl;
2133         u32 alignment;
2134
2135         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2136
2137         alignment = intel_surf_alignment(fb, 0);
2138
2139         intel_fill_fb_ggtt_view(&view, fb, rotation);
2140
2141         /* Note that the w/a also requires 64 PTE of padding following the
2142          * bo. We currently fill all unused PTE with the shadow page and so
2143          * we should always have valid PTE following the scanout preventing
2144          * the VT-d warning.
2145          */
2146         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2147                 alignment = 256 * 1024;
2148
2149         /*
2150          * Global gtt pte registers are special registers which actually forward
2151          * writes to a chunk of system memory. Which means that there is no risk
2152          * that the register values disappear as soon as we call
2153          * intel_runtime_pm_put(), so it is correct to wrap only the
2154          * pin/unpin/fence and not more.
2155          */
2156         intel_runtime_pm_get(dev_priv);
2157
2158         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2159
2160         pinctl = 0;
2161
2162         /* Valleyview is definitely limited to scanning out the first
2163          * 512MiB. Lets presume this behaviour was inherited from the
2164          * g4x display engine and that all earlier gen are similarly
2165          * limited. Testing suggests that it is a little more
2166          * complicated than this. For example, Cherryview appears quite
2167          * happy to scanout from anywhere within its global aperture.
2168          */
2169         if (HAS_GMCH_DISPLAY(dev_priv))
2170                 pinctl |= PIN_MAPPABLE;
2171
2172         vma = i915_gem_object_pin_to_display_plane(obj,
2173                                                    alignment, &view, pinctl);
2174         if (IS_ERR(vma))
2175                 goto err;
2176
2177         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2178                 int ret;
2179
2180                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2181                  * fence, whereas 965+ only requires a fence if using
2182                  * framebuffer compression.  For simplicity, we always, when
2183                  * possible, install a fence as the cost is not that onerous.
2184                  *
2185                  * If we fail to fence the tiled scanout, then either the
2186                  * modeset will reject the change (which is highly unlikely as
2187                  * the affected systems, all but one, do not have unmappable
2188                  * space) or we will not be able to enable full powersaving
2189                  * techniques (also likely not to apply due to various limits
2190                  * FBC and the like impose on the size of the buffer, which
2191                  * presumably we violated anyway with this unmappable buffer).
2192                  * Anyway, it is presumably better to stumble onwards with
2193                  * something and try to run the system in a "less than optimal"
2194                  * mode that matches the user configuration.
2195                  */
2196                 ret = i915_vma_pin_fence(vma);
2197                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2198                         i915_gem_object_unpin_from_display_plane(vma);
2199                         vma = ERR_PTR(ret);
2200                         goto err;
2201                 }
2202
2203                 if (ret == 0 && vma->fence)
2204                         *out_flags |= PLANE_HAS_FENCE;
2205         }
2206
2207         i915_vma_get(vma);
2208 err:
2209         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2210
2211         intel_runtime_pm_put(dev_priv);
2212         return vma;
2213 }
2214
2215 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2216 {
2217         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2218
2219         if (flags & PLANE_HAS_FENCE)
2220                 i915_vma_unpin_fence(vma);
2221         i915_gem_object_unpin_from_display_plane(vma);
2222         i915_vma_put(vma);
2223 }
2224
2225 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2226                           unsigned int rotation)
2227 {
2228         if (drm_rotation_90_or_270(rotation))
2229                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2230         else
2231                 return fb->pitches[plane];
2232 }
2233
2234 /*
2235  * Convert the x/y offsets into a linear offset.
2236  * Only valid with 0/180 degree rotation, which is fine since linear
2237  * offset is only used with linear buffers on pre-hsw and tiled buffers
2238  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2239  */
2240 u32 intel_fb_xy_to_linear(int x, int y,
2241                           const struct intel_plane_state *state,
2242                           int plane)
2243 {
2244         const struct drm_framebuffer *fb = state->base.fb;
2245         unsigned int cpp = fb->format->cpp[plane];
2246         unsigned int pitch = fb->pitches[plane];
2247
2248         return y * pitch + x * cpp;
2249 }
2250
2251 /*
2252  * Add the x/y offsets derived from fb->offsets[] to the user
2253  * specified plane src x/y offsets. The resulting x/y offsets
2254  * specify the start of scanout from the beginning of the gtt mapping.
2255  */
2256 void intel_add_fb_offsets(int *x, int *y,
2257                           const struct intel_plane_state *state,
2258                           int plane)
2259
2260 {
2261         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2262         unsigned int rotation = state->base.rotation;
2263
2264         if (drm_rotation_90_or_270(rotation)) {
2265                 *x += intel_fb->rotated[plane].x;
2266                 *y += intel_fb->rotated[plane].y;
2267         } else {
2268                 *x += intel_fb->normal[plane].x;
2269                 *y += intel_fb->normal[plane].y;
2270         }
2271 }
2272
2273 static u32 __intel_adjust_tile_offset(int *x, int *y,
2274                                       unsigned int tile_width,
2275                                       unsigned int tile_height,
2276                                       unsigned int tile_size,
2277                                       unsigned int pitch_tiles,
2278                                       u32 old_offset,
2279                                       u32 new_offset)
2280 {
2281         unsigned int pitch_pixels = pitch_tiles * tile_width;
2282         unsigned int tiles;
2283
2284         WARN_ON(old_offset & (tile_size - 1));
2285         WARN_ON(new_offset & (tile_size - 1));
2286         WARN_ON(new_offset > old_offset);
2287
2288         tiles = (old_offset - new_offset) / tile_size;
2289
2290         *y += tiles / pitch_tiles * tile_height;
2291         *x += tiles % pitch_tiles * tile_width;
2292
2293         /* minimize x in case it got needlessly big */
2294         *y += *x / pitch_pixels * tile_height;
2295         *x %= pitch_pixels;
2296
2297         return new_offset;
2298 }
2299
2300 static u32 _intel_adjust_tile_offset(int *x, int *y,
2301                                      const struct drm_framebuffer *fb, int plane,
2302                                      unsigned int rotation,
2303                                      u32 old_offset, u32 new_offset)
2304 {
2305         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2306         unsigned int cpp = fb->format->cpp[plane];
2307         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2308
2309         WARN_ON(new_offset > old_offset);
2310
2311         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2312                 unsigned int tile_size, tile_width, tile_height;
2313                 unsigned int pitch_tiles;
2314
2315                 tile_size = intel_tile_size(dev_priv);
2316                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2317
2318                 if (drm_rotation_90_or_270(rotation)) {
2319                         pitch_tiles = pitch / tile_height;
2320                         swap(tile_width, tile_height);
2321                 } else {
2322                         pitch_tiles = pitch / (tile_width * cpp);
2323                 }
2324
2325                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2326                                            tile_size, pitch_tiles,
2327                                            old_offset, new_offset);
2328         } else {
2329                 old_offset += *y * pitch + *x * cpp;
2330
2331                 *y = (old_offset - new_offset) / pitch;
2332                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2333         }
2334
2335         return new_offset;
2336 }
2337
2338 /*
2339  * Adjust the tile offset by moving the difference into
2340  * the x/y offsets.
2341  */
2342 static u32 intel_adjust_tile_offset(int *x, int *y,
2343                                     const struct intel_plane_state *state, int plane,
2344                                     u32 old_offset, u32 new_offset)
2345 {
2346         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2347                                          state->base.rotation,
2348                                          old_offset, new_offset);
2349 }
2350
2351 /*
2352  * Computes the linear offset to the base tile and adjusts
2353  * x, y. bytes per pixel is assumed to be a power-of-two.
2354  *
2355  * In the 90/270 rotated case, x and y are assumed
2356  * to be already rotated to match the rotated GTT view, and
2357  * pitch is the tile_height aligned framebuffer height.
2358  *
2359  * This function is used when computing the derived information
2360  * under intel_framebuffer, so using any of that information
2361  * here is not allowed. Anything under drm_framebuffer can be
2362  * used. This is why the user has to pass in the pitch since it
2363  * is specified in the rotated orientation.
2364  */
2365 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2366                                       int *x, int *y,
2367                                       const struct drm_framebuffer *fb, int plane,
2368                                       unsigned int pitch,
2369                                       unsigned int rotation,
2370                                       u32 alignment)
2371 {
2372         uint64_t fb_modifier = fb->modifier;
2373         unsigned int cpp = fb->format->cpp[plane];
2374         u32 offset, offset_aligned;
2375
2376         if (alignment)
2377                 alignment--;
2378
2379         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2380                 unsigned int tile_size, tile_width, tile_height;
2381                 unsigned int tile_rows, tiles, pitch_tiles;
2382
2383                 tile_size = intel_tile_size(dev_priv);
2384                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2385
2386                 if (drm_rotation_90_or_270(rotation)) {
2387                         pitch_tiles = pitch / tile_height;
2388                         swap(tile_width, tile_height);
2389                 } else {
2390                         pitch_tiles = pitch / (tile_width * cpp);
2391                 }
2392
2393                 tile_rows = *y / tile_height;
2394                 *y %= tile_height;
2395
2396                 tiles = *x / tile_width;
2397                 *x %= tile_width;
2398
2399                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2400                 offset_aligned = offset & ~alignment;
2401
2402                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2403                                            tile_size, pitch_tiles,
2404                                            offset, offset_aligned);
2405         } else {
2406                 offset = *y * pitch + *x * cpp;
2407                 offset_aligned = offset & ~alignment;
2408
2409                 *y = (offset & alignment) / pitch;
2410                 *x = ((offset & alignment) - *y * pitch) / cpp;
2411         }
2412
2413         return offset_aligned;
2414 }
2415
2416 u32 intel_compute_tile_offset(int *x, int *y,
2417                               const struct intel_plane_state *state,
2418                               int plane)
2419 {
2420         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2421         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2422         const struct drm_framebuffer *fb = state->base.fb;
2423         unsigned int rotation = state->base.rotation;
2424         int pitch = intel_fb_pitch(fb, plane, rotation);
2425         u32 alignment;
2426
2427         if (intel_plane->id == PLANE_CURSOR)
2428                 alignment = intel_cursor_alignment(dev_priv);
2429         else
2430                 alignment = intel_surf_alignment(fb, plane);
2431
2432         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2433                                           rotation, alignment);
2434 }
2435
2436 /* Convert the fb->offset[] into x/y offsets */
2437 static int intel_fb_offset_to_xy(int *x, int *y,
2438                                  const struct drm_framebuffer *fb, int plane)
2439 {
2440         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2441
2442         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2443             fb->offsets[plane] % intel_tile_size(dev_priv))
2444                 return -EINVAL;
2445
2446         *x = 0;
2447         *y = 0;
2448
2449         _intel_adjust_tile_offset(x, y,
2450                                   fb, plane, DRM_MODE_ROTATE_0,
2451                                   fb->offsets[plane], 0);
2452
2453         return 0;
2454 }
2455
2456 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2457 {
2458         switch (fb_modifier) {
2459         case I915_FORMAT_MOD_X_TILED:
2460                 return I915_TILING_X;
2461         case I915_FORMAT_MOD_Y_TILED:
2462         case I915_FORMAT_MOD_Y_TILED_CCS:
2463                 return I915_TILING_Y;
2464         default:
2465                 return I915_TILING_NONE;
2466         }
2467 }
2468
2469 /*
2470  * From the Sky Lake PRM:
2471  * "The Color Control Surface (CCS) contains the compression status of
2472  *  the cache-line pairs. The compression state of the cache-line pair
2473  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2474  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2475  *  cache-line-pairs. CCS is always Y tiled."
2476  *
2477  * Since cache line pairs refers to horizontally adjacent cache lines,
2478  * each cache line in the CCS corresponds to an area of 32x16 cache
2479  * lines on the main surface. Since each pixel is 4 bytes, this gives
2480  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2481  * main surface.
2482  */
2483 static const struct drm_format_info ccs_formats[] = {
2484         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2485         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2486         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2487         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2488 };
2489
2490 static const struct drm_format_info *
2491 lookup_format_info(const struct drm_format_info formats[],
2492                    int num_formats, u32 format)
2493 {
2494         int i;
2495
2496         for (i = 0; i < num_formats; i++) {
2497                 if (formats[i].format == format)
2498                         return &formats[i];
2499         }
2500
2501         return NULL;
2502 }
2503
2504 static const struct drm_format_info *
2505 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2506 {
2507         switch (cmd->modifier[0]) {
2508         case I915_FORMAT_MOD_Y_TILED_CCS:
2509         case I915_FORMAT_MOD_Yf_TILED_CCS:
2510                 return lookup_format_info(ccs_formats,
2511                                           ARRAY_SIZE(ccs_formats),
2512                                           cmd->pixel_format);
2513         default:
2514                 return NULL;
2515         }
2516 }
2517
2518 static int
2519 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2520                    struct drm_framebuffer *fb)
2521 {
2522         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2523         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2524         u32 gtt_offset_rotated = 0;
2525         unsigned int max_size = 0;
2526         int i, num_planes = fb->format->num_planes;
2527         unsigned int tile_size = intel_tile_size(dev_priv);
2528
2529         for (i = 0; i < num_planes; i++) {
2530                 unsigned int width, height;
2531                 unsigned int cpp, size;
2532                 u32 offset;
2533                 int x, y;
2534                 int ret;
2535
2536                 cpp = fb->format->cpp[i];
2537                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2538                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2539
2540                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2541                 if (ret) {
2542                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2543                                       i, fb->offsets[i]);
2544                         return ret;
2545                 }
2546
2547                 if ((fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2548                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) && i == 1) {
2549                         int hsub = fb->format->hsub;
2550                         int vsub = fb->format->vsub;
2551                         int tile_width, tile_height;
2552                         int main_x, main_y;
2553                         int ccs_x, ccs_y;
2554
2555                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2556                         tile_width *= hsub;
2557                         tile_height *= vsub;
2558
2559                         ccs_x = (x * hsub) % tile_width;
2560                         ccs_y = (y * vsub) % tile_height;
2561                         main_x = intel_fb->normal[0].x % tile_width;
2562                         main_y = intel_fb->normal[0].y % tile_height;
2563
2564                         /*
2565                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2566                          * x/y offsets must match between CCS and the main surface.
2567                          */
2568                         if (main_x != ccs_x || main_y != ccs_y) {
2569                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2570                                               main_x, main_y,
2571                                               ccs_x, ccs_y,
2572                                               intel_fb->normal[0].x,
2573                                               intel_fb->normal[0].y,
2574                                               x, y);
2575                                 return -EINVAL;
2576                         }
2577                 }
2578
2579                 /*
2580                  * The fence (if used) is aligned to the start of the object
2581                  * so having the framebuffer wrap around across the edge of the
2582                  * fenced region doesn't really work. We have no API to configure
2583                  * the fence start offset within the object (nor could we probably
2584                  * on gen2/3). So it's just easier if we just require that the
2585                  * fb layout agrees with the fence layout. We already check that the
2586                  * fb stride matches the fence stride elsewhere.
2587                  */
2588                 if (i == 0 && i915_gem_object_is_tiled(intel_fb->obj) &&
2589                     (x + width) * cpp > fb->pitches[i]) {
2590                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2591                                       i, fb->offsets[i]);
2592                         return -EINVAL;
2593                 }
2594
2595                 /*
2596                  * First pixel of the framebuffer from
2597                  * the start of the normal gtt mapping.
2598                  */
2599                 intel_fb->normal[i].x = x;
2600                 intel_fb->normal[i].y = y;
2601
2602                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2603                                                     fb, i, fb->pitches[i],
2604                                                     DRM_MODE_ROTATE_0, tile_size);
2605                 offset /= tile_size;
2606
2607                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2608                         unsigned int tile_width, tile_height;
2609                         unsigned int pitch_tiles;
2610                         struct drm_rect r;
2611
2612                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2613
2614                         rot_info->plane[i].offset = offset;
2615                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2616                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2617                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2618
2619                         intel_fb->rotated[i].pitch =
2620                                 rot_info->plane[i].height * tile_height;
2621
2622                         /* how many tiles does this plane need */
2623                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2624                         /*
2625                          * If the plane isn't horizontally tile aligned,
2626                          * we need one more tile.
2627                          */
2628                         if (x != 0)
2629                                 size++;
2630
2631                         /* rotate the x/y offsets to match the GTT view */
2632                         r.x1 = x;
2633                         r.y1 = y;
2634                         r.x2 = x + width;
2635                         r.y2 = y + height;
2636                         drm_rect_rotate(&r,
2637                                         rot_info->plane[i].width * tile_width,
2638                                         rot_info->plane[i].height * tile_height,
2639                                         DRM_MODE_ROTATE_270);
2640                         x = r.x1;
2641                         y = r.y1;
2642
2643                         /* rotate the tile dimensions to match the GTT view */
2644                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2645                         swap(tile_width, tile_height);
2646
2647                         /*
2648                          * We only keep the x/y offsets, so push all of the
2649                          * gtt offset into the x/y offsets.
2650                          */
2651                         __intel_adjust_tile_offset(&x, &y,
2652                                                    tile_width, tile_height,
2653                                                    tile_size, pitch_tiles,
2654                                                    gtt_offset_rotated * tile_size, 0);
2655
2656                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2657
2658                         /*
2659                          * First pixel of the framebuffer from
2660                          * the start of the rotated gtt mapping.
2661                          */
2662                         intel_fb->rotated[i].x = x;
2663                         intel_fb->rotated[i].y = y;
2664                 } else {
2665                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2666                                             x * cpp, tile_size);
2667                 }
2668
2669                 /* how many tiles in total needed in the bo */
2670                 max_size = max(max_size, offset + size);
2671         }
2672
2673         if (max_size * tile_size > intel_fb->obj->base.size) {
2674                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2675                               max_size * tile_size, intel_fb->obj->base.size);
2676                 return -EINVAL;
2677         }
2678
2679         return 0;
2680 }
2681
2682 static int i9xx_format_to_fourcc(int format)
2683 {
2684         switch (format) {
2685         case DISPPLANE_8BPP:
2686                 return DRM_FORMAT_C8;
2687         case DISPPLANE_BGRX555:
2688                 return DRM_FORMAT_XRGB1555;
2689         case DISPPLANE_BGRX565:
2690                 return DRM_FORMAT_RGB565;
2691         default:
2692         case DISPPLANE_BGRX888:
2693                 return DRM_FORMAT_XRGB8888;
2694         case DISPPLANE_RGBX888:
2695                 return DRM_FORMAT_XBGR8888;
2696         case DISPPLANE_BGRX101010:
2697                 return DRM_FORMAT_XRGB2101010;
2698         case DISPPLANE_RGBX101010:
2699                 return DRM_FORMAT_XBGR2101010;
2700         }
2701 }
2702
2703 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2704 {
2705         switch (format) {
2706         case PLANE_CTL_FORMAT_RGB_565:
2707                 return DRM_FORMAT_RGB565;
2708         case PLANE_CTL_FORMAT_NV12:
2709                 return DRM_FORMAT_NV12;
2710         default:
2711         case PLANE_CTL_FORMAT_XRGB_8888:
2712                 if (rgb_order) {
2713                         if (alpha)
2714                                 return DRM_FORMAT_ABGR8888;
2715                         else
2716                                 return DRM_FORMAT_XBGR8888;
2717                 } else {
2718                         if (alpha)
2719                                 return DRM_FORMAT_ARGB8888;
2720                         else
2721                                 return DRM_FORMAT_XRGB8888;
2722                 }
2723         case PLANE_CTL_FORMAT_XRGB_2101010:
2724                 if (rgb_order)
2725                         return DRM_FORMAT_XBGR2101010;
2726                 else
2727                         return DRM_FORMAT_XRGB2101010;
2728         }
2729 }
2730
2731 static bool
2732 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2733                               struct intel_initial_plane_config *plane_config)
2734 {
2735         struct drm_device *dev = crtc->base.dev;
2736         struct drm_i915_private *dev_priv = to_i915(dev);
2737         struct drm_i915_gem_object *obj = NULL;
2738         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2739         struct drm_framebuffer *fb = &plane_config->fb->base;
2740         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2741         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2742                                     PAGE_SIZE);
2743
2744         size_aligned -= base_aligned;
2745
2746         if (plane_config->size == 0)
2747                 return false;
2748
2749         /* If the FB is too big, just don't use it since fbdev is not very
2750          * important and we should probably use that space with FBC or other
2751          * features. */
2752         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2753                 return false;
2754
2755         mutex_lock(&dev->struct_mutex);
2756         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2757                                                              base_aligned,
2758                                                              base_aligned,
2759                                                              size_aligned);
2760         mutex_unlock(&dev->struct_mutex);
2761         if (!obj)
2762                 return false;
2763
2764         if (plane_config->tiling == I915_TILING_X)
2765                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2766
2767         mode_cmd.pixel_format = fb->format->format;
2768         mode_cmd.width = fb->width;
2769         mode_cmd.height = fb->height;
2770         mode_cmd.pitches[0] = fb->pitches[0];
2771         mode_cmd.modifier[0] = fb->modifier;
2772         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2773
2774         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2775                 DRM_DEBUG_KMS("intel fb init failed\n");
2776                 goto out_unref_obj;
2777         }
2778
2779
2780         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2781         return true;
2782
2783 out_unref_obj:
2784         i915_gem_object_put(obj);
2785         return false;
2786 }
2787
2788 static void
2789 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2790                         struct intel_plane_state *plane_state,
2791                         bool visible)
2792 {
2793         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2794
2795         plane_state->base.visible = visible;
2796
2797         /* FIXME pre-g4x don't work like this */
2798         if (visible) {
2799                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2800                 crtc_state->active_planes |= BIT(plane->id);
2801         } else {
2802                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2803                 crtc_state->active_planes &= ~BIT(plane->id);
2804         }
2805
2806         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2807                       crtc_state->base.crtc->name,
2808                       crtc_state->active_planes);
2809 }
2810
2811 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2812                                          struct intel_plane *plane)
2813 {
2814         struct intel_crtc_state *crtc_state =
2815                 to_intel_crtc_state(crtc->base.state);
2816         struct intel_plane_state *plane_state =
2817                 to_intel_plane_state(plane->base.state);
2818
2819         intel_set_plane_visible(crtc_state, plane_state, false);
2820
2821         if (plane->id == PLANE_PRIMARY)
2822                 intel_pre_disable_primary_noatomic(&crtc->base);
2823
2824         trace_intel_disable_plane(&plane->base, crtc);
2825         plane->disable_plane(plane, crtc);
2826 }
2827
2828 static void
2829 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2830                              struct intel_initial_plane_config *plane_config)
2831 {
2832         struct drm_device *dev = intel_crtc->base.dev;
2833         struct drm_i915_private *dev_priv = to_i915(dev);
2834         struct drm_crtc *c;
2835         struct drm_i915_gem_object *obj;
2836         struct drm_plane *primary = intel_crtc->base.primary;
2837         struct drm_plane_state *plane_state = primary->state;
2838         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2839         struct intel_plane *intel_plane = to_intel_plane(primary);
2840         struct intel_plane_state *intel_state =
2841                 to_intel_plane_state(plane_state);
2842         struct drm_framebuffer *fb;
2843
2844         if (!plane_config->fb)
2845                 return;
2846
2847         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2848                 fb = &plane_config->fb->base;
2849                 goto valid_fb;
2850         }
2851
2852         kfree(plane_config->fb);
2853
2854         /*
2855          * Failed to alloc the obj, check to see if we should share
2856          * an fb with another CRTC instead
2857          */
2858         for_each_crtc(dev, c) {
2859                 struct intel_plane_state *state;
2860
2861                 if (c == &intel_crtc->base)
2862                         continue;
2863
2864                 if (!to_intel_crtc(c)->active)
2865                         continue;
2866
2867                 state = to_intel_plane_state(c->primary->state);
2868                 if (!state->vma)
2869                         continue;
2870
2871                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2872                         fb = state->base.fb;
2873                         drm_framebuffer_get(fb);
2874                         goto valid_fb;
2875                 }
2876         }
2877
2878         /*
2879          * We've failed to reconstruct the BIOS FB.  Current display state
2880          * indicates that the primary plane is visible, but has a NULL FB,
2881          * which will lead to problems later if we don't fix it up.  The
2882          * simplest solution is to just disable the primary plane now and
2883          * pretend the BIOS never had it enabled.
2884          */
2885         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2886
2887         return;
2888
2889 valid_fb:
2890         mutex_lock(&dev->struct_mutex);
2891         intel_state->vma =
2892                 intel_pin_and_fence_fb_obj(fb,
2893                                            primary->state->rotation,
2894                                            intel_plane_uses_fence(intel_state),
2895                                            &intel_state->flags);
2896         mutex_unlock(&dev->struct_mutex);
2897         if (IS_ERR(intel_state->vma)) {
2898                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2899                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2900
2901                 intel_state->vma = NULL;
2902                 drm_framebuffer_put(fb);
2903                 return;
2904         }
2905
2906         obj = intel_fb_obj(fb);
2907         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2908
2909         plane_state->src_x = 0;
2910         plane_state->src_y = 0;
2911         plane_state->src_w = fb->width << 16;
2912         plane_state->src_h = fb->height << 16;
2913
2914         plane_state->crtc_x = 0;
2915         plane_state->crtc_y = 0;
2916         plane_state->crtc_w = fb->width;
2917         plane_state->crtc_h = fb->height;
2918
2919         intel_state->base.src = drm_plane_state_src(plane_state);
2920         intel_state->base.dst = drm_plane_state_dest(plane_state);
2921
2922         if (i915_gem_object_is_tiled(obj))
2923                 dev_priv->preserve_bios_swizzle = true;
2924
2925         drm_framebuffer_get(fb);
2926         primary->fb = primary->state->fb = fb;
2927         primary->crtc = primary->state->crtc = &intel_crtc->base;
2928
2929         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2930                                 to_intel_plane_state(plane_state),
2931                                 true);
2932
2933         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2934                   &obj->frontbuffer_bits);
2935 }
2936
2937 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2938                                unsigned int rotation)
2939 {
2940         int cpp = fb->format->cpp[plane];
2941
2942         switch (fb->modifier) {
2943         case DRM_FORMAT_MOD_LINEAR:
2944         case I915_FORMAT_MOD_X_TILED:
2945                 switch (cpp) {
2946                 case 8:
2947                         return 4096;
2948                 case 4:
2949                 case 2:
2950                 case 1:
2951                         return 8192;
2952                 default:
2953                         MISSING_CASE(cpp);
2954                         break;
2955                 }
2956                 break;
2957         case I915_FORMAT_MOD_Y_TILED_CCS:
2958         case I915_FORMAT_MOD_Yf_TILED_CCS:
2959                 /* FIXME AUX plane? */
2960         case I915_FORMAT_MOD_Y_TILED:
2961         case I915_FORMAT_MOD_Yf_TILED:
2962                 switch (cpp) {
2963                 case 8:
2964                         return 2048;
2965                 case 4:
2966                         return 4096;
2967                 case 2:
2968                 case 1:
2969                         return 8192;
2970                 default:
2971                         MISSING_CASE(cpp);
2972                         break;
2973                 }
2974                 break;
2975         default:
2976                 MISSING_CASE(fb->modifier);
2977         }
2978
2979         return 2048;
2980 }
2981
2982 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2983                                            int main_x, int main_y, u32 main_offset)
2984 {
2985         const struct drm_framebuffer *fb = plane_state->base.fb;
2986         int hsub = fb->format->hsub;
2987         int vsub = fb->format->vsub;
2988         int aux_x = plane_state->aux.x;
2989         int aux_y = plane_state->aux.y;
2990         u32 aux_offset = plane_state->aux.offset;
2991         u32 alignment = intel_surf_alignment(fb, 1);
2992
2993         while (aux_offset >= main_offset && aux_y <= main_y) {
2994                 int x, y;
2995
2996                 if (aux_x == main_x && aux_y == main_y)
2997                         break;
2998
2999                 if (aux_offset == 0)
3000                         break;
3001
3002                 x = aux_x / hsub;
3003                 y = aux_y / vsub;
3004                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
3005                                                       aux_offset, aux_offset - alignment);
3006                 aux_x = x * hsub + aux_x % hsub;
3007                 aux_y = y * vsub + aux_y % vsub;
3008         }
3009
3010         if (aux_x != main_x || aux_y != main_y)
3011                 return false;
3012
3013         plane_state->aux.offset = aux_offset;
3014         plane_state->aux.x = aux_x;
3015         plane_state->aux.y = aux_y;
3016
3017         return true;
3018 }
3019
3020 static int skl_check_main_surface(const struct intel_crtc_state *crtc_state,
3021                                   struct intel_plane_state *plane_state)
3022 {
3023         struct drm_i915_private *dev_priv =
3024                 to_i915(plane_state->base.plane->dev);
3025         const struct drm_framebuffer *fb = plane_state->base.fb;
3026         unsigned int rotation = plane_state->base.rotation;
3027         int x = plane_state->base.src.x1 >> 16;
3028         int y = plane_state->base.src.y1 >> 16;
3029         int w = drm_rect_width(&plane_state->base.src) >> 16;
3030         int h = drm_rect_height(&plane_state->base.src) >> 16;
3031         int dst_x = plane_state->base.dst.x1;
3032         int pipe_src_w = crtc_state->pipe_src_w;
3033         int max_width = skl_max_plane_width(fb, 0, rotation);
3034         int max_height = 4096;
3035         u32 alignment, offset, aux_offset = plane_state->aux.offset;
3036
3037         if (w > max_width || h > max_height) {
3038                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3039                               w, h, max_width, max_height);
3040                 return -EINVAL;
3041         }
3042
3043         /*
3044          * Display WA #1175: cnl,glk
3045          * Planes other than the cursor may cause FIFO underflow and display
3046          * corruption if starting less than 4 pixels from the right edge of
3047          * the screen.
3048          * Besides the above WA fix the similar problem, where planes other
3049          * than the cursor ending less than 4 pixels from the left edge of the
3050          * screen may cause FIFO underflow and display corruption.
3051          */
3052         if ((IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
3053             (dst_x + w < 4 || dst_x > pipe_src_w - 4)) {
3054                 DRM_DEBUG_KMS("requested plane X %s position %d invalid (valid range %d-%d)\n",
3055                               dst_x + w < 4 ? "end" : "start",
3056                               dst_x + w < 4 ? dst_x + w : dst_x,
3057                               4, pipe_src_w - 4);
3058                 return -ERANGE;
3059         }
3060
3061         intel_add_fb_offsets(&x, &y, plane_state, 0);
3062         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
3063         alignment = intel_surf_alignment(fb, 0);
3064
3065         /*
3066          * AUX surface offset is specified as the distance from the
3067          * main surface offset, and it must be non-negative. Make
3068          * sure that is what we will get.
3069          */
3070         if (offset > aux_offset)
3071                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3072                                                   offset, aux_offset & ~(alignment - 1));
3073
3074         /*
3075          * When using an X-tiled surface, the plane blows up
3076          * if the x offset + width exceed the stride.
3077          *
3078          * TODO: linear and Y-tiled seem fine, Yf untested,
3079          */
3080         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3081                 int cpp = fb->format->cpp[0];
3082
3083                 while ((x + w) * cpp > fb->pitches[0]) {
3084                         if (offset == 0) {
3085                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3086                                 return -EINVAL;
3087                         }
3088
3089                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3090                                                           offset, offset - alignment);
3091                 }
3092         }
3093
3094         /*
3095          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3096          * they match with the main surface x/y offsets.
3097          */
3098         if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3099             fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3100                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3101                         if (offset == 0)
3102                                 break;
3103
3104                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3105                                                           offset, offset - alignment);
3106                 }
3107
3108                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
3109                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3110                         return -EINVAL;
3111                 }
3112         }
3113
3114         plane_state->main.offset = offset;
3115         plane_state->main.x = x;
3116         plane_state->main.y = y;
3117
3118         return 0;
3119 }
3120
3121 static int
3122 skl_check_nv12_surface(const struct intel_crtc_state *crtc_state,
3123                        struct intel_plane_state *plane_state)
3124 {
3125         /* Display WA #1106 */
3126         if (plane_state->base.rotation !=
3127             (DRM_MODE_REFLECT_X | DRM_MODE_ROTATE_90) &&
3128             plane_state->base.rotation != DRM_MODE_ROTATE_270)
3129                 return 0;
3130
3131         /*
3132          * src coordinates are rotated here.
3133          * We check height but report it as width
3134          */
3135         if (((drm_rect_height(&plane_state->base.src) >> 16) % 4) != 0) {
3136                 DRM_DEBUG_KMS("src width must be multiple "
3137                               "of 4 for rotated NV12\n");
3138                 return -EINVAL;
3139         }
3140
3141         return 0;
3142 }
3143
3144 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3145 {
3146         const struct drm_framebuffer *fb = plane_state->base.fb;
3147         unsigned int rotation = plane_state->base.rotation;
3148         int max_width = skl_max_plane_width(fb, 1, rotation);
3149         int max_height = 4096;
3150         int x = plane_state->base.src.x1 >> 17;
3151         int y = plane_state->base.src.y1 >> 17;
3152         int w = drm_rect_width(&plane_state->base.src) >> 17;
3153         int h = drm_rect_height(&plane_state->base.src) >> 17;
3154         u32 offset;
3155
3156         intel_add_fb_offsets(&x, &y, plane_state, 1);
3157         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3158
3159         /* FIXME not quite sure how/if these apply to the chroma plane */
3160         if (w > max_width || h > max_height) {
3161                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3162                               w, h, max_width, max_height);
3163                 return -EINVAL;
3164         }
3165
3166         plane_state->aux.offset = offset;
3167         plane_state->aux.x = x;
3168         plane_state->aux.y = y;
3169
3170         return 0;
3171 }
3172
3173 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3174 {
3175         const struct drm_framebuffer *fb = plane_state->base.fb;
3176         int src_x = plane_state->base.src.x1 >> 16;
3177         int src_y = plane_state->base.src.y1 >> 16;
3178         int hsub = fb->format->hsub;
3179         int vsub = fb->format->vsub;
3180         int x = src_x / hsub;
3181         int y = src_y / vsub;
3182         u32 offset;
3183
3184         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3185                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3186                               plane_state->base.rotation);
3187                 return -EINVAL;
3188         }
3189
3190         intel_add_fb_offsets(&x, &y, plane_state, 1);
3191         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3192
3193         plane_state->aux.offset = offset;
3194         plane_state->aux.x = x * hsub + src_x % hsub;
3195         plane_state->aux.y = y * vsub + src_y % vsub;
3196
3197         return 0;
3198 }
3199
3200 int skl_check_plane_surface(const struct intel_crtc_state *crtc_state,
3201                             struct intel_plane_state *plane_state)
3202 {
3203         const struct drm_framebuffer *fb = plane_state->base.fb;
3204         unsigned int rotation = plane_state->base.rotation;
3205         int ret;
3206
3207         if (rotation & DRM_MODE_REFLECT_X &&
3208             fb->modifier == DRM_FORMAT_MOD_LINEAR) {
3209                 DRM_DEBUG_KMS("horizontal flip is not supported with linear surface formats\n");
3210                 return -EINVAL;
3211         }
3212
3213         if (!plane_state->base.visible)
3214                 return 0;
3215
3216         /* Rotate src coordinates to match rotated GTT view */
3217         if (drm_rotation_90_or_270(rotation))
3218                 drm_rect_rotate(&plane_state->base.src,
3219                                 fb->width << 16, fb->height << 16,
3220                                 DRM_MODE_ROTATE_270);
3221
3222         /*
3223          * Handle the AUX surface first since
3224          * the main surface setup depends on it.
3225          */
3226         if (fb->format->format == DRM_FORMAT_NV12) {
3227                 ret = skl_check_nv12_surface(crtc_state, plane_state);
3228                 if (ret)
3229                         return ret;
3230                 ret = skl_check_nv12_aux_surface(plane_state);
3231                 if (ret)
3232                         return ret;
3233         } else if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3234                    fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3235                 ret = skl_check_ccs_aux_surface(plane_state);
3236                 if (ret)
3237                         return ret;
3238         } else {
3239                 plane_state->aux.offset = ~0xfff;
3240                 plane_state->aux.x = 0;
3241                 plane_state->aux.y = 0;
3242         }
3243
3244         ret = skl_check_main_surface(crtc_state, plane_state);
3245         if (ret)
3246                 return ret;
3247
3248         return 0;
3249 }
3250
3251 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3252                           const struct intel_plane_state *plane_state)
3253 {
3254         struct drm_i915_private *dev_priv =
3255                 to_i915(plane_state->base.plane->dev);
3256         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3257         const struct drm_framebuffer *fb = plane_state->base.fb;
3258         unsigned int rotation = plane_state->base.rotation;
3259         u32 dspcntr;
3260
3261         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3262
3263         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3264             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3265                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3266
3267         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3268                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3269
3270         if (INTEL_GEN(dev_priv) < 5)
3271                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3272
3273         switch (fb->format->format) {
3274         case DRM_FORMAT_C8:
3275                 dspcntr |= DISPPLANE_8BPP;
3276                 break;
3277         case DRM_FORMAT_XRGB1555:
3278                 dspcntr |= DISPPLANE_BGRX555;
3279                 break;
3280         case DRM_FORMAT_RGB565:
3281                 dspcntr |= DISPPLANE_BGRX565;
3282                 break;
3283         case DRM_FORMAT_XRGB8888:
3284                 dspcntr |= DISPPLANE_BGRX888;
3285                 break;
3286         case DRM_FORMAT_XBGR8888:
3287                 dspcntr |= DISPPLANE_RGBX888;
3288                 break;
3289         case DRM_FORMAT_XRGB2101010:
3290                 dspcntr |= DISPPLANE_BGRX101010;
3291                 break;
3292         case DRM_FORMAT_XBGR2101010:
3293                 dspcntr |= DISPPLANE_RGBX101010;
3294                 break;
3295         default:
3296                 MISSING_CASE(fb->format->format);
3297                 return 0;
3298         }
3299
3300         if (INTEL_GEN(dev_priv) >= 4 &&
3301             fb->modifier == I915_FORMAT_MOD_X_TILED)
3302                 dspcntr |= DISPPLANE_TILED;
3303
3304         if (rotation & DRM_MODE_ROTATE_180)
3305                 dspcntr |= DISPPLANE_ROTATE_180;
3306
3307         if (rotation & DRM_MODE_REFLECT_X)
3308                 dspcntr |= DISPPLANE_MIRROR;
3309
3310         return dspcntr;
3311 }
3312
3313 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3314 {
3315         struct drm_i915_private *dev_priv =
3316                 to_i915(plane_state->base.plane->dev);
3317         int src_x = plane_state->base.src.x1 >> 16;
3318         int src_y = plane_state->base.src.y1 >> 16;
3319         u32 offset;
3320
3321         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3322
3323         if (INTEL_GEN(dev_priv) >= 4)
3324                 offset = intel_compute_tile_offset(&src_x, &src_y,
3325                                                    plane_state, 0);
3326         else
3327                 offset = 0;
3328
3329         /* HSW/BDW do this automagically in hardware */
3330         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3331                 unsigned int rotation = plane_state->base.rotation;
3332                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3333                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3334
3335                 if (rotation & DRM_MODE_ROTATE_180) {
3336                         src_x += src_w - 1;
3337                         src_y += src_h - 1;
3338                 } else if (rotation & DRM_MODE_REFLECT_X) {
3339                         src_x += src_w - 1;
3340                 }
3341         }
3342
3343         plane_state->main.offset = offset;
3344         plane_state->main.x = src_x;
3345         plane_state->main.y = src_y;
3346
3347         return 0;
3348 }
3349
3350 static void i9xx_update_plane(struct intel_plane *plane,
3351                               const struct intel_crtc_state *crtc_state,
3352                               const struct intel_plane_state *plane_state)
3353 {
3354         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3355         const struct drm_framebuffer *fb = plane_state->base.fb;
3356         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3357         u32 linear_offset;
3358         u32 dspcntr = plane_state->ctl;
3359         i915_reg_t reg = DSPCNTR(i9xx_plane);
3360         int x = plane_state->main.x;
3361         int y = plane_state->main.y;
3362         unsigned long irqflags;
3363         u32 dspaddr_offset;
3364
3365         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3366
3367         if (INTEL_GEN(dev_priv) >= 4)
3368                 dspaddr_offset = plane_state->main.offset;
3369         else
3370                 dspaddr_offset = linear_offset;
3371
3372         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3373
3374         if (INTEL_GEN(dev_priv) < 4) {
3375                 /* pipesrc and dspsize control the size that is scaled from,
3376                  * which should always be the user's requested size.
3377                  */
3378                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3379                               ((crtc_state->pipe_src_h - 1) << 16) |
3380                               (crtc_state->pipe_src_w - 1));
3381                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3382         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3383                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3384                               ((crtc_state->pipe_src_h - 1) << 16) |
3385                               (crtc_state->pipe_src_w - 1));
3386                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3387                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3388         }
3389
3390         I915_WRITE_FW(reg, dspcntr);
3391
3392         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), fb->pitches[0]);
3393         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3394                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3395                               intel_plane_ggtt_offset(plane_state) +
3396                               dspaddr_offset);
3397                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3398         } else if (INTEL_GEN(dev_priv) >= 4) {
3399                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3400                               intel_plane_ggtt_offset(plane_state) +
3401                               dspaddr_offset);
3402                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3403                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3404         } else {
3405                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3406                               intel_plane_ggtt_offset(plane_state) +
3407                               dspaddr_offset);
3408         }
3409         POSTING_READ_FW(reg);
3410
3411         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3412 }
3413
3414 static void i9xx_disable_plane(struct intel_plane *plane,
3415                                struct intel_crtc *crtc)
3416 {
3417         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3418         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3419         unsigned long irqflags;
3420
3421         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3422
3423         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3424         if (INTEL_GEN(dev_priv) >= 4)
3425                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3426         else
3427                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3428         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3429
3430         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3431 }
3432
3433 static bool i9xx_plane_get_hw_state(struct intel_plane *plane)
3434 {
3435         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3436         enum intel_display_power_domain power_domain;
3437         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3438         enum pipe pipe = plane->pipe;
3439         bool ret;
3440
3441         /*
3442          * Not 100% correct for planes that can move between pipes,
3443          * but that's only the case for gen2-4 which don't have any
3444          * display power wells.
3445          */
3446         power_domain = POWER_DOMAIN_PIPE(pipe);
3447         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3448                 return false;
3449
3450         ret = I915_READ(DSPCNTR(i9xx_plane)) & DISPLAY_PLANE_ENABLE;
3451
3452         intel_display_power_put(dev_priv, power_domain);
3453
3454         return ret;
3455 }
3456
3457 static u32
3458 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3459 {
3460         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3461                 return 64;
3462         else
3463                 return intel_tile_width_bytes(fb, plane);
3464 }
3465
3466 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3467 {
3468         struct drm_device *dev = intel_crtc->base.dev;
3469         struct drm_i915_private *dev_priv = to_i915(dev);
3470
3471         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3472         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3473         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3474 }
3475
3476 /*
3477  * This function detaches (aka. unbinds) unused scalers in hardware
3478  */
3479 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3480 {
3481         struct intel_crtc_scaler_state *scaler_state;
3482         int i;
3483
3484         scaler_state = &intel_crtc->config->scaler_state;
3485
3486         /* loop through and disable scalers that aren't in use */
3487         for (i = 0; i < intel_crtc->num_scalers; i++) {
3488                 if (!scaler_state->scalers[i].in_use)
3489                         skl_detach_scaler(intel_crtc, i);
3490         }
3491 }
3492
3493 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3494                      unsigned int rotation)
3495 {
3496         u32 stride;
3497
3498         if (plane >= fb->format->num_planes)
3499                 return 0;
3500
3501         stride = intel_fb_pitch(fb, plane, rotation);
3502
3503         /*
3504          * The stride is either expressed as a multiple of 64 bytes chunks for
3505          * linear buffers or in number of tiles for tiled buffers.
3506          */
3507         if (drm_rotation_90_or_270(rotation))
3508                 stride /= intel_tile_height(fb, plane);
3509         else
3510                 stride /= intel_fb_stride_alignment(fb, plane);
3511
3512         return stride;
3513 }
3514
3515 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3516 {
3517         switch (pixel_format) {
3518         case DRM_FORMAT_C8:
3519                 return PLANE_CTL_FORMAT_INDEXED;
3520         case DRM_FORMAT_RGB565:
3521                 return PLANE_CTL_FORMAT_RGB_565;
3522         case DRM_FORMAT_XBGR8888:
3523         case DRM_FORMAT_ABGR8888:
3524                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3525         case DRM_FORMAT_XRGB8888:
3526         case DRM_FORMAT_ARGB8888:
3527                 return PLANE_CTL_FORMAT_XRGB_8888;
3528         case DRM_FORMAT_XRGB2101010:
3529                 return PLANE_CTL_FORMAT_XRGB_2101010;
3530         case DRM_FORMAT_XBGR2101010:
3531                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3532         case DRM_FORMAT_YUYV:
3533                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3534         case DRM_FORMAT_YVYU:
3535                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3536         case DRM_FORMAT_UYVY:
3537                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3538         case DRM_FORMAT_VYUY:
3539                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3540         case DRM_FORMAT_NV12:
3541                 return PLANE_CTL_FORMAT_NV12;
3542         default:
3543                 MISSING_CASE(pixel_format);
3544         }
3545
3546         return 0;
3547 }
3548
3549 /*
3550  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3551  * to be already pre-multiplied. We need to add a knob (or a different
3552  * DRM_FORMAT) for user-space to configure that.
3553  */
3554 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3555 {
3556         switch (pixel_format) {
3557         case DRM_FORMAT_ABGR8888:
3558         case DRM_FORMAT_ARGB8888:
3559                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3560         default:
3561                 return PLANE_CTL_ALPHA_DISABLE;
3562         }
3563 }
3564
3565 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3566 {
3567         switch (pixel_format) {
3568         case DRM_FORMAT_ABGR8888:
3569         case DRM_FORMAT_ARGB8888:
3570                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3571         default:
3572                 return PLANE_COLOR_ALPHA_DISABLE;
3573         }
3574 }
3575
3576 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3577 {
3578         switch (fb_modifier) {
3579         case DRM_FORMAT_MOD_LINEAR:
3580                 break;
3581         case I915_FORMAT_MOD_X_TILED:
3582                 return PLANE_CTL_TILED_X;
3583         case I915_FORMAT_MOD_Y_TILED:
3584                 return PLANE_CTL_TILED_Y;
3585         case I915_FORMAT_MOD_Y_TILED_CCS:
3586                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3587         case I915_FORMAT_MOD_Yf_TILED:
3588                 return PLANE_CTL_TILED_YF;
3589         case I915_FORMAT_MOD_Yf_TILED_CCS:
3590                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3591         default:
3592                 MISSING_CASE(fb_modifier);
3593         }
3594
3595         return 0;
3596 }
3597
3598 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3599 {
3600         switch (rotate) {
3601         case DRM_MODE_ROTATE_0:
3602                 break;
3603         /*
3604          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3605          * while i915 HW rotation is clockwise, thats why this swapping.
3606          */
3607         case DRM_MODE_ROTATE_90:
3608                 return PLANE_CTL_ROTATE_270;
3609         case DRM_MODE_ROTATE_180:
3610                 return PLANE_CTL_ROTATE_180;
3611         case DRM_MODE_ROTATE_270:
3612                 return PLANE_CTL_ROTATE_90;
3613         default:
3614                 MISSING_CASE(rotate);
3615         }
3616
3617         return 0;
3618 }
3619
3620 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3621 {
3622         switch (reflect) {
3623         case 0:
3624                 break;
3625         case DRM_MODE_REFLECT_X:
3626                 return PLANE_CTL_FLIP_HORIZONTAL;
3627         case DRM_MODE_REFLECT_Y:
3628         default:
3629                 MISSING_CASE(reflect);
3630         }
3631
3632         return 0;
3633 }
3634
3635 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3636                   const struct intel_plane_state *plane_state)
3637 {
3638         struct drm_i915_private *dev_priv =
3639                 to_i915(plane_state->base.plane->dev);
3640         const struct drm_framebuffer *fb = plane_state->base.fb;
3641         unsigned int rotation = plane_state->base.rotation;
3642         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3643         u32 plane_ctl;
3644
3645         plane_ctl = PLANE_CTL_ENABLE;
3646
3647         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3648                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3649                 plane_ctl |=
3650                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3651                         PLANE_CTL_PIPE_CSC_ENABLE |
3652                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3653
3654                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3655                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3656
3657                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3658                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3659         }
3660
3661         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3662         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3663         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3664
3665         if (INTEL_GEN(dev_priv) >= 10)
3666                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3667                                                 DRM_MODE_REFLECT_MASK);
3668
3669         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3670                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3671         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3672                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3673
3674         return plane_ctl;
3675 }
3676
3677 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3678                         const struct intel_plane_state *plane_state)
3679 {
3680         struct drm_i915_private *dev_priv =
3681                 to_i915(plane_state->base.plane->dev);
3682         const struct drm_framebuffer *fb = plane_state->base.fb;
3683         u32 plane_color_ctl = 0;
3684
3685         if (INTEL_GEN(dev_priv) < 11) {
3686                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3687                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3688         }
3689         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3690         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3691
3692         if (intel_format_is_yuv(fb->format->format)) {
3693                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3694                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3695                 else
3696                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3697
3698                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3699                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3700         }
3701
3702         return plane_color_ctl;
3703 }
3704
3705 static int
3706 __intel_display_resume(struct drm_device *dev,
3707                        struct drm_atomic_state *state,
3708                        struct drm_modeset_acquire_ctx *ctx)
3709 {
3710         struct drm_crtc_state *crtc_state;
3711         struct drm_crtc *crtc;
3712         int i, ret;
3713
3714         intel_modeset_setup_hw_state(dev, ctx);
3715         i915_redisable_vga(to_i915(dev));
3716
3717         if (!state)
3718                 return 0;
3719
3720         /*
3721          * We've duplicated the state, pointers to the old state are invalid.
3722          *
3723          * Don't attempt to use the old state until we commit the duplicated state.
3724          */
3725         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3726                 /*
3727                  * Force recalculation even if we restore
3728                  * current state. With fast modeset this may not result
3729                  * in a modeset when the state is compatible.
3730                  */
3731                 crtc_state->mode_changed = true;
3732         }
3733
3734         /* ignore any reset values/BIOS leftovers in the WM registers */
3735         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3736                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3737
3738         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3739
3740         WARN_ON(ret == -EDEADLK);
3741         return ret;
3742 }
3743
3744 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3745 {
3746         return intel_has_gpu_reset(dev_priv) &&
3747                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3748 }
3749
3750 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3751 {
3752         struct drm_device *dev = &dev_priv->drm;
3753         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3754         struct drm_atomic_state *state;
3755         int ret;
3756
3757         /* reset doesn't touch the display */
3758         if (!i915_modparams.force_reset_modeset_test &&
3759             !gpu_reset_clobbers_display(dev_priv))
3760                 return;
3761
3762         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3763         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3764         wake_up_all(&dev_priv->gpu_error.wait_queue);
3765
3766         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3767                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3768                 i915_gem_set_wedged(dev_priv);
3769         }
3770
3771         /*
3772          * Need mode_config.mutex so that we don't
3773          * trample ongoing ->detect() and whatnot.
3774          */
3775         mutex_lock(&dev->mode_config.mutex);
3776         drm_modeset_acquire_init(ctx, 0);
3777         while (1) {
3778                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3779                 if (ret != -EDEADLK)
3780                         break;
3781
3782                 drm_modeset_backoff(ctx);
3783         }
3784         /*
3785          * Disabling the crtcs gracefully seems nicer. Also the
3786          * g33 docs say we should at least disable all the planes.
3787          */
3788         state = drm_atomic_helper_duplicate_state(dev, ctx);
3789         if (IS_ERR(state)) {
3790                 ret = PTR_ERR(state);
3791                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3792                 return;
3793         }
3794
3795         ret = drm_atomic_helper_disable_all(dev, ctx);
3796         if (ret) {
3797                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3798                 drm_atomic_state_put(state);
3799                 return;
3800         }
3801
3802         dev_priv->modeset_restore_state = state;
3803         state->acquire_ctx = ctx;
3804 }
3805
3806 void intel_finish_reset(struct drm_i915_private *dev_priv)
3807 {
3808         struct drm_device *dev = &dev_priv->drm;
3809         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3810         struct drm_atomic_state *state;
3811         int ret;
3812
3813         /* reset doesn't touch the display */
3814         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3815                 return;
3816
3817         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3818         if (!state)
3819                 goto unlock;
3820
3821         /* reset doesn't touch the display */
3822         if (!gpu_reset_clobbers_display(dev_priv)) {
3823                 /* for testing only restore the display */
3824                 ret = __intel_display_resume(dev, state, ctx);
3825                 if (ret)
3826                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3827         } else {
3828                 /*
3829                  * The display has been reset as well,
3830                  * so need a full re-initialization.
3831                  */
3832                 intel_runtime_pm_disable_interrupts(dev_priv);
3833                 intel_runtime_pm_enable_interrupts(dev_priv);
3834
3835                 intel_pps_unlock_regs_wa(dev_priv);
3836                 intel_modeset_init_hw(dev);
3837                 intel_init_clock_gating(dev_priv);
3838
3839                 spin_lock_irq(&dev_priv->irq_lock);
3840                 if (dev_priv->display.hpd_irq_setup)
3841                         dev_priv->display.hpd_irq_setup(dev_priv);
3842                 spin_unlock_irq(&dev_priv->irq_lock);
3843
3844                 ret = __intel_display_resume(dev, state, ctx);
3845                 if (ret)
3846                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3847
3848                 intel_hpd_init(dev_priv);
3849         }
3850
3851         drm_atomic_state_put(state);
3852 unlock:
3853         drm_modeset_drop_locks(ctx);
3854         drm_modeset_acquire_fini(ctx);
3855         mutex_unlock(&dev->mode_config.mutex);
3856
3857         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3858 }
3859
3860 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3861                                      const struct intel_crtc_state *new_crtc_state)
3862 {
3863         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3864         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3865
3866         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3867         crtc->base.mode = new_crtc_state->base.mode;
3868
3869         /*
3870          * Update pipe size and adjust fitter if needed: the reason for this is
3871          * that in compute_mode_changes we check the native mode (not the pfit
3872          * mode) to see if we can flip rather than do a full mode set. In the
3873          * fastboot case, we'll flip, but if we don't update the pipesrc and
3874          * pfit state, we'll end up with a big fb scanned out into the wrong
3875          * sized surface.
3876          */
3877
3878         I915_WRITE(PIPESRC(crtc->pipe),
3879                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3880                    (new_crtc_state->pipe_src_h - 1));
3881
3882         /* on skylake this is done by detaching scalers */
3883         if (INTEL_GEN(dev_priv) >= 9) {
3884                 skl_detach_scalers(crtc);
3885
3886                 if (new_crtc_state->pch_pfit.enabled)
3887                         skylake_pfit_enable(crtc);
3888         } else if (HAS_PCH_SPLIT(dev_priv)) {
3889                 if (new_crtc_state->pch_pfit.enabled)
3890                         ironlake_pfit_enable(crtc);
3891                 else if (old_crtc_state->pch_pfit.enabled)
3892                         ironlake_pfit_disable(crtc, true);
3893         }
3894 }
3895
3896 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3897 {
3898         struct drm_device *dev = crtc->base.dev;
3899         struct drm_i915_private *dev_priv = to_i915(dev);
3900         int pipe = crtc->pipe;
3901         i915_reg_t reg;
3902         u32 temp;
3903
3904         /* enable normal train */
3905         reg = FDI_TX_CTL(pipe);
3906         temp = I915_READ(reg);
3907         if (IS_IVYBRIDGE(dev_priv)) {
3908                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3909                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3910         } else {
3911                 temp &= ~FDI_LINK_TRAIN_NONE;
3912                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3913         }
3914         I915_WRITE(reg, temp);
3915
3916         reg = FDI_RX_CTL(pipe);
3917         temp = I915_READ(reg);
3918         if (HAS_PCH_CPT(dev_priv)) {
3919                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3920                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3921         } else {
3922                 temp &= ~FDI_LINK_TRAIN_NONE;
3923                 temp |= FDI_LINK_TRAIN_NONE;
3924         }
3925         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3926
3927         /* wait one idle pattern time */
3928         POSTING_READ(reg);
3929         udelay(1000);
3930
3931         /* IVB wants error correction enabled */
3932         if (IS_IVYBRIDGE(dev_priv))
3933                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3934                            FDI_FE_ERRC_ENABLE);
3935 }
3936
3937 /* The FDI link training functions for ILK/Ibexpeak. */
3938 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3939                                     const struct intel_crtc_state *crtc_state)
3940 {
3941         struct drm_device *dev = crtc->base.dev;
3942         struct drm_i915_private *dev_priv = to_i915(dev);
3943         int pipe = crtc->pipe;
3944         i915_reg_t reg;
3945         u32 temp, tries;
3946
3947         /* FDI needs bits from pipe first */
3948         assert_pipe_enabled(dev_priv, pipe);
3949
3950         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3951            for train result */
3952         reg = FDI_RX_IMR(pipe);
3953         temp = I915_READ(reg);
3954         temp &= ~FDI_RX_SYMBOL_LOCK;
3955         temp &= ~FDI_RX_BIT_LOCK;
3956         I915_WRITE(reg, temp);
3957         I915_READ(reg);
3958         udelay(150);
3959
3960         /* enable CPU FDI TX and PCH FDI RX */
3961         reg = FDI_TX_CTL(pipe);
3962         temp = I915_READ(reg);
3963         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3964         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3965         temp &= ~FDI_LINK_TRAIN_NONE;
3966         temp |= FDI_LINK_TRAIN_PATTERN_1;
3967         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3968
3969         reg = FDI_RX_CTL(pipe);
3970         temp = I915_READ(reg);
3971         temp &= ~FDI_LINK_TRAIN_NONE;
3972         temp |= FDI_LINK_TRAIN_PATTERN_1;
3973         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3974
3975         POSTING_READ(reg);
3976         udelay(150);
3977
3978         /* Ironlake workaround, enable clock pointer after FDI enable*/
3979         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3980         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3981                    FDI_RX_PHASE_SYNC_POINTER_EN);
3982
3983         reg = FDI_RX_IIR(pipe);
3984         for (tries = 0; tries < 5; tries++) {
3985                 temp = I915_READ(reg);
3986                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3987
3988                 if ((temp & FDI_RX_BIT_LOCK)) {
3989                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3990                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3991                         break;
3992                 }
3993         }
3994         if (tries == 5)
3995                 DRM_ERROR("FDI train 1 fail!\n");
3996
3997         /* Train 2 */
3998         reg = FDI_TX_CTL(pipe);
3999         temp = I915_READ(reg);
4000         temp &= ~FDI_LINK_TRAIN_NONE;
4001         temp |= FDI_LINK_TRAIN_PATTERN_2;
4002         I915_WRITE(reg, temp);
4003
4004         reg = FDI_RX_CTL(pipe);
4005         temp = I915_READ(reg);
4006         temp &= ~FDI_LINK_TRAIN_NONE;
4007         temp |= FDI_LINK_TRAIN_PATTERN_2;
4008         I915_WRITE(reg, temp);
4009
4010         POSTING_READ(reg);
4011         udelay(150);
4012
4013         reg = FDI_RX_IIR(pipe);
4014         for (tries = 0; tries < 5; tries++) {
4015                 temp = I915_READ(reg);
4016                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4017
4018                 if (temp & FDI_RX_SYMBOL_LOCK) {
4019                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4020                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4021                         break;
4022                 }
4023         }
4024         if (tries == 5)
4025                 DRM_ERROR("FDI train 2 fail!\n");
4026
4027         DRM_DEBUG_KMS("FDI train done\n");
4028
4029 }
4030
4031 static const int snb_b_fdi_train_param[] = {
4032         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4033         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4034         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4035         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4036 };
4037
4038 /* The FDI link training functions for SNB/Cougarpoint. */
4039 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4040                                 const struct intel_crtc_state *crtc_state)
4041 {
4042         struct drm_device *dev = crtc->base.dev;
4043         struct drm_i915_private *dev_priv = to_i915(dev);
4044         int pipe = crtc->pipe;
4045         i915_reg_t reg;
4046         u32 temp, i, retry;
4047
4048         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4049            for train result */
4050         reg = FDI_RX_IMR(pipe);
4051         temp = I915_READ(reg);
4052         temp &= ~FDI_RX_SYMBOL_LOCK;
4053         temp &= ~FDI_RX_BIT_LOCK;
4054         I915_WRITE(reg, temp);
4055
4056         POSTING_READ(reg);
4057         udelay(150);
4058
4059         /* enable CPU FDI TX and PCH FDI RX */
4060         reg = FDI_TX_CTL(pipe);
4061         temp = I915_READ(reg);
4062         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4063         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4064         temp &= ~FDI_LINK_TRAIN_NONE;
4065         temp |= FDI_LINK_TRAIN_PATTERN_1;
4066         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4067         /* SNB-B */
4068         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4069         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4070
4071         I915_WRITE(FDI_RX_MISC(pipe),
4072                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
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_1_CPT;
4079         } else {
4080                 temp &= ~FDI_LINK_TRAIN_NONE;
4081                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4082         }
4083         I915_WRITE(reg, temp | FDI_RX_ENABLE);
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_BIT_LOCK) {
4103                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4104                                 DRM_DEBUG_KMS("FDI train 1 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 1 fail!\n");
4114
4115         /* Train 2 */
4116         reg = FDI_TX_CTL(pipe);
4117         temp = I915_READ(reg);
4118         temp &= ~FDI_LINK_TRAIN_NONE;
4119         temp |= FDI_LINK_TRAIN_PATTERN_2;
4120         if (IS_GEN6(dev_priv)) {
4121                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4122                 /* SNB-B */
4123                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4124         }
4125         I915_WRITE(reg, temp);
4126
4127         reg = FDI_RX_CTL(pipe);
4128         temp = I915_READ(reg);
4129         if (HAS_PCH_CPT(dev_priv)) {
4130                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4131                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4132         } else {
4133                 temp &= ~FDI_LINK_TRAIN_NONE;
4134                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4135         }
4136         I915_WRITE(reg, temp);
4137
4138         POSTING_READ(reg);
4139         udelay(150);
4140
4141         for (i = 0; i < 4; i++) {
4142                 reg = FDI_TX_CTL(pipe);
4143                 temp = I915_READ(reg);
4144                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4145                 temp |= snb_b_fdi_train_param[i];
4146                 I915_WRITE(reg, temp);
4147
4148                 POSTING_READ(reg);
4149                 udelay(500);
4150
4151                 for (retry = 0; retry < 5; retry++) {
4152                         reg = FDI_RX_IIR(pipe);
4153                         temp = I915_READ(reg);
4154                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4155                         if (temp & FDI_RX_SYMBOL_LOCK) {
4156                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4157                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4158                                 break;
4159                         }
4160                         udelay(50);
4161                 }
4162                 if (retry < 5)
4163                         break;
4164         }
4165         if (i == 4)
4166                 DRM_ERROR("FDI train 2 fail!\n");
4167
4168         DRM_DEBUG_KMS("FDI train done.\n");
4169 }
4170
4171 /* Manual link training for Ivy Bridge A0 parts */
4172 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4173                                       const struct intel_crtc_state *crtc_state)
4174 {
4175         struct drm_device *dev = crtc->base.dev;
4176         struct drm_i915_private *dev_priv = to_i915(dev);
4177         int pipe = crtc->pipe;
4178         i915_reg_t reg;
4179         u32 temp, i, j;
4180
4181         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4182            for train result */
4183         reg = FDI_RX_IMR(pipe);
4184         temp = I915_READ(reg);
4185         temp &= ~FDI_RX_SYMBOL_LOCK;
4186         temp &= ~FDI_RX_BIT_LOCK;
4187         I915_WRITE(reg, temp);
4188
4189         POSTING_READ(reg);
4190         udelay(150);
4191
4192         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4193                       I915_READ(FDI_RX_IIR(pipe)));
4194
4195         /* Try each vswing and preemphasis setting twice before moving on */
4196         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4197                 /* disable first in case we need to retry */
4198                 reg = FDI_TX_CTL(pipe);
4199                 temp = I915_READ(reg);
4200                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4201                 temp &= ~FDI_TX_ENABLE;
4202                 I915_WRITE(reg, temp);
4203
4204                 reg = FDI_RX_CTL(pipe);
4205                 temp = I915_READ(reg);
4206                 temp &= ~FDI_LINK_TRAIN_AUTO;
4207                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4208                 temp &= ~FDI_RX_ENABLE;
4209                 I915_WRITE(reg, temp);
4210
4211                 /* enable CPU FDI TX and PCH FDI RX */
4212                 reg = FDI_TX_CTL(pipe);
4213                 temp = I915_READ(reg);
4214                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4215                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4216                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4217                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4218                 temp |= snb_b_fdi_train_param[j/2];
4219                 temp |= FDI_COMPOSITE_SYNC;
4220                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4221
4222                 I915_WRITE(FDI_RX_MISC(pipe),
4223                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4224
4225                 reg = FDI_RX_CTL(pipe);
4226                 temp = I915_READ(reg);
4227                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4228                 temp |= FDI_COMPOSITE_SYNC;
4229                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4230
4231                 POSTING_READ(reg);
4232                 udelay(1); /* should be 0.5us */
4233
4234                 for (i = 0; i < 4; i++) {
4235                         reg = FDI_RX_IIR(pipe);
4236                         temp = I915_READ(reg);
4237                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4238
4239                         if (temp & FDI_RX_BIT_LOCK ||
4240                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4241                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4242                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4243                                               i);
4244                                 break;
4245                         }
4246                         udelay(1); /* should be 0.5us */
4247                 }
4248                 if (i == 4) {
4249                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4250                         continue;
4251                 }
4252
4253                 /* Train 2 */
4254                 reg = FDI_TX_CTL(pipe);
4255                 temp = I915_READ(reg);
4256                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4257                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4258                 I915_WRITE(reg, temp);
4259
4260                 reg = FDI_RX_CTL(pipe);
4261                 temp = I915_READ(reg);
4262                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4263                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4264                 I915_WRITE(reg, temp);
4265
4266                 POSTING_READ(reg);
4267                 udelay(2); /* should be 1.5us */
4268
4269                 for (i = 0; i < 4; i++) {
4270                         reg = FDI_RX_IIR(pipe);
4271                         temp = I915_READ(reg);
4272                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4273
4274                         if (temp & FDI_RX_SYMBOL_LOCK ||
4275                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4276                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4277                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4278                                               i);
4279                                 goto train_done;
4280                         }
4281                         udelay(2); /* should be 1.5us */
4282                 }
4283                 if (i == 4)
4284                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4285         }
4286
4287 train_done:
4288         DRM_DEBUG_KMS("FDI train done.\n");
4289 }
4290
4291 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4292 {
4293         struct drm_device *dev = intel_crtc->base.dev;
4294         struct drm_i915_private *dev_priv = to_i915(dev);
4295         int pipe = intel_crtc->pipe;
4296         i915_reg_t reg;
4297         u32 temp;
4298
4299         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4300         reg = FDI_RX_CTL(pipe);
4301         temp = I915_READ(reg);
4302         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4303         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4304         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4305         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4306
4307         POSTING_READ(reg);
4308         udelay(200);
4309
4310         /* Switch from Rawclk to PCDclk */
4311         temp = I915_READ(reg);
4312         I915_WRITE(reg, temp | FDI_PCDCLK);
4313
4314         POSTING_READ(reg);
4315         udelay(200);
4316
4317         /* Enable CPU FDI TX PLL, always on for Ironlake */
4318         reg = FDI_TX_CTL(pipe);
4319         temp = I915_READ(reg);
4320         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4321                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4322
4323                 POSTING_READ(reg);
4324                 udelay(100);
4325         }
4326 }
4327
4328 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4329 {
4330         struct drm_device *dev = intel_crtc->base.dev;
4331         struct drm_i915_private *dev_priv = to_i915(dev);
4332         int pipe = intel_crtc->pipe;
4333         i915_reg_t reg;
4334         u32 temp;
4335
4336         /* Switch from PCDclk to Rawclk */
4337         reg = FDI_RX_CTL(pipe);
4338         temp = I915_READ(reg);
4339         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4340
4341         /* Disable CPU FDI TX PLL */
4342         reg = FDI_TX_CTL(pipe);
4343         temp = I915_READ(reg);
4344         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4345
4346         POSTING_READ(reg);
4347         udelay(100);
4348
4349         reg = FDI_RX_CTL(pipe);
4350         temp = I915_READ(reg);
4351         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4352
4353         /* Wait for the clocks to turn off. */
4354         POSTING_READ(reg);
4355         udelay(100);
4356 }
4357
4358 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4359 {
4360         struct drm_device *dev = crtc->dev;
4361         struct drm_i915_private *dev_priv = to_i915(dev);
4362         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4363         int pipe = intel_crtc->pipe;
4364         i915_reg_t reg;
4365         u32 temp;
4366
4367         /* disable CPU FDI tx and PCH FDI rx */
4368         reg = FDI_TX_CTL(pipe);
4369         temp = I915_READ(reg);
4370         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4371         POSTING_READ(reg);
4372
4373         reg = FDI_RX_CTL(pipe);
4374         temp = I915_READ(reg);
4375         temp &= ~(0x7 << 16);
4376         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4377         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4378
4379         POSTING_READ(reg);
4380         udelay(100);
4381
4382         /* Ironlake workaround, disable clock pointer after downing FDI */
4383         if (HAS_PCH_IBX(dev_priv))
4384                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4385
4386         /* still set train pattern 1 */
4387         reg = FDI_TX_CTL(pipe);
4388         temp = I915_READ(reg);
4389         temp &= ~FDI_LINK_TRAIN_NONE;
4390         temp |= FDI_LINK_TRAIN_PATTERN_1;
4391         I915_WRITE(reg, temp);
4392
4393         reg = FDI_RX_CTL(pipe);
4394         temp = I915_READ(reg);
4395         if (HAS_PCH_CPT(dev_priv)) {
4396                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4397                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4398         } else {
4399                 temp &= ~FDI_LINK_TRAIN_NONE;
4400                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4401         }
4402         /* BPC in FDI rx is consistent with that in PIPECONF */
4403         temp &= ~(0x07 << 16);
4404         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4405         I915_WRITE(reg, temp);
4406
4407         POSTING_READ(reg);
4408         udelay(100);
4409 }
4410
4411 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4412 {
4413         struct drm_crtc *crtc;
4414         bool cleanup_done;
4415
4416         drm_for_each_crtc(crtc, &dev_priv->drm) {
4417                 struct drm_crtc_commit *commit;
4418                 spin_lock(&crtc->commit_lock);
4419                 commit = list_first_entry_or_null(&crtc->commit_list,
4420                                                   struct drm_crtc_commit, commit_entry);
4421                 cleanup_done = commit ?
4422                         try_wait_for_completion(&commit->cleanup_done) : true;
4423                 spin_unlock(&crtc->commit_lock);
4424
4425                 if (cleanup_done)
4426                         continue;
4427
4428                 drm_crtc_wait_one_vblank(crtc);
4429
4430                 return true;
4431         }
4432
4433         return false;
4434 }
4435
4436 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4437 {
4438         u32 temp;
4439
4440         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4441
4442         mutex_lock(&dev_priv->sb_lock);
4443
4444         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4445         temp |= SBI_SSCCTL_DISABLE;
4446         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4447
4448         mutex_unlock(&dev_priv->sb_lock);
4449 }
4450
4451 /* Program iCLKIP clock to the desired frequency */
4452 static void lpt_program_iclkip(struct intel_crtc *crtc)
4453 {
4454         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4455         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4456         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4457         u32 temp;
4458
4459         lpt_disable_iclkip(dev_priv);
4460
4461         /* The iCLK virtual clock root frequency is in MHz,
4462          * but the adjusted_mode->crtc_clock in in KHz. To get the
4463          * divisors, it is necessary to divide one by another, so we
4464          * convert the virtual clock precision to KHz here for higher
4465          * precision.
4466          */
4467         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4468                 u32 iclk_virtual_root_freq = 172800 * 1000;
4469                 u32 iclk_pi_range = 64;
4470                 u32 desired_divisor;
4471
4472                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4473                                                     clock << auxdiv);
4474                 divsel = (desired_divisor / iclk_pi_range) - 2;
4475                 phaseinc = desired_divisor % iclk_pi_range;
4476
4477                 /*
4478                  * Near 20MHz is a corner case which is
4479                  * out of range for the 7-bit divisor
4480                  */
4481                 if (divsel <= 0x7f)
4482                         break;
4483         }
4484
4485         /* This should not happen with any sane values */
4486         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4487                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4488         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4489                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4490
4491         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4492                         clock,
4493                         auxdiv,
4494                         divsel,
4495                         phasedir,
4496                         phaseinc);
4497
4498         mutex_lock(&dev_priv->sb_lock);
4499
4500         /* Program SSCDIVINTPHASE6 */
4501         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4502         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4503         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4504         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4505         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4506         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4507         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4508         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4509
4510         /* Program SSCAUXDIV */
4511         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4512         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4513         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4514         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4515
4516         /* Enable modulator and associated divider */
4517         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4518         temp &= ~SBI_SSCCTL_DISABLE;
4519         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4520
4521         mutex_unlock(&dev_priv->sb_lock);
4522
4523         /* Wait for initialization time */
4524         udelay(24);
4525
4526         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4527 }
4528
4529 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4530 {
4531         u32 divsel, phaseinc, auxdiv;
4532         u32 iclk_virtual_root_freq = 172800 * 1000;
4533         u32 iclk_pi_range = 64;
4534         u32 desired_divisor;
4535         u32 temp;
4536
4537         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4538                 return 0;
4539
4540         mutex_lock(&dev_priv->sb_lock);
4541
4542         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4543         if (temp & SBI_SSCCTL_DISABLE) {
4544                 mutex_unlock(&dev_priv->sb_lock);
4545                 return 0;
4546         }
4547
4548         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4549         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4550                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4551         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4552                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4553
4554         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4555         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4556                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4557
4558         mutex_unlock(&dev_priv->sb_lock);
4559
4560         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4561
4562         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4563                                  desired_divisor << auxdiv);
4564 }
4565
4566 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4567                                                 enum pipe pch_transcoder)
4568 {
4569         struct drm_device *dev = crtc->base.dev;
4570         struct drm_i915_private *dev_priv = to_i915(dev);
4571         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4572
4573         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4574                    I915_READ(HTOTAL(cpu_transcoder)));
4575         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4576                    I915_READ(HBLANK(cpu_transcoder)));
4577         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4578                    I915_READ(HSYNC(cpu_transcoder)));
4579
4580         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4581                    I915_READ(VTOTAL(cpu_transcoder)));
4582         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4583                    I915_READ(VBLANK(cpu_transcoder)));
4584         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4585                    I915_READ(VSYNC(cpu_transcoder)));
4586         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4587                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4588 }
4589
4590 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4591 {
4592         struct drm_i915_private *dev_priv = to_i915(dev);
4593         uint32_t temp;
4594
4595         temp = I915_READ(SOUTH_CHICKEN1);
4596         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4597                 return;
4598
4599         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4600         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4601
4602         temp &= ~FDI_BC_BIFURCATION_SELECT;
4603         if (enable)
4604                 temp |= FDI_BC_BIFURCATION_SELECT;
4605
4606         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4607         I915_WRITE(SOUTH_CHICKEN1, temp);
4608         POSTING_READ(SOUTH_CHICKEN1);
4609 }
4610
4611 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4612 {
4613         struct drm_device *dev = intel_crtc->base.dev;
4614
4615         switch (intel_crtc->pipe) {
4616         case PIPE_A:
4617                 break;
4618         case PIPE_B:
4619                 if (intel_crtc->config->fdi_lanes > 2)
4620                         cpt_set_fdi_bc_bifurcation(dev, false);
4621                 else
4622                         cpt_set_fdi_bc_bifurcation(dev, true);
4623
4624                 break;
4625         case PIPE_C:
4626                 cpt_set_fdi_bc_bifurcation(dev, true);
4627
4628                 break;
4629         default:
4630                 BUG();
4631         }
4632 }
4633
4634 /* Return which DP Port should be selected for Transcoder DP control */
4635 static enum port
4636 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4637 {
4638         struct drm_device *dev = crtc->base.dev;
4639         struct intel_encoder *encoder;
4640
4641         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4642                 if (encoder->type == INTEL_OUTPUT_DP ||
4643                     encoder->type == INTEL_OUTPUT_EDP)
4644                         return encoder->port;
4645         }
4646
4647         return -1;
4648 }
4649
4650 /*
4651  * Enable PCH resources required for PCH ports:
4652  *   - PCH PLLs
4653  *   - FDI training & RX/TX
4654  *   - update transcoder timings
4655  *   - DP transcoding bits
4656  *   - transcoder
4657  */
4658 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4659 {
4660         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4661         struct drm_device *dev = crtc->base.dev;
4662         struct drm_i915_private *dev_priv = to_i915(dev);
4663         int pipe = crtc->pipe;
4664         u32 temp;
4665
4666         assert_pch_transcoder_disabled(dev_priv, pipe);
4667
4668         if (IS_IVYBRIDGE(dev_priv))
4669                 ivybridge_update_fdi_bc_bifurcation(crtc);
4670
4671         /* Write the TU size bits before fdi link training, so that error
4672          * detection works. */
4673         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4674                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4675
4676         /* For PCH output, training FDI link */
4677         dev_priv->display.fdi_link_train(crtc, crtc_state);
4678
4679         /* We need to program the right clock selection before writing the pixel
4680          * mutliplier into the DPLL. */
4681         if (HAS_PCH_CPT(dev_priv)) {
4682                 u32 sel;
4683
4684                 temp = I915_READ(PCH_DPLL_SEL);
4685                 temp |= TRANS_DPLL_ENABLE(pipe);
4686                 sel = TRANS_DPLLB_SEL(pipe);
4687                 if (crtc_state->shared_dpll ==
4688                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4689                         temp |= sel;
4690                 else
4691                         temp &= ~sel;
4692                 I915_WRITE(PCH_DPLL_SEL, temp);
4693         }
4694
4695         /* XXX: pch pll's can be enabled any time before we enable the PCH
4696          * transcoder, and we actually should do this to not upset any PCH
4697          * transcoder that already use the clock when we share it.
4698          *
4699          * Note that enable_shared_dpll tries to do the right thing, but
4700          * get_shared_dpll unconditionally resets the pll - we need that to have
4701          * the right LVDS enable sequence. */
4702         intel_enable_shared_dpll(crtc);
4703
4704         /* set transcoder timing, panel must allow it */
4705         assert_panel_unlocked(dev_priv, pipe);
4706         ironlake_pch_transcoder_set_timings(crtc, pipe);
4707
4708         intel_fdi_normal_train(crtc);
4709
4710         /* For PCH DP, enable TRANS_DP_CTL */
4711         if (HAS_PCH_CPT(dev_priv) &&
4712             intel_crtc_has_dp_encoder(crtc_state)) {
4713                 const struct drm_display_mode *adjusted_mode =
4714                         &crtc_state->base.adjusted_mode;
4715                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4716                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4717                 temp = I915_READ(reg);
4718                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4719                           TRANS_DP_SYNC_MASK |
4720                           TRANS_DP_BPC_MASK);
4721                 temp |= TRANS_DP_OUTPUT_ENABLE;
4722                 temp |= bpc << 9; /* same format but at 11:9 */
4723
4724                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4725                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4726                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4727                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4728
4729                 switch (intel_trans_dp_port_sel(crtc)) {
4730                 case PORT_B:
4731                         temp |= TRANS_DP_PORT_SEL_B;
4732                         break;
4733                 case PORT_C:
4734                         temp |= TRANS_DP_PORT_SEL_C;
4735                         break;
4736                 case PORT_D:
4737                         temp |= TRANS_DP_PORT_SEL_D;
4738                         break;
4739                 default:
4740                         BUG();
4741                 }
4742
4743                 I915_WRITE(reg, temp);
4744         }
4745
4746         ironlake_enable_pch_transcoder(dev_priv, pipe);
4747 }
4748
4749 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4750 {
4751         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4752         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4753         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4754
4755         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4756
4757         lpt_program_iclkip(crtc);
4758
4759         /* Set transcoder timing. */
4760         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4761
4762         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4763 }
4764
4765 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4766 {
4767         struct drm_i915_private *dev_priv = to_i915(dev);
4768         i915_reg_t dslreg = PIPEDSL(pipe);
4769         u32 temp;
4770
4771         temp = I915_READ(dslreg);
4772         udelay(500);
4773         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4774                 if (wait_for(I915_READ(dslreg) != temp, 5))
4775                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4776         }
4777 }
4778
4779 static int
4780 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4781                   unsigned int scaler_user, int *scaler_id,
4782                   int src_w, int src_h, int dst_w, int dst_h,
4783                   bool plane_scaler_check,
4784                   uint32_t pixel_format)
4785 {
4786         struct intel_crtc_scaler_state *scaler_state =
4787                 &crtc_state->scaler_state;
4788         struct intel_crtc *intel_crtc =
4789                 to_intel_crtc(crtc_state->base.crtc);
4790         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4791         const struct drm_display_mode *adjusted_mode =
4792                 &crtc_state->base.adjusted_mode;
4793         int need_scaling;
4794
4795         /*
4796          * Src coordinates are already rotated by 270 degrees for
4797          * the 90/270 degree plane rotation cases (to match the
4798          * GTT mapping), hence no need to account for rotation here.
4799          */
4800         need_scaling = src_w != dst_w || src_h != dst_h;
4801
4802         if (plane_scaler_check)
4803                 if (pixel_format == DRM_FORMAT_NV12)
4804                         need_scaling = true;
4805
4806         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4807                 need_scaling = true;
4808
4809         /*
4810          * Scaling/fitting not supported in IF-ID mode in GEN9+
4811          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4812          * Once NV12 is enabled, handle it here while allocating scaler
4813          * for NV12.
4814          */
4815         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4816             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4817                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4818                 return -EINVAL;
4819         }
4820
4821         /*
4822          * if plane is being disabled or scaler is no more required or force detach
4823          *  - free scaler binded to this plane/crtc
4824          *  - in order to do this, update crtc->scaler_usage
4825          *
4826          * Here scaler state in crtc_state is set free so that
4827          * scaler can be assigned to other user. Actual register
4828          * update to free the scaler is done in plane/panel-fit programming.
4829          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4830          */
4831         if (force_detach || !need_scaling) {
4832                 if (*scaler_id >= 0) {
4833                         scaler_state->scaler_users &= ~(1 << scaler_user);
4834                         scaler_state->scalers[*scaler_id].in_use = 0;
4835
4836                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4837                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4838                                 intel_crtc->pipe, scaler_user, *scaler_id,
4839                                 scaler_state->scaler_users);
4840                         *scaler_id = -1;
4841                 }
4842                 return 0;
4843         }
4844
4845         if (plane_scaler_check && pixel_format == DRM_FORMAT_NV12 &&
4846             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4847                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4848                 return -EINVAL;
4849         }
4850
4851         /* range checks */
4852         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4853             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4854             (IS_GEN11(dev_priv) &&
4855              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4856               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4857             (!IS_GEN11(dev_priv) &&
4858              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4859               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4860                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4861                         "size is out of scaler range\n",
4862                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4863                 return -EINVAL;
4864         }
4865
4866         /* mark this plane as a scaler user in crtc_state */
4867         scaler_state->scaler_users |= (1 << scaler_user);
4868         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4869                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4870                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4871                 scaler_state->scaler_users);
4872
4873         return 0;
4874 }
4875
4876 /**
4877  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4878  *
4879  * @state: crtc's scaler state
4880  *
4881  * Return
4882  *     0 - scaler_usage updated successfully
4883  *    error - requested scaling cannot be supported or other error condition
4884  */
4885 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4886 {
4887         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4888
4889         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4890                                  &state->scaler_state.scaler_id,
4891                                  state->pipe_src_w, state->pipe_src_h,
4892                                  adjusted_mode->crtc_hdisplay,
4893                                  adjusted_mode->crtc_vdisplay, false, 0);
4894 }
4895
4896 /**
4897  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4898  * @crtc_state: crtc's scaler state
4899  * @plane_state: atomic plane state to update
4900  *
4901  * Return
4902  *     0 - scaler_usage updated successfully
4903  *    error - requested scaling cannot be supported or other error condition
4904  */
4905 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4906                                    struct intel_plane_state *plane_state)
4907 {
4908
4909         struct intel_plane *intel_plane =
4910                 to_intel_plane(plane_state->base.plane);
4911         struct drm_framebuffer *fb = plane_state->base.fb;
4912         int ret;
4913
4914         bool force_detach = !fb || !plane_state->base.visible;
4915
4916         ret = skl_update_scaler(crtc_state, force_detach,
4917                                 drm_plane_index(&intel_plane->base),
4918                                 &plane_state->scaler_id,
4919                                 drm_rect_width(&plane_state->base.src) >> 16,
4920                                 drm_rect_height(&plane_state->base.src) >> 16,
4921                                 drm_rect_width(&plane_state->base.dst),
4922                                 drm_rect_height(&plane_state->base.dst),
4923                                 fb ? true : false, fb ? fb->format->format : 0);
4924
4925         if (ret || plane_state->scaler_id < 0)
4926                 return ret;
4927
4928         /* check colorkey */
4929         if (plane_state->ckey.flags) {
4930                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4931                               intel_plane->base.base.id,
4932                               intel_plane->base.name);
4933                 return -EINVAL;
4934         }
4935
4936         /* Check src format */
4937         switch (fb->format->format) {
4938         case DRM_FORMAT_RGB565:
4939         case DRM_FORMAT_XBGR8888:
4940         case DRM_FORMAT_XRGB8888:
4941         case DRM_FORMAT_ABGR8888:
4942         case DRM_FORMAT_ARGB8888:
4943         case DRM_FORMAT_XRGB2101010:
4944         case DRM_FORMAT_XBGR2101010:
4945         case DRM_FORMAT_YUYV:
4946         case DRM_FORMAT_YVYU:
4947         case DRM_FORMAT_UYVY:
4948         case DRM_FORMAT_VYUY:
4949         case DRM_FORMAT_NV12:
4950                 break;
4951         default:
4952                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4953                               intel_plane->base.base.id, intel_plane->base.name,
4954                               fb->base.id, fb->format->format);
4955                 return -EINVAL;
4956         }
4957
4958         return 0;
4959 }
4960
4961 static void skylake_scaler_disable(struct intel_crtc *crtc)
4962 {
4963         int i;
4964
4965         for (i = 0; i < crtc->num_scalers; i++)
4966                 skl_detach_scaler(crtc, i);
4967 }
4968
4969 static void skylake_pfit_enable(struct intel_crtc *crtc)
4970 {
4971         struct drm_device *dev = crtc->base.dev;
4972         struct drm_i915_private *dev_priv = to_i915(dev);
4973         int pipe = crtc->pipe;
4974         struct intel_crtc_scaler_state *scaler_state =
4975                 &crtc->config->scaler_state;
4976
4977         if (crtc->config->pch_pfit.enabled) {
4978                 int id;
4979
4980                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4981                         return;
4982
4983                 id = scaler_state->scaler_id;
4984                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4985                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4986                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4987                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4988         }
4989 }
4990
4991 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4992 {
4993         struct drm_device *dev = crtc->base.dev;
4994         struct drm_i915_private *dev_priv = to_i915(dev);
4995         int pipe = crtc->pipe;
4996
4997         if (crtc->config->pch_pfit.enabled) {
4998                 /* Force use of hard-coded filter coefficients
4999                  * as some pre-programmed values are broken,
5000                  * e.g. x201.
5001                  */
5002                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5003                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5004                                                  PF_PIPE_SEL_IVB(pipe));
5005                 else
5006                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5007                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
5008                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
5009         }
5010 }
5011
5012 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5013 {
5014         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5015         struct drm_device *dev = crtc->base.dev;
5016         struct drm_i915_private *dev_priv = to_i915(dev);
5017
5018         if (!crtc_state->ips_enabled)
5019                 return;
5020
5021         /*
5022          * We can only enable IPS after we enable a plane and wait for a vblank
5023          * This function is called from post_plane_update, which is run after
5024          * a vblank wait.
5025          */
5026         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5027
5028         if (IS_BROADWELL(dev_priv)) {
5029                 mutex_lock(&dev_priv->pcu_lock);
5030                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5031                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5032                 mutex_unlock(&dev_priv->pcu_lock);
5033                 /* Quoting Art Runyan: "its not safe to expect any particular
5034                  * value in IPS_CTL bit 31 after enabling IPS through the
5035                  * mailbox." Moreover, the mailbox may return a bogus state,
5036                  * so we need to just enable it and continue on.
5037                  */
5038         } else {
5039                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5040                 /* The bit only becomes 1 in the next vblank, so this wait here
5041                  * is essentially intel_wait_for_vblank. If we don't have this
5042                  * and don't wait for vblanks until the end of crtc_enable, then
5043                  * the HW state readout code will complain that the expected
5044                  * IPS_CTL value is not the one we read. */
5045                 if (intel_wait_for_register(dev_priv,
5046                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5047                                             50))
5048                         DRM_ERROR("Timed out waiting for IPS enable\n");
5049         }
5050 }
5051
5052 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5053 {
5054         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5055         struct drm_device *dev = crtc->base.dev;
5056         struct drm_i915_private *dev_priv = to_i915(dev);
5057
5058         if (!crtc_state->ips_enabled)
5059                 return;
5060
5061         if (IS_BROADWELL(dev_priv)) {
5062                 mutex_lock(&dev_priv->pcu_lock);
5063                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5064                 mutex_unlock(&dev_priv->pcu_lock);
5065                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
5066                 if (intel_wait_for_register(dev_priv,
5067                                             IPS_CTL, IPS_ENABLE, 0,
5068                                             42))
5069                         DRM_ERROR("Timed out waiting for IPS disable\n");
5070         } else {
5071                 I915_WRITE(IPS_CTL, 0);
5072                 POSTING_READ(IPS_CTL);
5073         }
5074
5075         /* We need to wait for a vblank before we can disable the plane. */
5076         intel_wait_for_vblank(dev_priv, crtc->pipe);
5077 }
5078
5079 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5080 {
5081         if (intel_crtc->overlay) {
5082                 struct drm_device *dev = intel_crtc->base.dev;
5083
5084                 mutex_lock(&dev->struct_mutex);
5085                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5086                 mutex_unlock(&dev->struct_mutex);
5087         }
5088
5089         /* Let userspace switch the overlay on again. In most cases userspace
5090          * has to recompute where to put it anyway.
5091          */
5092 }
5093
5094 /**
5095  * intel_post_enable_primary - Perform operations after enabling primary plane
5096  * @crtc: the CRTC whose primary plane was just enabled
5097  * @new_crtc_state: the enabling state
5098  *
5099  * Performs potentially sleeping operations that must be done after the primary
5100  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5101  * called due to an explicit primary plane update, or due to an implicit
5102  * re-enable that is caused when a sprite plane is updated to no longer
5103  * completely hide the primary plane.
5104  */
5105 static void
5106 intel_post_enable_primary(struct drm_crtc *crtc,
5107                           const struct intel_crtc_state *new_crtc_state)
5108 {
5109         struct drm_device *dev = crtc->dev;
5110         struct drm_i915_private *dev_priv = to_i915(dev);
5111         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5112         int pipe = intel_crtc->pipe;
5113
5114         /*
5115          * Gen2 reports pipe underruns whenever all planes are disabled.
5116          * So don't enable underrun reporting before at least some planes
5117          * are enabled.
5118          * FIXME: Need to fix the logic to work when we turn off all planes
5119          * but leave the pipe running.
5120          */
5121         if (IS_GEN2(dev_priv))
5122                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5123
5124         /* Underruns don't always raise interrupts, so check manually. */
5125         intel_check_cpu_fifo_underruns(dev_priv);
5126         intel_check_pch_fifo_underruns(dev_priv);
5127 }
5128
5129 /* FIXME get rid of this and use pre_plane_update */
5130 static void
5131 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5132 {
5133         struct drm_device *dev = crtc->dev;
5134         struct drm_i915_private *dev_priv = to_i915(dev);
5135         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5136         int pipe = intel_crtc->pipe;
5137
5138         /*
5139          * Gen2 reports pipe underruns whenever all planes are disabled.
5140          * So disable underrun reporting before all the planes get disabled.
5141          */
5142         if (IS_GEN2(dev_priv))
5143                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5144
5145         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5146
5147         /*
5148          * Vblank time updates from the shadow to live plane control register
5149          * are blocked if the memory self-refresh mode is active at that
5150          * moment. So to make sure the plane gets truly disabled, disable
5151          * first the self-refresh mode. The self-refresh enable bit in turn
5152          * will be checked/applied by the HW only at the next frame start
5153          * event which is after the vblank start event, so we need to have a
5154          * wait-for-vblank between disabling the plane and the pipe.
5155          */
5156         if (HAS_GMCH_DISPLAY(dev_priv) &&
5157             intel_set_memory_cxsr(dev_priv, false))
5158                 intel_wait_for_vblank(dev_priv, pipe);
5159 }
5160
5161 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5162                                        const struct intel_crtc_state *new_crtc_state)
5163 {
5164         if (!old_crtc_state->ips_enabled)
5165                 return false;
5166
5167         if (needs_modeset(&new_crtc_state->base))
5168                 return true;
5169
5170         return !new_crtc_state->ips_enabled;
5171 }
5172
5173 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5174                                        const struct intel_crtc_state *new_crtc_state)
5175 {
5176         if (!new_crtc_state->ips_enabled)
5177                 return false;
5178
5179         if (needs_modeset(&new_crtc_state->base))
5180                 return true;
5181
5182         /*
5183          * We can't read out IPS on broadwell, assume the worst and
5184          * forcibly enable IPS on the first fastset.
5185          */
5186         if (new_crtc_state->update_pipe &&
5187             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5188                 return true;
5189
5190         return !old_crtc_state->ips_enabled;
5191 }
5192
5193 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5194                           const struct intel_crtc_state *crtc_state)
5195 {
5196         if (!crtc_state->nv12_planes)
5197                 return false;
5198
5199         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
5200                 return false;
5201
5202         if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5203             IS_CANNONLAKE(dev_priv))
5204                 return true;
5205
5206         return false;
5207 }
5208
5209 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5210 {
5211         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5212         struct drm_device *dev = crtc->base.dev;
5213         struct drm_i915_private *dev_priv = to_i915(dev);
5214         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5215         struct intel_crtc_state *pipe_config =
5216                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5217                                                 crtc);
5218         struct drm_plane *primary = crtc->base.primary;
5219         struct drm_plane_state *old_primary_state =
5220                 drm_atomic_get_old_plane_state(old_state, primary);
5221
5222         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5223
5224         if (pipe_config->update_wm_post && pipe_config->base.active)
5225                 intel_update_watermarks(crtc);
5226
5227         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5228                 hsw_enable_ips(pipe_config);
5229
5230         if (old_primary_state) {
5231                 struct drm_plane_state *new_primary_state =
5232                         drm_atomic_get_new_plane_state(old_state, primary);
5233
5234                 intel_fbc_post_update(crtc);
5235
5236                 if (new_primary_state->visible &&
5237                     (needs_modeset(&pipe_config->base) ||
5238                      !old_primary_state->visible))
5239                         intel_post_enable_primary(&crtc->base, pipe_config);
5240         }
5241
5242         /* Display WA 827 */
5243         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5244             !needs_nv12_wa(dev_priv, pipe_config)) {
5245                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5246                 skl_wa_528(dev_priv, crtc->pipe, false);
5247         }
5248 }
5249
5250 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5251                                    struct intel_crtc_state *pipe_config)
5252 {
5253         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5254         struct drm_device *dev = crtc->base.dev;
5255         struct drm_i915_private *dev_priv = to_i915(dev);
5256         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5257         struct drm_plane *primary = crtc->base.primary;
5258         struct drm_plane_state *old_primary_state =
5259                 drm_atomic_get_old_plane_state(old_state, primary);
5260         bool modeset = needs_modeset(&pipe_config->base);
5261         struct intel_atomic_state *old_intel_state =
5262                 to_intel_atomic_state(old_state);
5263
5264         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5265                 hsw_disable_ips(old_crtc_state);
5266
5267         if (old_primary_state) {
5268                 struct intel_plane_state *new_primary_state =
5269                         intel_atomic_get_new_plane_state(old_intel_state,
5270                                                          to_intel_plane(primary));
5271
5272                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5273                 /*
5274                  * Gen2 reports pipe underruns whenever all planes are disabled.
5275                  * So disable underrun reporting before all the planes get disabled.
5276                  */
5277                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5278                     (modeset || !new_primary_state->base.visible))
5279                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5280         }
5281
5282         /* Display WA 827 */
5283         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5284             needs_nv12_wa(dev_priv, pipe_config)) {
5285                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5286                 skl_wa_528(dev_priv, crtc->pipe, true);
5287         }
5288
5289         /*
5290          * Vblank time updates from the shadow to live plane control register
5291          * are blocked if the memory self-refresh mode is active at that
5292          * moment. So to make sure the plane gets truly disabled, disable
5293          * first the self-refresh mode. The self-refresh enable bit in turn
5294          * will be checked/applied by the HW only at the next frame start
5295          * event which is after the vblank start event, so we need to have a
5296          * wait-for-vblank between disabling the plane and the pipe.
5297          */
5298         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5299             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5300                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5301
5302         /*
5303          * IVB workaround: must disable low power watermarks for at least
5304          * one frame before enabling scaling.  LP watermarks can be re-enabled
5305          * when scaling is disabled.
5306          *
5307          * WaCxSRDisabledForSpriteScaling:ivb
5308          */
5309         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5310                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5311
5312         /*
5313          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5314          * watermark programming here.
5315          */
5316         if (needs_modeset(&pipe_config->base))
5317                 return;
5318
5319         /*
5320          * For platforms that support atomic watermarks, program the
5321          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5322          * will be the intermediate values that are safe for both pre- and
5323          * post- vblank; when vblank happens, the 'active' values will be set
5324          * to the final 'target' values and we'll do this again to get the
5325          * optimal watermarks.  For gen9+ platforms, the values we program here
5326          * will be the final target values which will get automatically latched
5327          * at vblank time; no further programming will be necessary.
5328          *
5329          * If a platform hasn't been transitioned to atomic watermarks yet,
5330          * we'll continue to update watermarks the old way, if flags tell
5331          * us to.
5332          */
5333         if (dev_priv->display.initial_watermarks != NULL)
5334                 dev_priv->display.initial_watermarks(old_intel_state,
5335                                                      pipe_config);
5336         else if (pipe_config->update_wm_pre)
5337                 intel_update_watermarks(crtc);
5338 }
5339
5340 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5341 {
5342         struct drm_device *dev = crtc->dev;
5343         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5344         struct drm_plane *p;
5345         int pipe = intel_crtc->pipe;
5346
5347         intel_crtc_dpms_overlay_disable(intel_crtc);
5348
5349         drm_for_each_plane_mask(p, dev, plane_mask)
5350                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5351
5352         /*
5353          * FIXME: Once we grow proper nuclear flip support out of this we need
5354          * to compute the mask of flip planes precisely. For the time being
5355          * consider this a flip to a NULL plane.
5356          */
5357         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5358 }
5359
5360 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5361                                           struct intel_crtc_state *crtc_state,
5362                                           struct drm_atomic_state *old_state)
5363 {
5364         struct drm_connector_state *conn_state;
5365         struct drm_connector *conn;
5366         int i;
5367
5368         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5369                 struct intel_encoder *encoder =
5370                         to_intel_encoder(conn_state->best_encoder);
5371
5372                 if (conn_state->crtc != crtc)
5373                         continue;
5374
5375                 if (encoder->pre_pll_enable)
5376                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5377         }
5378 }
5379
5380 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5381                                       struct intel_crtc_state *crtc_state,
5382                                       struct drm_atomic_state *old_state)
5383 {
5384         struct drm_connector_state *conn_state;
5385         struct drm_connector *conn;
5386         int i;
5387
5388         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5389                 struct intel_encoder *encoder =
5390                         to_intel_encoder(conn_state->best_encoder);
5391
5392                 if (conn_state->crtc != crtc)
5393                         continue;
5394
5395                 if (encoder->pre_enable)
5396                         encoder->pre_enable(encoder, crtc_state, conn_state);
5397         }
5398 }
5399
5400 static void intel_encoders_enable(struct drm_crtc *crtc,
5401                                   struct intel_crtc_state *crtc_state,
5402                                   struct drm_atomic_state *old_state)
5403 {
5404         struct drm_connector_state *conn_state;
5405         struct drm_connector *conn;
5406         int i;
5407
5408         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5409                 struct intel_encoder *encoder =
5410                         to_intel_encoder(conn_state->best_encoder);
5411
5412                 if (conn_state->crtc != crtc)
5413                         continue;
5414
5415                 encoder->enable(encoder, crtc_state, conn_state);
5416                 intel_opregion_notify_encoder(encoder, true);
5417         }
5418 }
5419
5420 static void intel_encoders_disable(struct drm_crtc *crtc,
5421                                    struct intel_crtc_state *old_crtc_state,
5422                                    struct drm_atomic_state *old_state)
5423 {
5424         struct drm_connector_state *old_conn_state;
5425         struct drm_connector *conn;
5426         int i;
5427
5428         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5429                 struct intel_encoder *encoder =
5430                         to_intel_encoder(old_conn_state->best_encoder);
5431
5432                 if (old_conn_state->crtc != crtc)
5433                         continue;
5434
5435                 intel_opregion_notify_encoder(encoder, false);
5436                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5437         }
5438 }
5439
5440 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5441                                         struct intel_crtc_state *old_crtc_state,
5442                                         struct drm_atomic_state *old_state)
5443 {
5444         struct drm_connector_state *old_conn_state;
5445         struct drm_connector *conn;
5446         int i;
5447
5448         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5449                 struct intel_encoder *encoder =
5450                         to_intel_encoder(old_conn_state->best_encoder);
5451
5452                 if (old_conn_state->crtc != crtc)
5453                         continue;
5454
5455                 if (encoder->post_disable)
5456                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5457         }
5458 }
5459
5460 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5461                                             struct intel_crtc_state *old_crtc_state,
5462                                             struct drm_atomic_state *old_state)
5463 {
5464         struct drm_connector_state *old_conn_state;
5465         struct drm_connector *conn;
5466         int i;
5467
5468         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5469                 struct intel_encoder *encoder =
5470                         to_intel_encoder(old_conn_state->best_encoder);
5471
5472                 if (old_conn_state->crtc != crtc)
5473                         continue;
5474
5475                 if (encoder->post_pll_disable)
5476                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5477         }
5478 }
5479
5480 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5481                                  struct drm_atomic_state *old_state)
5482 {
5483         struct drm_crtc *crtc = pipe_config->base.crtc;
5484         struct drm_device *dev = crtc->dev;
5485         struct drm_i915_private *dev_priv = to_i915(dev);
5486         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5487         int pipe = intel_crtc->pipe;
5488         struct intel_atomic_state *old_intel_state =
5489                 to_intel_atomic_state(old_state);
5490
5491         if (WARN_ON(intel_crtc->active))
5492                 return;
5493
5494         /*
5495          * Sometimes spurious CPU pipe underruns happen during FDI
5496          * training, at least with VGA+HDMI cloning. Suppress them.
5497          *
5498          * On ILK we get an occasional spurious CPU pipe underruns
5499          * between eDP port A enable and vdd enable. Also PCH port
5500          * enable seems to result in the occasional CPU pipe underrun.
5501          *
5502          * Spurious PCH underruns also occur during PCH enabling.
5503          */
5504         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5505                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5506         if (intel_crtc->config->has_pch_encoder)
5507                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5508
5509         if (intel_crtc->config->has_pch_encoder)
5510                 intel_prepare_shared_dpll(intel_crtc);
5511
5512         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5513                 intel_dp_set_m_n(intel_crtc, M1_N1);
5514
5515         intel_set_pipe_timings(intel_crtc);
5516         intel_set_pipe_src_size(intel_crtc);
5517
5518         if (intel_crtc->config->has_pch_encoder) {
5519                 intel_cpu_transcoder_set_m_n(intel_crtc,
5520                                      &intel_crtc->config->fdi_m_n, NULL);
5521         }
5522
5523         ironlake_set_pipeconf(crtc);
5524
5525         intel_crtc->active = true;
5526
5527         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5528
5529         if (intel_crtc->config->has_pch_encoder) {
5530                 /* Note: FDI PLL enabling _must_ be done before we enable the
5531                  * cpu pipes, hence this is separate from all the other fdi/pch
5532                  * enabling. */
5533                 ironlake_fdi_pll_enable(intel_crtc);
5534         } else {
5535                 assert_fdi_tx_disabled(dev_priv, pipe);
5536                 assert_fdi_rx_disabled(dev_priv, pipe);
5537         }
5538
5539         ironlake_pfit_enable(intel_crtc);
5540
5541         /*
5542          * On ILK+ LUT must be loaded before the pipe is running but with
5543          * clocks enabled
5544          */
5545         intel_color_load_luts(&pipe_config->base);
5546
5547         if (dev_priv->display.initial_watermarks != NULL)
5548                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5549         intel_enable_pipe(pipe_config);
5550
5551         if (intel_crtc->config->has_pch_encoder)
5552                 ironlake_pch_enable(pipe_config);
5553
5554         assert_vblank_disabled(crtc);
5555         drm_crtc_vblank_on(crtc);
5556
5557         intel_encoders_enable(crtc, pipe_config, old_state);
5558
5559         if (HAS_PCH_CPT(dev_priv))
5560                 cpt_verify_modeset(dev, intel_crtc->pipe);
5561
5562         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5563         if (intel_crtc->config->has_pch_encoder)
5564                 intel_wait_for_vblank(dev_priv, pipe);
5565         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5566         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5567 }
5568
5569 /* IPS only exists on ULT machines and is tied to pipe A. */
5570 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5571 {
5572         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5573 }
5574
5575 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5576                                             enum pipe pipe, bool apply)
5577 {
5578         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5579         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5580
5581         if (apply)
5582                 val |= mask;
5583         else
5584                 val &= ~mask;
5585
5586         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5587 }
5588
5589 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5590 {
5591         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5592         enum pipe pipe = crtc->pipe;
5593         uint32_t val;
5594
5595         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5596
5597         /* Program B credit equally to all pipes */
5598         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5599
5600         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5601 }
5602
5603 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5604                                 struct drm_atomic_state *old_state)
5605 {
5606         struct drm_crtc *crtc = pipe_config->base.crtc;
5607         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5608         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5609         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5610         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5611         struct intel_atomic_state *old_intel_state =
5612                 to_intel_atomic_state(old_state);
5613         bool psl_clkgate_wa;
5614
5615         if (WARN_ON(intel_crtc->active))
5616                 return;
5617
5618         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5619
5620         if (intel_crtc->config->shared_dpll)
5621                 intel_enable_shared_dpll(intel_crtc);
5622
5623         if (INTEL_GEN(dev_priv) >= 11)
5624                 icl_map_plls_to_ports(crtc, pipe_config, old_state);
5625
5626         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5627                 intel_dp_set_m_n(intel_crtc, M1_N1);
5628
5629         if (!transcoder_is_dsi(cpu_transcoder))
5630                 intel_set_pipe_timings(intel_crtc);
5631
5632         intel_set_pipe_src_size(intel_crtc);
5633
5634         if (cpu_transcoder != TRANSCODER_EDP &&
5635             !transcoder_is_dsi(cpu_transcoder)) {
5636                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5637                            intel_crtc->config->pixel_multiplier - 1);
5638         }
5639
5640         if (intel_crtc->config->has_pch_encoder) {
5641                 intel_cpu_transcoder_set_m_n(intel_crtc,
5642                                      &intel_crtc->config->fdi_m_n, NULL);
5643         }
5644
5645         if (!transcoder_is_dsi(cpu_transcoder))
5646                 haswell_set_pipeconf(crtc);
5647
5648         haswell_set_pipemisc(crtc);
5649
5650         intel_color_set_csc(&pipe_config->base);
5651
5652         intel_crtc->active = true;
5653
5654         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5655
5656         if (!transcoder_is_dsi(cpu_transcoder))
5657                 intel_ddi_enable_pipe_clock(pipe_config);
5658
5659         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5660         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5661                          intel_crtc->config->pch_pfit.enabled;
5662         if (psl_clkgate_wa)
5663                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5664
5665         if (INTEL_GEN(dev_priv) >= 9)
5666                 skylake_pfit_enable(intel_crtc);
5667         else
5668                 ironlake_pfit_enable(intel_crtc);
5669
5670         /*
5671          * On ILK+ LUT must be loaded before the pipe is running but with
5672          * clocks enabled
5673          */
5674         intel_color_load_luts(&pipe_config->base);
5675
5676         intel_ddi_set_pipe_settings(pipe_config);
5677         if (!transcoder_is_dsi(cpu_transcoder))
5678                 intel_ddi_enable_transcoder_func(pipe_config);
5679
5680         if (dev_priv->display.initial_watermarks != NULL)
5681                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5682
5683         if (INTEL_GEN(dev_priv) >= 11)
5684                 icl_pipe_mbus_enable(intel_crtc);
5685
5686         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5687         if (!transcoder_is_dsi(cpu_transcoder))
5688                 intel_enable_pipe(pipe_config);
5689
5690         if (intel_crtc->config->has_pch_encoder)
5691                 lpt_pch_enable(pipe_config);
5692
5693         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5694                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5695
5696         assert_vblank_disabled(crtc);
5697         drm_crtc_vblank_on(crtc);
5698
5699         intel_encoders_enable(crtc, pipe_config, old_state);
5700
5701         if (psl_clkgate_wa) {
5702                 intel_wait_for_vblank(dev_priv, pipe);
5703                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5704         }
5705
5706         /* If we change the relative order between pipe/planes enabling, we need
5707          * to change the workaround. */
5708         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5709         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5710                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5711                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5712         }
5713 }
5714
5715 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5716 {
5717         struct drm_device *dev = crtc->base.dev;
5718         struct drm_i915_private *dev_priv = to_i915(dev);
5719         int pipe = crtc->pipe;
5720
5721         /* To avoid upsetting the power well on haswell only disable the pfit if
5722          * it's in use. The hw state code will make sure we get this right. */
5723         if (force || crtc->config->pch_pfit.enabled) {
5724                 I915_WRITE(PF_CTL(pipe), 0);
5725                 I915_WRITE(PF_WIN_POS(pipe), 0);
5726                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5727         }
5728 }
5729
5730 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5731                                   struct drm_atomic_state *old_state)
5732 {
5733         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5734         struct drm_device *dev = crtc->dev;
5735         struct drm_i915_private *dev_priv = to_i915(dev);
5736         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5737         int pipe = intel_crtc->pipe;
5738
5739         /*
5740          * Sometimes spurious CPU pipe underruns happen when the
5741          * pipe is already disabled, but FDI RX/TX is still enabled.
5742          * Happens at least with VGA+HDMI cloning. Suppress them.
5743          */
5744         if (intel_crtc->config->has_pch_encoder) {
5745                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5746                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5747         }
5748
5749         intel_encoders_disable(crtc, old_crtc_state, old_state);
5750
5751         drm_crtc_vblank_off(crtc);
5752         assert_vblank_disabled(crtc);
5753
5754         intel_disable_pipe(old_crtc_state);
5755
5756         ironlake_pfit_disable(intel_crtc, false);
5757
5758         if (intel_crtc->config->has_pch_encoder)
5759                 ironlake_fdi_disable(crtc);
5760
5761         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5762
5763         if (intel_crtc->config->has_pch_encoder) {
5764                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5765
5766                 if (HAS_PCH_CPT(dev_priv)) {
5767                         i915_reg_t reg;
5768                         u32 temp;
5769
5770                         /* disable TRANS_DP_CTL */
5771                         reg = TRANS_DP_CTL(pipe);
5772                         temp = I915_READ(reg);
5773                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5774                                   TRANS_DP_PORT_SEL_MASK);
5775                         temp |= TRANS_DP_PORT_SEL_NONE;
5776                         I915_WRITE(reg, temp);
5777
5778                         /* disable DPLL_SEL */
5779                         temp = I915_READ(PCH_DPLL_SEL);
5780                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5781                         I915_WRITE(PCH_DPLL_SEL, temp);
5782                 }
5783
5784                 ironlake_fdi_pll_disable(intel_crtc);
5785         }
5786
5787         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5788         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5789 }
5790
5791 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5792                                  struct drm_atomic_state *old_state)
5793 {
5794         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5795         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5796         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5797         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5798
5799         intel_encoders_disable(crtc, old_crtc_state, old_state);
5800
5801         drm_crtc_vblank_off(crtc);
5802         assert_vblank_disabled(crtc);
5803
5804         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5805         if (!transcoder_is_dsi(cpu_transcoder))
5806                 intel_disable_pipe(old_crtc_state);
5807
5808         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5809                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5810
5811         if (!transcoder_is_dsi(cpu_transcoder))
5812                 intel_ddi_disable_transcoder_func(old_crtc_state);
5813
5814         if (INTEL_GEN(dev_priv) >= 9)
5815                 skylake_scaler_disable(intel_crtc);
5816         else
5817                 ironlake_pfit_disable(intel_crtc, false);
5818
5819         if (!transcoder_is_dsi(cpu_transcoder))
5820                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5821
5822         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5823
5824         if (INTEL_GEN(dev_priv) >= 11)
5825                 icl_unmap_plls_to_ports(crtc, old_crtc_state, old_state);
5826 }
5827
5828 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5829 {
5830         struct drm_device *dev = crtc->base.dev;
5831         struct drm_i915_private *dev_priv = to_i915(dev);
5832         struct intel_crtc_state *pipe_config = crtc->config;
5833
5834         if (!pipe_config->gmch_pfit.control)
5835                 return;
5836
5837         /*
5838          * The panel fitter should only be adjusted whilst the pipe is disabled,
5839          * according to register description and PRM.
5840          */
5841         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5842         assert_pipe_disabled(dev_priv, crtc->pipe);
5843
5844         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5845         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5846
5847         /* Border color in case we don't scale up to the full screen. Black by
5848          * default, change to something else for debugging. */
5849         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5850 }
5851
5852 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5853 {
5854         switch (port) {
5855         case PORT_A:
5856                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5857         case PORT_B:
5858                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5859         case PORT_C:
5860                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5861         case PORT_D:
5862                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5863         case PORT_E:
5864                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5865         case PORT_F:
5866                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5867         default:
5868                 MISSING_CASE(port);
5869                 return POWER_DOMAIN_PORT_OTHER;
5870         }
5871 }
5872
5873 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5874                                   struct intel_crtc_state *crtc_state)
5875 {
5876         struct drm_device *dev = crtc->dev;
5877         struct drm_i915_private *dev_priv = to_i915(dev);
5878         struct drm_encoder *encoder;
5879         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5880         enum pipe pipe = intel_crtc->pipe;
5881         u64 mask;
5882         enum transcoder transcoder = crtc_state->cpu_transcoder;
5883
5884         if (!crtc_state->base.active)
5885                 return 0;
5886
5887         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5888         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5889         if (crtc_state->pch_pfit.enabled ||
5890             crtc_state->pch_pfit.force_thru)
5891                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5892
5893         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5894                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5895
5896                 mask |= BIT_ULL(intel_encoder->power_domain);
5897         }
5898
5899         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5900                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5901
5902         if (crtc_state->shared_dpll)
5903                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5904
5905         return mask;
5906 }
5907
5908 static u64
5909 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5910                                struct intel_crtc_state *crtc_state)
5911 {
5912         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5913         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5914         enum intel_display_power_domain domain;
5915         u64 domains, new_domains, old_domains;
5916
5917         old_domains = intel_crtc->enabled_power_domains;
5918         intel_crtc->enabled_power_domains = new_domains =
5919                 get_crtc_power_domains(crtc, crtc_state);
5920
5921         domains = new_domains & ~old_domains;
5922
5923         for_each_power_domain(domain, domains)
5924                 intel_display_power_get(dev_priv, domain);
5925
5926         return old_domains & ~new_domains;
5927 }
5928
5929 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5930                                       u64 domains)
5931 {
5932         enum intel_display_power_domain domain;
5933
5934         for_each_power_domain(domain, domains)
5935                 intel_display_power_put(dev_priv, domain);
5936 }
5937
5938 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5939                                    struct drm_atomic_state *old_state)
5940 {
5941         struct intel_atomic_state *old_intel_state =
5942                 to_intel_atomic_state(old_state);
5943         struct drm_crtc *crtc = pipe_config->base.crtc;
5944         struct drm_device *dev = crtc->dev;
5945         struct drm_i915_private *dev_priv = to_i915(dev);
5946         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5947         int pipe = intel_crtc->pipe;
5948
5949         if (WARN_ON(intel_crtc->active))
5950                 return;
5951
5952         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5953                 intel_dp_set_m_n(intel_crtc, M1_N1);
5954
5955         intel_set_pipe_timings(intel_crtc);
5956         intel_set_pipe_src_size(intel_crtc);
5957
5958         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5959                 struct drm_i915_private *dev_priv = to_i915(dev);
5960
5961                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5962                 I915_WRITE(CHV_CANVAS(pipe), 0);
5963         }
5964
5965         i9xx_set_pipeconf(intel_crtc);
5966
5967         intel_crtc->active = true;
5968
5969         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5970
5971         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5972
5973         if (IS_CHERRYVIEW(dev_priv)) {
5974                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5975                 chv_enable_pll(intel_crtc, intel_crtc->config);
5976         } else {
5977                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5978                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5979         }
5980
5981         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5982
5983         i9xx_pfit_enable(intel_crtc);
5984
5985         intel_color_load_luts(&pipe_config->base);
5986
5987         dev_priv->display.initial_watermarks(old_intel_state,
5988                                              pipe_config);
5989         intel_enable_pipe(pipe_config);
5990
5991         assert_vblank_disabled(crtc);
5992         drm_crtc_vblank_on(crtc);
5993
5994         intel_encoders_enable(crtc, pipe_config, old_state);
5995 }
5996
5997 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5998 {
5999         struct drm_device *dev = crtc->base.dev;
6000         struct drm_i915_private *dev_priv = to_i915(dev);
6001
6002         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6003         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6004 }
6005
6006 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6007                              struct drm_atomic_state *old_state)
6008 {
6009         struct intel_atomic_state *old_intel_state =
6010                 to_intel_atomic_state(old_state);
6011         struct drm_crtc *crtc = pipe_config->base.crtc;
6012         struct drm_device *dev = crtc->dev;
6013         struct drm_i915_private *dev_priv = to_i915(dev);
6014         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6015         enum pipe pipe = intel_crtc->pipe;
6016
6017         if (WARN_ON(intel_crtc->active))
6018                 return;
6019
6020         i9xx_set_pll_dividers(intel_crtc);
6021
6022         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6023                 intel_dp_set_m_n(intel_crtc, M1_N1);
6024
6025         intel_set_pipe_timings(intel_crtc);
6026         intel_set_pipe_src_size(intel_crtc);
6027
6028         i9xx_set_pipeconf(intel_crtc);
6029
6030         intel_crtc->active = true;
6031
6032         if (!IS_GEN2(dev_priv))
6033                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6034
6035         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6036
6037         i9xx_enable_pll(intel_crtc, pipe_config);
6038
6039         i9xx_pfit_enable(intel_crtc);
6040
6041         intel_color_load_luts(&pipe_config->base);
6042
6043         if (dev_priv->display.initial_watermarks != NULL)
6044                 dev_priv->display.initial_watermarks(old_intel_state,
6045                                                      intel_crtc->config);
6046         else
6047                 intel_update_watermarks(intel_crtc);
6048         intel_enable_pipe(pipe_config);
6049
6050         assert_vblank_disabled(crtc);
6051         drm_crtc_vblank_on(crtc);
6052
6053         intel_encoders_enable(crtc, pipe_config, old_state);
6054 }
6055
6056 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6057 {
6058         struct drm_device *dev = crtc->base.dev;
6059         struct drm_i915_private *dev_priv = to_i915(dev);
6060
6061         if (!crtc->config->gmch_pfit.control)
6062                 return;
6063
6064         assert_pipe_disabled(dev_priv, crtc->pipe);
6065
6066         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6067                          I915_READ(PFIT_CONTROL));
6068         I915_WRITE(PFIT_CONTROL, 0);
6069 }
6070
6071 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6072                               struct drm_atomic_state *old_state)
6073 {
6074         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6075         struct drm_device *dev = crtc->dev;
6076         struct drm_i915_private *dev_priv = to_i915(dev);
6077         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6078         int pipe = intel_crtc->pipe;
6079
6080         /*
6081          * On gen2 planes are double buffered but the pipe isn't, so we must
6082          * wait for planes to fully turn off before disabling the pipe.
6083          */
6084         if (IS_GEN2(dev_priv))
6085                 intel_wait_for_vblank(dev_priv, pipe);
6086
6087         intel_encoders_disable(crtc, old_crtc_state, old_state);
6088
6089         drm_crtc_vblank_off(crtc);
6090         assert_vblank_disabled(crtc);
6091
6092         intel_disable_pipe(old_crtc_state);
6093
6094         i9xx_pfit_disable(intel_crtc);
6095
6096         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6097
6098         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6099                 if (IS_CHERRYVIEW(dev_priv))
6100                         chv_disable_pll(dev_priv, pipe);
6101                 else if (IS_VALLEYVIEW(dev_priv))
6102                         vlv_disable_pll(dev_priv, pipe);
6103                 else
6104                         i9xx_disable_pll(intel_crtc);
6105         }
6106
6107         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6108
6109         if (!IS_GEN2(dev_priv))
6110                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6111
6112         if (!dev_priv->display.initial_watermarks)
6113                 intel_update_watermarks(intel_crtc);
6114
6115         /* clock the pipe down to 640x480@60 to potentially save power */
6116         if (IS_I830(dev_priv))
6117                 i830_enable_pipe(dev_priv, pipe);
6118 }
6119
6120 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6121                                         struct drm_modeset_acquire_ctx *ctx)
6122 {
6123         struct intel_encoder *encoder;
6124         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6125         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6126         enum intel_display_power_domain domain;
6127         struct intel_plane *plane;
6128         u64 domains;
6129         struct drm_atomic_state *state;
6130         struct intel_crtc_state *crtc_state;
6131         int ret;
6132
6133         if (!intel_crtc->active)
6134                 return;
6135
6136         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6137                 const struct intel_plane_state *plane_state =
6138                         to_intel_plane_state(plane->base.state);
6139
6140                 if (plane_state->base.visible)
6141                         intel_plane_disable_noatomic(intel_crtc, plane);
6142         }
6143
6144         state = drm_atomic_state_alloc(crtc->dev);
6145         if (!state) {
6146                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6147                               crtc->base.id, crtc->name);
6148                 return;
6149         }
6150
6151         state->acquire_ctx = ctx;
6152
6153         /* Everything's already locked, -EDEADLK can't happen. */
6154         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6155         ret = drm_atomic_add_affected_connectors(state, crtc);
6156
6157         WARN_ON(IS_ERR(crtc_state) || ret);
6158
6159         dev_priv->display.crtc_disable(crtc_state, state);
6160
6161         drm_atomic_state_put(state);
6162
6163         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6164                       crtc->base.id, crtc->name);
6165
6166         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6167         crtc->state->active = false;
6168         intel_crtc->active = false;
6169         crtc->enabled = false;
6170         crtc->state->connector_mask = 0;
6171         crtc->state->encoder_mask = 0;
6172
6173         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6174                 encoder->base.crtc = NULL;
6175
6176         intel_fbc_disable(intel_crtc);
6177         intel_update_watermarks(intel_crtc);
6178         intel_disable_shared_dpll(intel_crtc);
6179
6180         domains = intel_crtc->enabled_power_domains;
6181         for_each_power_domain(domain, domains)
6182                 intel_display_power_put(dev_priv, domain);
6183         intel_crtc->enabled_power_domains = 0;
6184
6185         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6186         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6187         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6188 }
6189
6190 /*
6191  * turn all crtc's off, but do not adjust state
6192  * This has to be paired with a call to intel_modeset_setup_hw_state.
6193  */
6194 int intel_display_suspend(struct drm_device *dev)
6195 {
6196         struct drm_i915_private *dev_priv = to_i915(dev);
6197         struct drm_atomic_state *state;
6198         int ret;
6199
6200         state = drm_atomic_helper_suspend(dev);
6201         ret = PTR_ERR_OR_ZERO(state);
6202         if (ret)
6203                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6204         else
6205                 dev_priv->modeset_restore_state = state;
6206         return ret;
6207 }
6208
6209 void intel_encoder_destroy(struct drm_encoder *encoder)
6210 {
6211         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6212
6213         drm_encoder_cleanup(encoder);
6214         kfree(intel_encoder);
6215 }
6216
6217 /* Cross check the actual hw state with our own modeset state tracking (and it's
6218  * internal consistency). */
6219 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6220                                          struct drm_connector_state *conn_state)
6221 {
6222         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6223
6224         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6225                       connector->base.base.id,
6226                       connector->base.name);
6227
6228         if (connector->get_hw_state(connector)) {
6229                 struct intel_encoder *encoder = connector->encoder;
6230
6231                 I915_STATE_WARN(!crtc_state,
6232                          "connector enabled without attached crtc\n");
6233
6234                 if (!crtc_state)
6235                         return;
6236
6237                 I915_STATE_WARN(!crtc_state->active,
6238                       "connector is active, but attached crtc isn't\n");
6239
6240                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6241                         return;
6242
6243                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6244                         "atomic encoder doesn't match attached encoder\n");
6245
6246                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6247                         "attached encoder crtc differs from connector crtc\n");
6248         } else {
6249                 I915_STATE_WARN(crtc_state && crtc_state->active,
6250                         "attached crtc is active, but connector isn't\n");
6251                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6252                         "best encoder set without crtc!\n");
6253         }
6254 }
6255
6256 int intel_connector_init(struct intel_connector *connector)
6257 {
6258         struct intel_digital_connector_state *conn_state;
6259
6260         /*
6261          * Allocate enough memory to hold intel_digital_connector_state,
6262          * This might be a few bytes too many, but for connectors that don't
6263          * need it we'll free the state and allocate a smaller one on the first
6264          * succesful commit anyway.
6265          */
6266         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6267         if (!conn_state)
6268                 return -ENOMEM;
6269
6270         __drm_atomic_helper_connector_reset(&connector->base,
6271                                             &conn_state->base);
6272
6273         return 0;
6274 }
6275
6276 struct intel_connector *intel_connector_alloc(void)
6277 {
6278         struct intel_connector *connector;
6279
6280         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6281         if (!connector)
6282                 return NULL;
6283
6284         if (intel_connector_init(connector) < 0) {
6285                 kfree(connector);
6286                 return NULL;
6287         }
6288
6289         return connector;
6290 }
6291
6292 /*
6293  * Free the bits allocated by intel_connector_alloc.
6294  * This should only be used after intel_connector_alloc has returned
6295  * successfully, and before drm_connector_init returns successfully.
6296  * Otherwise the destroy callbacks for the connector and the state should
6297  * take care of proper cleanup/free
6298  */
6299 void intel_connector_free(struct intel_connector *connector)
6300 {
6301         kfree(to_intel_digital_connector_state(connector->base.state));
6302         kfree(connector);
6303 }
6304
6305 /* Simple connector->get_hw_state implementation for encoders that support only
6306  * one connector and no cloning and hence the encoder state determines the state
6307  * of the connector. */
6308 bool intel_connector_get_hw_state(struct intel_connector *connector)
6309 {
6310         enum pipe pipe = 0;
6311         struct intel_encoder *encoder = connector->encoder;
6312
6313         return encoder->get_hw_state(encoder, &pipe);
6314 }
6315
6316 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6317 {
6318         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6319                 return crtc_state->fdi_lanes;
6320
6321         return 0;
6322 }
6323
6324 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6325                                      struct intel_crtc_state *pipe_config)
6326 {
6327         struct drm_i915_private *dev_priv = to_i915(dev);
6328         struct drm_atomic_state *state = pipe_config->base.state;
6329         struct intel_crtc *other_crtc;
6330         struct intel_crtc_state *other_crtc_state;
6331
6332         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6333                       pipe_name(pipe), pipe_config->fdi_lanes);
6334         if (pipe_config->fdi_lanes > 4) {
6335                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6336                               pipe_name(pipe), pipe_config->fdi_lanes);
6337                 return -EINVAL;
6338         }
6339
6340         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6341                 if (pipe_config->fdi_lanes > 2) {
6342                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6343                                       pipe_config->fdi_lanes);
6344                         return -EINVAL;
6345                 } else {
6346                         return 0;
6347                 }
6348         }
6349
6350         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6351                 return 0;
6352
6353         /* Ivybridge 3 pipe is really complicated */
6354         switch (pipe) {
6355         case PIPE_A:
6356                 return 0;
6357         case PIPE_B:
6358                 if (pipe_config->fdi_lanes <= 2)
6359                         return 0;
6360
6361                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6362                 other_crtc_state =
6363                         intel_atomic_get_crtc_state(state, other_crtc);
6364                 if (IS_ERR(other_crtc_state))
6365                         return PTR_ERR(other_crtc_state);
6366
6367                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6368                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6369                                       pipe_name(pipe), pipe_config->fdi_lanes);
6370                         return -EINVAL;
6371                 }
6372                 return 0;
6373         case PIPE_C:
6374                 if (pipe_config->fdi_lanes > 2) {
6375                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6376                                       pipe_name(pipe), pipe_config->fdi_lanes);
6377                         return -EINVAL;
6378                 }
6379
6380                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6381                 other_crtc_state =
6382                         intel_atomic_get_crtc_state(state, other_crtc);
6383                 if (IS_ERR(other_crtc_state))
6384                         return PTR_ERR(other_crtc_state);
6385
6386                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6387                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6388                         return -EINVAL;
6389                 }
6390                 return 0;
6391         default:
6392                 BUG();
6393         }
6394 }
6395
6396 #define RETRY 1
6397 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6398                                        struct intel_crtc_state *pipe_config)
6399 {
6400         struct drm_device *dev = intel_crtc->base.dev;
6401         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6402         int lane, link_bw, fdi_dotclock, ret;
6403         bool needs_recompute = false;
6404
6405 retry:
6406         /* FDI is a binary signal running at ~2.7GHz, encoding
6407          * each output octet as 10 bits. The actual frequency
6408          * is stored as a divider into a 100MHz clock, and the
6409          * mode pixel clock is stored in units of 1KHz.
6410          * Hence the bw of each lane in terms of the mode signal
6411          * is:
6412          */
6413         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6414
6415         fdi_dotclock = adjusted_mode->crtc_clock;
6416
6417         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6418                                            pipe_config->pipe_bpp);
6419
6420         pipe_config->fdi_lanes = lane;
6421
6422         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6423                                link_bw, &pipe_config->fdi_m_n, false);
6424
6425         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6426         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6427                 pipe_config->pipe_bpp -= 2*3;
6428                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6429                               pipe_config->pipe_bpp);
6430                 needs_recompute = true;
6431                 pipe_config->bw_constrained = true;
6432
6433                 goto retry;
6434         }
6435
6436         if (needs_recompute)
6437                 return RETRY;
6438
6439         return ret;
6440 }
6441
6442 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6443 {
6444         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6445         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6446
6447         /* IPS only exists on ULT machines and is tied to pipe A. */
6448         if (!hsw_crtc_supports_ips(crtc))
6449                 return false;
6450
6451         if (!i915_modparams.enable_ips)
6452                 return false;
6453
6454         if (crtc_state->pipe_bpp > 24)
6455                 return false;
6456
6457         /*
6458          * We compare against max which means we must take
6459          * the increased cdclk requirement into account when
6460          * calculating the new cdclk.
6461          *
6462          * Should measure whether using a lower cdclk w/o IPS
6463          */
6464         if (IS_BROADWELL(dev_priv) &&
6465             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6466                 return false;
6467
6468         return true;
6469 }
6470
6471 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6472 {
6473         struct drm_i915_private *dev_priv =
6474                 to_i915(crtc_state->base.crtc->dev);
6475         struct intel_atomic_state *intel_state =
6476                 to_intel_atomic_state(crtc_state->base.state);
6477
6478         if (!hsw_crtc_state_ips_capable(crtc_state))
6479                 return false;
6480
6481         if (crtc_state->ips_force_disable)
6482                 return false;
6483
6484         /* IPS should be fine as long as at least one plane is enabled. */
6485         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6486                 return false;
6487
6488         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6489         if (IS_BROADWELL(dev_priv) &&
6490             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6491                 return false;
6492
6493         return true;
6494 }
6495
6496 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6497 {
6498         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6499
6500         /* GDG double wide on either pipe, otherwise pipe A only */
6501         return INTEL_GEN(dev_priv) < 4 &&
6502                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6503 }
6504
6505 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6506 {
6507         uint32_t pixel_rate;
6508
6509         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6510
6511         /*
6512          * We only use IF-ID interlacing. If we ever use
6513          * PF-ID we'll need to adjust the pixel_rate here.
6514          */
6515
6516         if (pipe_config->pch_pfit.enabled) {
6517                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6518                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6519
6520                 pipe_w = pipe_config->pipe_src_w;
6521                 pipe_h = pipe_config->pipe_src_h;
6522
6523                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6524                 pfit_h = pfit_size & 0xFFFF;
6525                 if (pipe_w < pfit_w)
6526                         pipe_w = pfit_w;
6527                 if (pipe_h < pfit_h)
6528                         pipe_h = pfit_h;
6529
6530                 if (WARN_ON(!pfit_w || !pfit_h))
6531                         return pixel_rate;
6532
6533                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6534                                      pfit_w * pfit_h);
6535         }
6536
6537         return pixel_rate;
6538 }
6539
6540 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6541 {
6542         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6543
6544         if (HAS_GMCH_DISPLAY(dev_priv))
6545                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6546                 crtc_state->pixel_rate =
6547                         crtc_state->base.adjusted_mode.crtc_clock;
6548         else
6549                 crtc_state->pixel_rate =
6550                         ilk_pipe_pixel_rate(crtc_state);
6551 }
6552
6553 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6554                                      struct intel_crtc_state *pipe_config)
6555 {
6556         struct drm_device *dev = crtc->base.dev;
6557         struct drm_i915_private *dev_priv = to_i915(dev);
6558         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6559         int clock_limit = dev_priv->max_dotclk_freq;
6560
6561         if (INTEL_GEN(dev_priv) < 4) {
6562                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6563
6564                 /*
6565                  * Enable double wide mode when the dot clock
6566                  * is > 90% of the (display) core speed.
6567                  */
6568                 if (intel_crtc_supports_double_wide(crtc) &&
6569                     adjusted_mode->crtc_clock > clock_limit) {
6570                         clock_limit = dev_priv->max_dotclk_freq;
6571                         pipe_config->double_wide = true;
6572                 }
6573         }
6574
6575         if (adjusted_mode->crtc_clock > clock_limit) {
6576                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6577                               adjusted_mode->crtc_clock, clock_limit,
6578                               yesno(pipe_config->double_wide));
6579                 return -EINVAL;
6580         }
6581
6582         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6583                 /*
6584                  * There is only one pipe CSC unit per pipe, and we need that
6585                  * for output conversion from RGB->YCBCR. So if CTM is already
6586                  * applied we can't support YCBCR420 output.
6587                  */
6588                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6589                 return -EINVAL;
6590         }
6591
6592         /*
6593          * Pipe horizontal size must be even in:
6594          * - DVO ganged mode
6595          * - LVDS dual channel mode
6596          * - Double wide pipe
6597          */
6598         if (pipe_config->pipe_src_w & 1) {
6599                 if (pipe_config->double_wide) {
6600                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6601                         return -EINVAL;
6602                 }
6603
6604                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6605                     intel_is_dual_link_lvds(dev)) {
6606                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6607                         return -EINVAL;
6608                 }
6609         }
6610
6611         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6612          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6613          */
6614         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6615                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6616                 return -EINVAL;
6617
6618         intel_crtc_compute_pixel_rate(pipe_config);
6619
6620         if (pipe_config->has_pch_encoder)
6621                 return ironlake_fdi_compute_config(crtc, pipe_config);
6622
6623         return 0;
6624 }
6625
6626 static void
6627 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6628 {
6629         while (*num > DATA_LINK_M_N_MASK ||
6630                *den > DATA_LINK_M_N_MASK) {
6631                 *num >>= 1;
6632                 *den >>= 1;
6633         }
6634 }
6635
6636 static void compute_m_n(unsigned int m, unsigned int n,
6637                         uint32_t *ret_m, uint32_t *ret_n,
6638                         bool reduce_m_n)
6639 {
6640         /*
6641          * Reduce M/N as much as possible without loss in precision. Several DP
6642          * dongles in particular seem to be fussy about too large *link* M/N
6643          * values. The passed in values are more likely to have the least
6644          * significant bits zero than M after rounding below, so do this first.
6645          */
6646         if (reduce_m_n) {
6647                 while ((m & 1) == 0 && (n & 1) == 0) {
6648                         m >>= 1;
6649                         n >>= 1;
6650                 }
6651         }
6652
6653         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6654         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6655         intel_reduce_m_n_ratio(ret_m, ret_n);
6656 }
6657
6658 void
6659 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6660                        int pixel_clock, int link_clock,
6661                        struct intel_link_m_n *m_n,
6662                        bool reduce_m_n)
6663 {
6664         m_n->tu = 64;
6665
6666         compute_m_n(bits_per_pixel * pixel_clock,
6667                     link_clock * nlanes * 8,
6668                     &m_n->gmch_m, &m_n->gmch_n,
6669                     reduce_m_n);
6670
6671         compute_m_n(pixel_clock, link_clock,
6672                     &m_n->link_m, &m_n->link_n,
6673                     reduce_m_n);
6674 }
6675
6676 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6677 {
6678         if (i915_modparams.panel_use_ssc >= 0)
6679                 return i915_modparams.panel_use_ssc != 0;
6680         return dev_priv->vbt.lvds_use_ssc
6681                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6682 }
6683
6684 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6685 {
6686         return (1 << dpll->n) << 16 | dpll->m2;
6687 }
6688
6689 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6690 {
6691         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6692 }
6693
6694 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6695                                      struct intel_crtc_state *crtc_state,
6696                                      struct dpll *reduced_clock)
6697 {
6698         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6699         u32 fp, fp2 = 0;
6700
6701         if (IS_PINEVIEW(dev_priv)) {
6702                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6703                 if (reduced_clock)
6704                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6705         } else {
6706                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6707                 if (reduced_clock)
6708                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6709         }
6710
6711         crtc_state->dpll_hw_state.fp0 = fp;
6712
6713         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6714             reduced_clock) {
6715                 crtc_state->dpll_hw_state.fp1 = fp2;
6716         } else {
6717                 crtc_state->dpll_hw_state.fp1 = fp;
6718         }
6719 }
6720
6721 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6722                 pipe)
6723 {
6724         u32 reg_val;
6725
6726         /*
6727          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6728          * and set it to a reasonable value instead.
6729          */
6730         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6731         reg_val &= 0xffffff00;
6732         reg_val |= 0x00000030;
6733         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6734
6735         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6736         reg_val &= 0x00ffffff;
6737         reg_val |= 0x8c000000;
6738         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6739
6740         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6741         reg_val &= 0xffffff00;
6742         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6743
6744         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6745         reg_val &= 0x00ffffff;
6746         reg_val |= 0xb0000000;
6747         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6748 }
6749
6750 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6751                                          struct intel_link_m_n *m_n)
6752 {
6753         struct drm_device *dev = crtc->base.dev;
6754         struct drm_i915_private *dev_priv = to_i915(dev);
6755         int pipe = crtc->pipe;
6756
6757         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6758         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6759         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6760         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6761 }
6762
6763 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6764                                          struct intel_link_m_n *m_n,
6765                                          struct intel_link_m_n *m2_n2)
6766 {
6767         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6768         int pipe = crtc->pipe;
6769         enum transcoder transcoder = crtc->config->cpu_transcoder;
6770
6771         if (INTEL_GEN(dev_priv) >= 5) {
6772                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6773                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6774                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6775                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6776                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6777                  * for gen < 8) and if DRRS is supported (to make sure the
6778                  * registers are not unnecessarily accessed).
6779                  */
6780                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6781                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6782                         I915_WRITE(PIPE_DATA_M2(transcoder),
6783                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6784                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6785                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6786                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6787                 }
6788         } else {
6789                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6790                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6791                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6792                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6793         }
6794 }
6795
6796 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6797 {
6798         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6799
6800         if (m_n == M1_N1) {
6801                 dp_m_n = &crtc->config->dp_m_n;
6802                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6803         } else if (m_n == M2_N2) {
6804
6805                 /*
6806                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6807                  * needs to be programmed into M1_N1.
6808                  */
6809                 dp_m_n = &crtc->config->dp_m2_n2;
6810         } else {
6811                 DRM_ERROR("Unsupported divider value\n");
6812                 return;
6813         }
6814
6815         if (crtc->config->has_pch_encoder)
6816                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6817         else
6818                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6819 }
6820
6821 static void vlv_compute_dpll(struct intel_crtc *crtc,
6822                              struct intel_crtc_state *pipe_config)
6823 {
6824         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6825                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6826         if (crtc->pipe != PIPE_A)
6827                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6828
6829         /* DPLL not used with DSI, but still need the rest set up */
6830         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6831                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6832                         DPLL_EXT_BUFFER_ENABLE_VLV;
6833
6834         pipe_config->dpll_hw_state.dpll_md =
6835                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6836 }
6837
6838 static void chv_compute_dpll(struct intel_crtc *crtc,
6839                              struct intel_crtc_state *pipe_config)
6840 {
6841         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6842                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6843         if (crtc->pipe != PIPE_A)
6844                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6845
6846         /* DPLL not used with DSI, but still need the rest set up */
6847         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6848                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6849
6850         pipe_config->dpll_hw_state.dpll_md =
6851                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6852 }
6853
6854 static void vlv_prepare_pll(struct intel_crtc *crtc,
6855                             const struct intel_crtc_state *pipe_config)
6856 {
6857         struct drm_device *dev = crtc->base.dev;
6858         struct drm_i915_private *dev_priv = to_i915(dev);
6859         enum pipe pipe = crtc->pipe;
6860         u32 mdiv;
6861         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6862         u32 coreclk, reg_val;
6863
6864         /* Enable Refclk */
6865         I915_WRITE(DPLL(pipe),
6866                    pipe_config->dpll_hw_state.dpll &
6867                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6868
6869         /* No need to actually set up the DPLL with DSI */
6870         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6871                 return;
6872
6873         mutex_lock(&dev_priv->sb_lock);
6874
6875         bestn = pipe_config->dpll.n;
6876         bestm1 = pipe_config->dpll.m1;
6877         bestm2 = pipe_config->dpll.m2;
6878         bestp1 = pipe_config->dpll.p1;
6879         bestp2 = pipe_config->dpll.p2;
6880
6881         /* See eDP HDMI DPIO driver vbios notes doc */
6882
6883         /* PLL B needs special handling */
6884         if (pipe == PIPE_B)
6885                 vlv_pllb_recal_opamp(dev_priv, pipe);
6886
6887         /* Set up Tx target for periodic Rcomp update */
6888         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6889
6890         /* Disable target IRef on PLL */
6891         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6892         reg_val &= 0x00ffffff;
6893         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6894
6895         /* Disable fast lock */
6896         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6897
6898         /* Set idtafcrecal before PLL is enabled */
6899         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6900         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6901         mdiv |= ((bestn << DPIO_N_SHIFT));
6902         mdiv |= (1 << DPIO_K_SHIFT);
6903
6904         /*
6905          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6906          * but we don't support that).
6907          * Note: don't use the DAC post divider as it seems unstable.
6908          */
6909         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6910         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6911
6912         mdiv |= DPIO_ENABLE_CALIBRATION;
6913         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6914
6915         /* Set HBR and RBR LPF coefficients */
6916         if (pipe_config->port_clock == 162000 ||
6917             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6918             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6919                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6920                                  0x009f0003);
6921         else
6922                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6923                                  0x00d0000f);
6924
6925         if (intel_crtc_has_dp_encoder(pipe_config)) {
6926                 /* Use SSC source */
6927                 if (pipe == PIPE_A)
6928                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6929                                          0x0df40000);
6930                 else
6931                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6932                                          0x0df70000);
6933         } else { /* HDMI or VGA */
6934                 /* Use bend source */
6935                 if (pipe == PIPE_A)
6936                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6937                                          0x0df70000);
6938                 else
6939                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6940                                          0x0df40000);
6941         }
6942
6943         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6944         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6945         if (intel_crtc_has_dp_encoder(crtc->config))
6946                 coreclk |= 0x01000000;
6947         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6948
6949         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6950         mutex_unlock(&dev_priv->sb_lock);
6951 }
6952
6953 static void chv_prepare_pll(struct intel_crtc *crtc,
6954                             const struct intel_crtc_state *pipe_config)
6955 {
6956         struct drm_device *dev = crtc->base.dev;
6957         struct drm_i915_private *dev_priv = to_i915(dev);
6958         enum pipe pipe = crtc->pipe;
6959         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6960         u32 loopfilter, tribuf_calcntr;
6961         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6962         u32 dpio_val;
6963         int vco;
6964
6965         /* Enable Refclk and SSC */
6966         I915_WRITE(DPLL(pipe),
6967                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6968
6969         /* No need to actually set up the DPLL with DSI */
6970         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6971                 return;
6972
6973         bestn = pipe_config->dpll.n;
6974         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6975         bestm1 = pipe_config->dpll.m1;
6976         bestm2 = pipe_config->dpll.m2 >> 22;
6977         bestp1 = pipe_config->dpll.p1;
6978         bestp2 = pipe_config->dpll.p2;
6979         vco = pipe_config->dpll.vco;
6980         dpio_val = 0;
6981         loopfilter = 0;
6982
6983         mutex_lock(&dev_priv->sb_lock);
6984
6985         /* p1 and p2 divider */
6986         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6987                         5 << DPIO_CHV_S1_DIV_SHIFT |
6988                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6989                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6990                         1 << DPIO_CHV_K_DIV_SHIFT);
6991
6992         /* Feedback post-divider - m2 */
6993         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6994
6995         /* Feedback refclk divider - n and m1 */
6996         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6997                         DPIO_CHV_M1_DIV_BY_2 |
6998                         1 << DPIO_CHV_N_DIV_SHIFT);
6999
7000         /* M2 fraction division */
7001         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7002
7003         /* M2 fraction division enable */
7004         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7005         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7006         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7007         if (bestm2_frac)
7008                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7009         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7010
7011         /* Program digital lock detect threshold */
7012         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7013         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7014                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7015         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7016         if (!bestm2_frac)
7017                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7018         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7019
7020         /* Loop filter */
7021         if (vco == 5400000) {
7022                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7023                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7024                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7025                 tribuf_calcntr = 0x9;
7026         } else if (vco <= 6200000) {
7027                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7028                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7029                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7030                 tribuf_calcntr = 0x9;
7031         } else if (vco <= 6480000) {
7032                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7033                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7034                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7035                 tribuf_calcntr = 0x8;
7036         } else {
7037                 /* Not supported. Apply the same limits as in the max case */
7038                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7039                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7040                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7041                 tribuf_calcntr = 0;
7042         }
7043         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7044
7045         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7046         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7047         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7048         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7049
7050         /* AFC Recal */
7051         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7052                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7053                         DPIO_AFC_RECAL);
7054
7055         mutex_unlock(&dev_priv->sb_lock);
7056 }
7057
7058 /**
7059  * vlv_force_pll_on - forcibly enable just the PLL
7060  * @dev_priv: i915 private structure
7061  * @pipe: pipe PLL to enable
7062  * @dpll: PLL configuration
7063  *
7064  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7065  * in cases where we need the PLL enabled even when @pipe is not going to
7066  * be enabled.
7067  */
7068 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7069                      const struct dpll *dpll)
7070 {
7071         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7072         struct intel_crtc_state *pipe_config;
7073
7074         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7075         if (!pipe_config)
7076                 return -ENOMEM;
7077
7078         pipe_config->base.crtc = &crtc->base;
7079         pipe_config->pixel_multiplier = 1;
7080         pipe_config->dpll = *dpll;
7081
7082         if (IS_CHERRYVIEW(dev_priv)) {
7083                 chv_compute_dpll(crtc, pipe_config);
7084                 chv_prepare_pll(crtc, pipe_config);
7085                 chv_enable_pll(crtc, pipe_config);
7086         } else {
7087                 vlv_compute_dpll(crtc, pipe_config);
7088                 vlv_prepare_pll(crtc, pipe_config);
7089                 vlv_enable_pll(crtc, pipe_config);
7090         }
7091
7092         kfree(pipe_config);
7093
7094         return 0;
7095 }
7096
7097 /**
7098  * vlv_force_pll_off - forcibly disable just the PLL
7099  * @dev_priv: i915 private structure
7100  * @pipe: pipe PLL to disable
7101  *
7102  * Disable the PLL for @pipe. To be used in cases where we need
7103  * the PLL enabled even when @pipe is not going to be enabled.
7104  */
7105 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7106 {
7107         if (IS_CHERRYVIEW(dev_priv))
7108                 chv_disable_pll(dev_priv, pipe);
7109         else
7110                 vlv_disable_pll(dev_priv, pipe);
7111 }
7112
7113 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7114                               struct intel_crtc_state *crtc_state,
7115                               struct dpll *reduced_clock)
7116 {
7117         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7118         u32 dpll;
7119         struct dpll *clock = &crtc_state->dpll;
7120
7121         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7122
7123         dpll = DPLL_VGA_MODE_DIS;
7124
7125         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7126                 dpll |= DPLLB_MODE_LVDS;
7127         else
7128                 dpll |= DPLLB_MODE_DAC_SERIAL;
7129
7130         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7131             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7132                 dpll |= (crtc_state->pixel_multiplier - 1)
7133                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7134         }
7135
7136         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7137             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7138                 dpll |= DPLL_SDVO_HIGH_SPEED;
7139
7140         if (intel_crtc_has_dp_encoder(crtc_state))
7141                 dpll |= DPLL_SDVO_HIGH_SPEED;
7142
7143         /* compute bitmask from p1 value */
7144         if (IS_PINEVIEW(dev_priv))
7145                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7146         else {
7147                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7148                 if (IS_G4X(dev_priv) && reduced_clock)
7149                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7150         }
7151         switch (clock->p2) {
7152         case 5:
7153                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7154                 break;
7155         case 7:
7156                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7157                 break;
7158         case 10:
7159                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7160                 break;
7161         case 14:
7162                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7163                 break;
7164         }
7165         if (INTEL_GEN(dev_priv) >= 4)
7166                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7167
7168         if (crtc_state->sdvo_tv_clock)
7169                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7170         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7171                  intel_panel_use_ssc(dev_priv))
7172                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7173         else
7174                 dpll |= PLL_REF_INPUT_DREFCLK;
7175
7176         dpll |= DPLL_VCO_ENABLE;
7177         crtc_state->dpll_hw_state.dpll = dpll;
7178
7179         if (INTEL_GEN(dev_priv) >= 4) {
7180                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7181                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7182                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7183         }
7184 }
7185
7186 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7187                               struct intel_crtc_state *crtc_state,
7188                               struct dpll *reduced_clock)
7189 {
7190         struct drm_device *dev = crtc->base.dev;
7191         struct drm_i915_private *dev_priv = to_i915(dev);
7192         u32 dpll;
7193         struct dpll *clock = &crtc_state->dpll;
7194
7195         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7196
7197         dpll = DPLL_VGA_MODE_DIS;
7198
7199         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7200                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7201         } else {
7202                 if (clock->p1 == 2)
7203                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7204                 else
7205                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7206                 if (clock->p2 == 4)
7207                         dpll |= PLL_P2_DIVIDE_BY_4;
7208         }
7209
7210         if (!IS_I830(dev_priv) &&
7211             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7212                 dpll |= DPLL_DVO_2X_MODE;
7213
7214         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7215             intel_panel_use_ssc(dev_priv))
7216                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7217         else
7218                 dpll |= PLL_REF_INPUT_DREFCLK;
7219
7220         dpll |= DPLL_VCO_ENABLE;
7221         crtc_state->dpll_hw_state.dpll = dpll;
7222 }
7223
7224 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7225 {
7226         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7227         enum pipe pipe = intel_crtc->pipe;
7228         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7229         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7230         uint32_t crtc_vtotal, crtc_vblank_end;
7231         int vsyncshift = 0;
7232
7233         /* We need to be careful not to changed the adjusted mode, for otherwise
7234          * the hw state checker will get angry at the mismatch. */
7235         crtc_vtotal = adjusted_mode->crtc_vtotal;
7236         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7237
7238         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7239                 /* the chip adds 2 halflines automatically */
7240                 crtc_vtotal -= 1;
7241                 crtc_vblank_end -= 1;
7242
7243                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7244                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7245                 else
7246                         vsyncshift = adjusted_mode->crtc_hsync_start -
7247                                 adjusted_mode->crtc_htotal / 2;
7248                 if (vsyncshift < 0)
7249                         vsyncshift += adjusted_mode->crtc_htotal;
7250         }
7251
7252         if (INTEL_GEN(dev_priv) > 3)
7253                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7254
7255         I915_WRITE(HTOTAL(cpu_transcoder),
7256                    (adjusted_mode->crtc_hdisplay - 1) |
7257                    ((adjusted_mode->crtc_htotal - 1) << 16));
7258         I915_WRITE(HBLANK(cpu_transcoder),
7259                    (adjusted_mode->crtc_hblank_start - 1) |
7260                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7261         I915_WRITE(HSYNC(cpu_transcoder),
7262                    (adjusted_mode->crtc_hsync_start - 1) |
7263                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7264
7265         I915_WRITE(VTOTAL(cpu_transcoder),
7266                    (adjusted_mode->crtc_vdisplay - 1) |
7267                    ((crtc_vtotal - 1) << 16));
7268         I915_WRITE(VBLANK(cpu_transcoder),
7269                    (adjusted_mode->crtc_vblank_start - 1) |
7270                    ((crtc_vblank_end - 1) << 16));
7271         I915_WRITE(VSYNC(cpu_transcoder),
7272                    (adjusted_mode->crtc_vsync_start - 1) |
7273                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7274
7275         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7276          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7277          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7278          * bits. */
7279         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7280             (pipe == PIPE_B || pipe == PIPE_C))
7281                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7282
7283 }
7284
7285 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7286 {
7287         struct drm_device *dev = intel_crtc->base.dev;
7288         struct drm_i915_private *dev_priv = to_i915(dev);
7289         enum pipe pipe = intel_crtc->pipe;
7290
7291         /* pipesrc controls the size that is scaled from, which should
7292          * always be the user's requested size.
7293          */
7294         I915_WRITE(PIPESRC(pipe),
7295                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7296                    (intel_crtc->config->pipe_src_h - 1));
7297 }
7298
7299 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7300                                    struct intel_crtc_state *pipe_config)
7301 {
7302         struct drm_device *dev = crtc->base.dev;
7303         struct drm_i915_private *dev_priv = to_i915(dev);
7304         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7305         uint32_t tmp;
7306
7307         tmp = I915_READ(HTOTAL(cpu_transcoder));
7308         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7309         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7310         tmp = I915_READ(HBLANK(cpu_transcoder));
7311         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7312         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7313         tmp = I915_READ(HSYNC(cpu_transcoder));
7314         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7315         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7316
7317         tmp = I915_READ(VTOTAL(cpu_transcoder));
7318         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7319         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7320         tmp = I915_READ(VBLANK(cpu_transcoder));
7321         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7322         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7323         tmp = I915_READ(VSYNC(cpu_transcoder));
7324         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7325         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7326
7327         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7328                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7329                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7330                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7331         }
7332 }
7333
7334 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7335                                     struct intel_crtc_state *pipe_config)
7336 {
7337         struct drm_device *dev = crtc->base.dev;
7338         struct drm_i915_private *dev_priv = to_i915(dev);
7339         u32 tmp;
7340
7341         tmp = I915_READ(PIPESRC(crtc->pipe));
7342         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7343         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7344
7345         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7346         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7347 }
7348
7349 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7350                                  struct intel_crtc_state *pipe_config)
7351 {
7352         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7353         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7354         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7355         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7356
7357         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7358         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7359         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7360         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7361
7362         mode->flags = pipe_config->base.adjusted_mode.flags;
7363         mode->type = DRM_MODE_TYPE_DRIVER;
7364
7365         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7366
7367         mode->hsync = drm_mode_hsync(mode);
7368         mode->vrefresh = drm_mode_vrefresh(mode);
7369         drm_mode_set_name(mode);
7370 }
7371
7372 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7373 {
7374         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7375         uint32_t pipeconf;
7376
7377         pipeconf = 0;
7378
7379         /* we keep both pipes enabled on 830 */
7380         if (IS_I830(dev_priv))
7381                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7382
7383         if (intel_crtc->config->double_wide)
7384                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7385
7386         /* only g4x and later have fancy bpc/dither controls */
7387         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7388             IS_CHERRYVIEW(dev_priv)) {
7389                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7390                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7391                         pipeconf |= PIPECONF_DITHER_EN |
7392                                     PIPECONF_DITHER_TYPE_SP;
7393
7394                 switch (intel_crtc->config->pipe_bpp) {
7395                 case 18:
7396                         pipeconf |= PIPECONF_6BPC;
7397                         break;
7398                 case 24:
7399                         pipeconf |= PIPECONF_8BPC;
7400                         break;
7401                 case 30:
7402                         pipeconf |= PIPECONF_10BPC;
7403                         break;
7404                 default:
7405                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7406                         BUG();
7407                 }
7408         }
7409
7410         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7411                 if (INTEL_GEN(dev_priv) < 4 ||
7412                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7413                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7414                 else
7415                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7416         } else
7417                 pipeconf |= PIPECONF_PROGRESSIVE;
7418
7419         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7420              intel_crtc->config->limited_color_range)
7421                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7422
7423         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7424         POSTING_READ(PIPECONF(intel_crtc->pipe));
7425 }
7426
7427 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7428                                    struct intel_crtc_state *crtc_state)
7429 {
7430         struct drm_device *dev = crtc->base.dev;
7431         struct drm_i915_private *dev_priv = to_i915(dev);
7432         const struct intel_limit *limit;
7433         int refclk = 48000;
7434
7435         memset(&crtc_state->dpll_hw_state, 0,
7436                sizeof(crtc_state->dpll_hw_state));
7437
7438         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7439                 if (intel_panel_use_ssc(dev_priv)) {
7440                         refclk = dev_priv->vbt.lvds_ssc_freq;
7441                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7442                 }
7443
7444                 limit = &intel_limits_i8xx_lvds;
7445         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7446                 limit = &intel_limits_i8xx_dvo;
7447         } else {
7448                 limit = &intel_limits_i8xx_dac;
7449         }
7450
7451         if (!crtc_state->clock_set &&
7452             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7453                                  refclk, NULL, &crtc_state->dpll)) {
7454                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7455                 return -EINVAL;
7456         }
7457
7458         i8xx_compute_dpll(crtc, crtc_state, NULL);
7459
7460         return 0;
7461 }
7462
7463 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7464                                   struct intel_crtc_state *crtc_state)
7465 {
7466         struct drm_device *dev = crtc->base.dev;
7467         struct drm_i915_private *dev_priv = to_i915(dev);
7468         const struct intel_limit *limit;
7469         int refclk = 96000;
7470
7471         memset(&crtc_state->dpll_hw_state, 0,
7472                sizeof(crtc_state->dpll_hw_state));
7473
7474         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7475                 if (intel_panel_use_ssc(dev_priv)) {
7476                         refclk = dev_priv->vbt.lvds_ssc_freq;
7477                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7478                 }
7479
7480                 if (intel_is_dual_link_lvds(dev))
7481                         limit = &intel_limits_g4x_dual_channel_lvds;
7482                 else
7483                         limit = &intel_limits_g4x_single_channel_lvds;
7484         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7485                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7486                 limit = &intel_limits_g4x_hdmi;
7487         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7488                 limit = &intel_limits_g4x_sdvo;
7489         } else {
7490                 /* The option is for other outputs */
7491                 limit = &intel_limits_i9xx_sdvo;
7492         }
7493
7494         if (!crtc_state->clock_set &&
7495             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7496                                 refclk, NULL, &crtc_state->dpll)) {
7497                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7498                 return -EINVAL;
7499         }
7500
7501         i9xx_compute_dpll(crtc, crtc_state, NULL);
7502
7503         return 0;
7504 }
7505
7506 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7507                                   struct intel_crtc_state *crtc_state)
7508 {
7509         struct drm_device *dev = crtc->base.dev;
7510         struct drm_i915_private *dev_priv = to_i915(dev);
7511         const struct intel_limit *limit;
7512         int refclk = 96000;
7513
7514         memset(&crtc_state->dpll_hw_state, 0,
7515                sizeof(crtc_state->dpll_hw_state));
7516
7517         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7518                 if (intel_panel_use_ssc(dev_priv)) {
7519                         refclk = dev_priv->vbt.lvds_ssc_freq;
7520                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7521                 }
7522
7523                 limit = &intel_limits_pineview_lvds;
7524         } else {
7525                 limit = &intel_limits_pineview_sdvo;
7526         }
7527
7528         if (!crtc_state->clock_set &&
7529             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7530                                 refclk, NULL, &crtc_state->dpll)) {
7531                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7532                 return -EINVAL;
7533         }
7534
7535         i9xx_compute_dpll(crtc, crtc_state, NULL);
7536
7537         return 0;
7538 }
7539
7540 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7541                                    struct intel_crtc_state *crtc_state)
7542 {
7543         struct drm_device *dev = crtc->base.dev;
7544         struct drm_i915_private *dev_priv = to_i915(dev);
7545         const struct intel_limit *limit;
7546         int refclk = 96000;
7547
7548         memset(&crtc_state->dpll_hw_state, 0,
7549                sizeof(crtc_state->dpll_hw_state));
7550
7551         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7552                 if (intel_panel_use_ssc(dev_priv)) {
7553                         refclk = dev_priv->vbt.lvds_ssc_freq;
7554                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7555                 }
7556
7557                 limit = &intel_limits_i9xx_lvds;
7558         } else {
7559                 limit = &intel_limits_i9xx_sdvo;
7560         }
7561
7562         if (!crtc_state->clock_set &&
7563             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7564                                  refclk, NULL, &crtc_state->dpll)) {
7565                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7566                 return -EINVAL;
7567         }
7568
7569         i9xx_compute_dpll(crtc, crtc_state, NULL);
7570
7571         return 0;
7572 }
7573
7574 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7575                                   struct intel_crtc_state *crtc_state)
7576 {
7577         int refclk = 100000;
7578         const struct intel_limit *limit = &intel_limits_chv;
7579
7580         memset(&crtc_state->dpll_hw_state, 0,
7581                sizeof(crtc_state->dpll_hw_state));
7582
7583         if (!crtc_state->clock_set &&
7584             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7585                                 refclk, NULL, &crtc_state->dpll)) {
7586                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7587                 return -EINVAL;
7588         }
7589
7590         chv_compute_dpll(crtc, crtc_state);
7591
7592         return 0;
7593 }
7594
7595 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7596                                   struct intel_crtc_state *crtc_state)
7597 {
7598         int refclk = 100000;
7599         const struct intel_limit *limit = &intel_limits_vlv;
7600
7601         memset(&crtc_state->dpll_hw_state, 0,
7602                sizeof(crtc_state->dpll_hw_state));
7603
7604         if (!crtc_state->clock_set &&
7605             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7606                                 refclk, NULL, &crtc_state->dpll)) {
7607                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7608                 return -EINVAL;
7609         }
7610
7611         vlv_compute_dpll(crtc, crtc_state);
7612
7613         return 0;
7614 }
7615
7616 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7617                                  struct intel_crtc_state *pipe_config)
7618 {
7619         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7620         uint32_t tmp;
7621
7622         if (INTEL_GEN(dev_priv) <= 3 &&
7623             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7624                 return;
7625
7626         tmp = I915_READ(PFIT_CONTROL);
7627         if (!(tmp & PFIT_ENABLE))
7628                 return;
7629
7630         /* Check whether the pfit is attached to our pipe. */
7631         if (INTEL_GEN(dev_priv) < 4) {
7632                 if (crtc->pipe != PIPE_B)
7633                         return;
7634         } else {
7635                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7636                         return;
7637         }
7638
7639         pipe_config->gmch_pfit.control = tmp;
7640         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7641 }
7642
7643 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7644                                struct intel_crtc_state *pipe_config)
7645 {
7646         struct drm_device *dev = crtc->base.dev;
7647         struct drm_i915_private *dev_priv = to_i915(dev);
7648         int pipe = pipe_config->cpu_transcoder;
7649         struct dpll clock;
7650         u32 mdiv;
7651         int refclk = 100000;
7652
7653         /* In case of DSI, DPLL will not be used */
7654         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7655                 return;
7656
7657         mutex_lock(&dev_priv->sb_lock);
7658         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7659         mutex_unlock(&dev_priv->sb_lock);
7660
7661         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7662         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7663         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7664         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7665         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7666
7667         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7668 }
7669
7670 static void
7671 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7672                               struct intel_initial_plane_config *plane_config)
7673 {
7674         struct drm_device *dev = crtc->base.dev;
7675         struct drm_i915_private *dev_priv = to_i915(dev);
7676         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7677         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7678         enum pipe pipe = crtc->pipe;
7679         u32 val, base, offset;
7680         int fourcc, pixel_format;
7681         unsigned int aligned_height;
7682         struct drm_framebuffer *fb;
7683         struct intel_framebuffer *intel_fb;
7684
7685         if (!plane->get_hw_state(plane))
7686                 return;
7687
7688         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7689         if (!intel_fb) {
7690                 DRM_DEBUG_KMS("failed to alloc fb\n");
7691                 return;
7692         }
7693
7694         fb = &intel_fb->base;
7695
7696         fb->dev = dev;
7697
7698         val = I915_READ(DSPCNTR(i9xx_plane));
7699
7700         if (INTEL_GEN(dev_priv) >= 4) {
7701                 if (val & DISPPLANE_TILED) {
7702                         plane_config->tiling = I915_TILING_X;
7703                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7704                 }
7705         }
7706
7707         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7708         fourcc = i9xx_format_to_fourcc(pixel_format);
7709         fb->format = drm_format_info(fourcc);
7710
7711         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7712                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7713                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7714         } else if (INTEL_GEN(dev_priv) >= 4) {
7715                 if (plane_config->tiling)
7716                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7717                 else
7718                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7719                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7720         } else {
7721                 base = I915_READ(DSPADDR(i9xx_plane));
7722         }
7723         plane_config->base = base;
7724
7725         val = I915_READ(PIPESRC(pipe));
7726         fb->width = ((val >> 16) & 0xfff) + 1;
7727         fb->height = ((val >> 0) & 0xfff) + 1;
7728
7729         val = I915_READ(DSPSTRIDE(i9xx_plane));
7730         fb->pitches[0] = val & 0xffffffc0;
7731
7732         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7733
7734         plane_config->size = fb->pitches[0] * aligned_height;
7735
7736         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7737                       crtc->base.name, plane->base.name, fb->width, fb->height,
7738                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7739                       plane_config->size);
7740
7741         plane_config->fb = intel_fb;
7742 }
7743
7744 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7745                                struct intel_crtc_state *pipe_config)
7746 {
7747         struct drm_device *dev = crtc->base.dev;
7748         struct drm_i915_private *dev_priv = to_i915(dev);
7749         int pipe = pipe_config->cpu_transcoder;
7750         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7751         struct dpll clock;
7752         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7753         int refclk = 100000;
7754
7755         /* In case of DSI, DPLL will not be used */
7756         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7757                 return;
7758
7759         mutex_lock(&dev_priv->sb_lock);
7760         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7761         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7762         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7763         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7764         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7765         mutex_unlock(&dev_priv->sb_lock);
7766
7767         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7768         clock.m2 = (pll_dw0 & 0xff) << 22;
7769         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7770                 clock.m2 |= pll_dw2 & 0x3fffff;
7771         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7772         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7773         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7774
7775         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7776 }
7777
7778 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7779                                  struct intel_crtc_state *pipe_config)
7780 {
7781         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7782         enum intel_display_power_domain power_domain;
7783         uint32_t tmp;
7784         bool ret;
7785
7786         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7787         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7788                 return false;
7789
7790         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7791         pipe_config->shared_dpll = NULL;
7792
7793         ret = false;
7794
7795         tmp = I915_READ(PIPECONF(crtc->pipe));
7796         if (!(tmp & PIPECONF_ENABLE))
7797                 goto out;
7798
7799         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7800             IS_CHERRYVIEW(dev_priv)) {
7801                 switch (tmp & PIPECONF_BPC_MASK) {
7802                 case PIPECONF_6BPC:
7803                         pipe_config->pipe_bpp = 18;
7804                         break;
7805                 case PIPECONF_8BPC:
7806                         pipe_config->pipe_bpp = 24;
7807                         break;
7808                 case PIPECONF_10BPC:
7809                         pipe_config->pipe_bpp = 30;
7810                         break;
7811                 default:
7812                         break;
7813                 }
7814         }
7815
7816         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7817             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7818                 pipe_config->limited_color_range = true;
7819
7820         if (INTEL_GEN(dev_priv) < 4)
7821                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7822
7823         intel_get_pipe_timings(crtc, pipe_config);
7824         intel_get_pipe_src_size(crtc, pipe_config);
7825
7826         i9xx_get_pfit_config(crtc, pipe_config);
7827
7828         if (INTEL_GEN(dev_priv) >= 4) {
7829                 /* No way to read it out on pipes B and C */
7830                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7831                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7832                 else
7833                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7834                 pipe_config->pixel_multiplier =
7835                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7836                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7837                 pipe_config->dpll_hw_state.dpll_md = tmp;
7838         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7839                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7840                 tmp = I915_READ(DPLL(crtc->pipe));
7841                 pipe_config->pixel_multiplier =
7842                         ((tmp & SDVO_MULTIPLIER_MASK)
7843                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7844         } else {
7845                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7846                  * port and will be fixed up in the encoder->get_config
7847                  * function. */
7848                 pipe_config->pixel_multiplier = 1;
7849         }
7850         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7851         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7852                 /*
7853                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7854                  * on 830. Filter it out here so that we don't
7855                  * report errors due to that.
7856                  */
7857                 if (IS_I830(dev_priv))
7858                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7859
7860                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7861                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7862         } else {
7863                 /* Mask out read-only status bits. */
7864                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7865                                                      DPLL_PORTC_READY_MASK |
7866                                                      DPLL_PORTB_READY_MASK);
7867         }
7868
7869         if (IS_CHERRYVIEW(dev_priv))
7870                 chv_crtc_clock_get(crtc, pipe_config);
7871         else if (IS_VALLEYVIEW(dev_priv))
7872                 vlv_crtc_clock_get(crtc, pipe_config);
7873         else
7874                 i9xx_crtc_clock_get(crtc, pipe_config);
7875
7876         /*
7877          * Normally the dotclock is filled in by the encoder .get_config()
7878          * but in case the pipe is enabled w/o any ports we need a sane
7879          * default.
7880          */
7881         pipe_config->base.adjusted_mode.crtc_clock =
7882                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7883
7884         ret = true;
7885
7886 out:
7887         intel_display_power_put(dev_priv, power_domain);
7888
7889         return ret;
7890 }
7891
7892 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7893 {
7894         struct intel_encoder *encoder;
7895         int i;
7896         u32 val, final;
7897         bool has_lvds = false;
7898         bool has_cpu_edp = false;
7899         bool has_panel = false;
7900         bool has_ck505 = false;
7901         bool can_ssc = false;
7902         bool using_ssc_source = false;
7903
7904         /* We need to take the global config into account */
7905         for_each_intel_encoder(&dev_priv->drm, encoder) {
7906                 switch (encoder->type) {
7907                 case INTEL_OUTPUT_LVDS:
7908                         has_panel = true;
7909                         has_lvds = true;
7910                         break;
7911                 case INTEL_OUTPUT_EDP:
7912                         has_panel = true;
7913                         if (encoder->port == PORT_A)
7914                                 has_cpu_edp = true;
7915                         break;
7916                 default:
7917                         break;
7918                 }
7919         }
7920
7921         if (HAS_PCH_IBX(dev_priv)) {
7922                 has_ck505 = dev_priv->vbt.display_clock_mode;
7923                 can_ssc = has_ck505;
7924         } else {
7925                 has_ck505 = false;
7926                 can_ssc = true;
7927         }
7928
7929         /* Check if any DPLLs are using the SSC source */
7930         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7931                 u32 temp = I915_READ(PCH_DPLL(i));
7932
7933                 if (!(temp & DPLL_VCO_ENABLE))
7934                         continue;
7935
7936                 if ((temp & PLL_REF_INPUT_MASK) ==
7937                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7938                         using_ssc_source = true;
7939                         break;
7940                 }
7941         }
7942
7943         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7944                       has_panel, has_lvds, has_ck505, using_ssc_source);
7945
7946         /* Ironlake: try to setup display ref clock before DPLL
7947          * enabling. This is only under driver's control after
7948          * PCH B stepping, previous chipset stepping should be
7949          * ignoring this setting.
7950          */
7951         val = I915_READ(PCH_DREF_CONTROL);
7952
7953         /* As we must carefully and slowly disable/enable each source in turn,
7954          * compute the final state we want first and check if we need to
7955          * make any changes at all.
7956          */
7957         final = val;
7958         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7959         if (has_ck505)
7960                 final |= DREF_NONSPREAD_CK505_ENABLE;
7961         else
7962                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7963
7964         final &= ~DREF_SSC_SOURCE_MASK;
7965         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7966         final &= ~DREF_SSC1_ENABLE;
7967
7968         if (has_panel) {
7969                 final |= DREF_SSC_SOURCE_ENABLE;
7970
7971                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7972                         final |= DREF_SSC1_ENABLE;
7973
7974                 if (has_cpu_edp) {
7975                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7976                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7977                         else
7978                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7979                 } else
7980                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7981         } else if (using_ssc_source) {
7982                 final |= DREF_SSC_SOURCE_ENABLE;
7983                 final |= DREF_SSC1_ENABLE;
7984         }
7985
7986         if (final == val)
7987                 return;
7988
7989         /* Always enable nonspread source */
7990         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7991
7992         if (has_ck505)
7993                 val |= DREF_NONSPREAD_CK505_ENABLE;
7994         else
7995                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7996
7997         if (has_panel) {
7998                 val &= ~DREF_SSC_SOURCE_MASK;
7999                 val |= DREF_SSC_SOURCE_ENABLE;
8000
8001                 /* SSC must be turned on before enabling the CPU output  */
8002                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8003                         DRM_DEBUG_KMS("Using SSC on panel\n");
8004                         val |= DREF_SSC1_ENABLE;
8005                 } else
8006                         val &= ~DREF_SSC1_ENABLE;
8007
8008                 /* Get SSC going before enabling the outputs */
8009                 I915_WRITE(PCH_DREF_CONTROL, val);
8010                 POSTING_READ(PCH_DREF_CONTROL);
8011                 udelay(200);
8012
8013                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8014
8015                 /* Enable CPU source on CPU attached eDP */
8016                 if (has_cpu_edp) {
8017                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8018                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8019                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8020                         } else
8021                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8022                 } else
8023                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8024
8025                 I915_WRITE(PCH_DREF_CONTROL, val);
8026                 POSTING_READ(PCH_DREF_CONTROL);
8027                 udelay(200);
8028         } else {
8029                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8030
8031                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8032
8033                 /* Turn off CPU output */
8034                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8035
8036                 I915_WRITE(PCH_DREF_CONTROL, val);
8037                 POSTING_READ(PCH_DREF_CONTROL);
8038                 udelay(200);
8039
8040                 if (!using_ssc_source) {
8041                         DRM_DEBUG_KMS("Disabling SSC source\n");
8042
8043                         /* Turn off the SSC source */
8044                         val &= ~DREF_SSC_SOURCE_MASK;
8045                         val |= DREF_SSC_SOURCE_DISABLE;
8046
8047                         /* Turn off SSC1 */
8048                         val &= ~DREF_SSC1_ENABLE;
8049
8050                         I915_WRITE(PCH_DREF_CONTROL, val);
8051                         POSTING_READ(PCH_DREF_CONTROL);
8052                         udelay(200);
8053                 }
8054         }
8055
8056         BUG_ON(val != final);
8057 }
8058
8059 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8060 {
8061         uint32_t tmp;
8062
8063         tmp = I915_READ(SOUTH_CHICKEN2);
8064         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8065         I915_WRITE(SOUTH_CHICKEN2, tmp);
8066
8067         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8068                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8069                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8070
8071         tmp = I915_READ(SOUTH_CHICKEN2);
8072         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8073         I915_WRITE(SOUTH_CHICKEN2, tmp);
8074
8075         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8076                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8077                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8078 }
8079
8080 /* WaMPhyProgramming:hsw */
8081 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8082 {
8083         uint32_t tmp;
8084
8085         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8086         tmp &= ~(0xFF << 24);
8087         tmp |= (0x12 << 24);
8088         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8089
8090         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8091         tmp |= (1 << 11);
8092         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8093
8094         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8095         tmp |= (1 << 11);
8096         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8097
8098         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8099         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8100         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8101
8102         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8103         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8104         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8105
8106         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8107         tmp &= ~(7 << 13);
8108         tmp |= (5 << 13);
8109         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8110
8111         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8112         tmp &= ~(7 << 13);
8113         tmp |= (5 << 13);
8114         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8115
8116         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8117         tmp &= ~0xFF;
8118         tmp |= 0x1C;
8119         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8120
8121         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8122         tmp &= ~0xFF;
8123         tmp |= 0x1C;
8124         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8125
8126         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8127         tmp &= ~(0xFF << 16);
8128         tmp |= (0x1C << 16);
8129         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8130
8131         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8132         tmp &= ~(0xFF << 16);
8133         tmp |= (0x1C << 16);
8134         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8135
8136         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8137         tmp |= (1 << 27);
8138         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8139
8140         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8141         tmp |= (1 << 27);
8142         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8143
8144         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8145         tmp &= ~(0xF << 28);
8146         tmp |= (4 << 28);
8147         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8148
8149         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8150         tmp &= ~(0xF << 28);
8151         tmp |= (4 << 28);
8152         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8153 }
8154
8155 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8156  * Programming" based on the parameters passed:
8157  * - Sequence to enable CLKOUT_DP
8158  * - Sequence to enable CLKOUT_DP without spread
8159  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8160  */
8161 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8162                                  bool with_spread, bool with_fdi)
8163 {
8164         uint32_t reg, tmp;
8165
8166         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8167                 with_spread = true;
8168         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8169             with_fdi, "LP PCH doesn't have FDI\n"))
8170                 with_fdi = false;
8171
8172         mutex_lock(&dev_priv->sb_lock);
8173
8174         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8175         tmp &= ~SBI_SSCCTL_DISABLE;
8176         tmp |= SBI_SSCCTL_PATHALT;
8177         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8178
8179         udelay(24);
8180
8181         if (with_spread) {
8182                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8183                 tmp &= ~SBI_SSCCTL_PATHALT;
8184                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8185
8186                 if (with_fdi) {
8187                         lpt_reset_fdi_mphy(dev_priv);
8188                         lpt_program_fdi_mphy(dev_priv);
8189                 }
8190         }
8191
8192         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8193         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8194         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8195         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8196
8197         mutex_unlock(&dev_priv->sb_lock);
8198 }
8199
8200 /* Sequence to disable CLKOUT_DP */
8201 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8202 {
8203         uint32_t reg, tmp;
8204
8205         mutex_lock(&dev_priv->sb_lock);
8206
8207         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8208         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8209         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8210         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8211
8212         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8213         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8214                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8215                         tmp |= SBI_SSCCTL_PATHALT;
8216                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8217                         udelay(32);
8218                 }
8219                 tmp |= SBI_SSCCTL_DISABLE;
8220                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8221         }
8222
8223         mutex_unlock(&dev_priv->sb_lock);
8224 }
8225
8226 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8227
8228 static const uint16_t sscdivintphase[] = {
8229         [BEND_IDX( 50)] = 0x3B23,
8230         [BEND_IDX( 45)] = 0x3B23,
8231         [BEND_IDX( 40)] = 0x3C23,
8232         [BEND_IDX( 35)] = 0x3C23,
8233         [BEND_IDX( 30)] = 0x3D23,
8234         [BEND_IDX( 25)] = 0x3D23,
8235         [BEND_IDX( 20)] = 0x3E23,
8236         [BEND_IDX( 15)] = 0x3E23,
8237         [BEND_IDX( 10)] = 0x3F23,
8238         [BEND_IDX(  5)] = 0x3F23,
8239         [BEND_IDX(  0)] = 0x0025,
8240         [BEND_IDX( -5)] = 0x0025,
8241         [BEND_IDX(-10)] = 0x0125,
8242         [BEND_IDX(-15)] = 0x0125,
8243         [BEND_IDX(-20)] = 0x0225,
8244         [BEND_IDX(-25)] = 0x0225,
8245         [BEND_IDX(-30)] = 0x0325,
8246         [BEND_IDX(-35)] = 0x0325,
8247         [BEND_IDX(-40)] = 0x0425,
8248         [BEND_IDX(-45)] = 0x0425,
8249         [BEND_IDX(-50)] = 0x0525,
8250 };
8251
8252 /*
8253  * Bend CLKOUT_DP
8254  * steps -50 to 50 inclusive, in steps of 5
8255  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8256  * change in clock period = -(steps / 10) * 5.787 ps
8257  */
8258 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8259 {
8260         uint32_t tmp;
8261         int idx = BEND_IDX(steps);
8262
8263         if (WARN_ON(steps % 5 != 0))
8264                 return;
8265
8266         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8267                 return;
8268
8269         mutex_lock(&dev_priv->sb_lock);
8270
8271         if (steps % 10 != 0)
8272                 tmp = 0xAAAAAAAB;
8273         else
8274                 tmp = 0x00000000;
8275         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8276
8277         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8278         tmp &= 0xffff0000;
8279         tmp |= sscdivintphase[idx];
8280         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8281
8282         mutex_unlock(&dev_priv->sb_lock);
8283 }
8284
8285 #undef BEND_IDX
8286
8287 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8288 {
8289         struct intel_encoder *encoder;
8290         bool has_vga = false;
8291
8292         for_each_intel_encoder(&dev_priv->drm, encoder) {
8293                 switch (encoder->type) {
8294                 case INTEL_OUTPUT_ANALOG:
8295                         has_vga = true;
8296                         break;
8297                 default:
8298                         break;
8299                 }
8300         }
8301
8302         if (has_vga) {
8303                 lpt_bend_clkout_dp(dev_priv, 0);
8304                 lpt_enable_clkout_dp(dev_priv, true, true);
8305         } else {
8306                 lpt_disable_clkout_dp(dev_priv);
8307         }
8308 }
8309
8310 /*
8311  * Initialize reference clocks when the driver loads
8312  */
8313 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8314 {
8315         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8316                 ironlake_init_pch_refclk(dev_priv);
8317         else if (HAS_PCH_LPT(dev_priv))
8318                 lpt_init_pch_refclk(dev_priv);
8319 }
8320
8321 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8322 {
8323         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8324         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8325         int pipe = intel_crtc->pipe;
8326         uint32_t val;
8327
8328         val = 0;
8329
8330         switch (intel_crtc->config->pipe_bpp) {
8331         case 18:
8332                 val |= PIPECONF_6BPC;
8333                 break;
8334         case 24:
8335                 val |= PIPECONF_8BPC;
8336                 break;
8337         case 30:
8338                 val |= PIPECONF_10BPC;
8339                 break;
8340         case 36:
8341                 val |= PIPECONF_12BPC;
8342                 break;
8343         default:
8344                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8345                 BUG();
8346         }
8347
8348         if (intel_crtc->config->dither)
8349                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8350
8351         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8352                 val |= PIPECONF_INTERLACED_ILK;
8353         else
8354                 val |= PIPECONF_PROGRESSIVE;
8355
8356         if (intel_crtc->config->limited_color_range)
8357                 val |= PIPECONF_COLOR_RANGE_SELECT;
8358
8359         I915_WRITE(PIPECONF(pipe), val);
8360         POSTING_READ(PIPECONF(pipe));
8361 }
8362
8363 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8364 {
8365         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8366         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8367         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8368         u32 val = 0;
8369
8370         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8371                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8372
8373         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8374                 val |= PIPECONF_INTERLACED_ILK;
8375         else
8376                 val |= PIPECONF_PROGRESSIVE;
8377
8378         I915_WRITE(PIPECONF(cpu_transcoder), val);
8379         POSTING_READ(PIPECONF(cpu_transcoder));
8380 }
8381
8382 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8383 {
8384         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8385         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8386         struct intel_crtc_state *config = intel_crtc->config;
8387
8388         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8389                 u32 val = 0;
8390
8391                 switch (intel_crtc->config->pipe_bpp) {
8392                 case 18:
8393                         val |= PIPEMISC_DITHER_6_BPC;
8394                         break;
8395                 case 24:
8396                         val |= PIPEMISC_DITHER_8_BPC;
8397                         break;
8398                 case 30:
8399                         val |= PIPEMISC_DITHER_10_BPC;
8400                         break;
8401                 case 36:
8402                         val |= PIPEMISC_DITHER_12_BPC;
8403                         break;
8404                 default:
8405                         /* Case prevented by pipe_config_set_bpp. */
8406                         BUG();
8407                 }
8408
8409                 if (intel_crtc->config->dither)
8410                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8411
8412                 if (config->ycbcr420) {
8413                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8414                                 PIPEMISC_YUV420_ENABLE |
8415                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8416                 }
8417
8418                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8419         }
8420 }
8421
8422 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8423 {
8424         /*
8425          * Account for spread spectrum to avoid
8426          * oversubscribing the link. Max center spread
8427          * is 2.5%; use 5% for safety's sake.
8428          */
8429         u32 bps = target_clock * bpp * 21 / 20;
8430         return DIV_ROUND_UP(bps, link_bw * 8);
8431 }
8432
8433 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8434 {
8435         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8436 }
8437
8438 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8439                                   struct intel_crtc_state *crtc_state,
8440                                   struct dpll *reduced_clock)
8441 {
8442         struct drm_crtc *crtc = &intel_crtc->base;
8443         struct drm_device *dev = crtc->dev;
8444         struct drm_i915_private *dev_priv = to_i915(dev);
8445         u32 dpll, fp, fp2;
8446         int factor;
8447
8448         /* Enable autotuning of the PLL clock (if permissible) */
8449         factor = 21;
8450         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8451                 if ((intel_panel_use_ssc(dev_priv) &&
8452                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8453                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8454                         factor = 25;
8455         } else if (crtc_state->sdvo_tv_clock)
8456                 factor = 20;
8457
8458         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8459
8460         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8461                 fp |= FP_CB_TUNE;
8462
8463         if (reduced_clock) {
8464                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8465
8466                 if (reduced_clock->m < factor * reduced_clock->n)
8467                         fp2 |= FP_CB_TUNE;
8468         } else {
8469                 fp2 = fp;
8470         }
8471
8472         dpll = 0;
8473
8474         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8475                 dpll |= DPLLB_MODE_LVDS;
8476         else
8477                 dpll |= DPLLB_MODE_DAC_SERIAL;
8478
8479         dpll |= (crtc_state->pixel_multiplier - 1)
8480                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8481
8482         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8483             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8484                 dpll |= DPLL_SDVO_HIGH_SPEED;
8485
8486         if (intel_crtc_has_dp_encoder(crtc_state))
8487                 dpll |= DPLL_SDVO_HIGH_SPEED;
8488
8489         /*
8490          * The high speed IO clock is only really required for
8491          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8492          * possible to share the DPLL between CRT and HDMI. Enabling
8493          * the clock needlessly does no real harm, except use up a
8494          * bit of power potentially.
8495          *
8496          * We'll limit this to IVB with 3 pipes, since it has only two
8497          * DPLLs and so DPLL sharing is the only way to get three pipes
8498          * driving PCH ports at the same time. On SNB we could do this,
8499          * and potentially avoid enabling the second DPLL, but it's not
8500          * clear if it''s a win or loss power wise. No point in doing
8501          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8502          */
8503         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8504             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8505                 dpll |= DPLL_SDVO_HIGH_SPEED;
8506
8507         /* compute bitmask from p1 value */
8508         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8509         /* also FPA1 */
8510         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8511
8512         switch (crtc_state->dpll.p2) {
8513         case 5:
8514                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8515                 break;
8516         case 7:
8517                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8518                 break;
8519         case 10:
8520                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8521                 break;
8522         case 14:
8523                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8524                 break;
8525         }
8526
8527         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8528             intel_panel_use_ssc(dev_priv))
8529                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8530         else
8531                 dpll |= PLL_REF_INPUT_DREFCLK;
8532
8533         dpll |= DPLL_VCO_ENABLE;
8534
8535         crtc_state->dpll_hw_state.dpll = dpll;
8536         crtc_state->dpll_hw_state.fp0 = fp;
8537         crtc_state->dpll_hw_state.fp1 = fp2;
8538 }
8539
8540 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8541                                        struct intel_crtc_state *crtc_state)
8542 {
8543         struct drm_device *dev = crtc->base.dev;
8544         struct drm_i915_private *dev_priv = to_i915(dev);
8545         const struct intel_limit *limit;
8546         int refclk = 120000;
8547
8548         memset(&crtc_state->dpll_hw_state, 0,
8549                sizeof(crtc_state->dpll_hw_state));
8550
8551         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8552         if (!crtc_state->has_pch_encoder)
8553                 return 0;
8554
8555         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8556                 if (intel_panel_use_ssc(dev_priv)) {
8557                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8558                                       dev_priv->vbt.lvds_ssc_freq);
8559                         refclk = dev_priv->vbt.lvds_ssc_freq;
8560                 }
8561
8562                 if (intel_is_dual_link_lvds(dev)) {
8563                         if (refclk == 100000)
8564                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8565                         else
8566                                 limit = &intel_limits_ironlake_dual_lvds;
8567                 } else {
8568                         if (refclk == 100000)
8569                                 limit = &intel_limits_ironlake_single_lvds_100m;
8570                         else
8571                                 limit = &intel_limits_ironlake_single_lvds;
8572                 }
8573         } else {
8574                 limit = &intel_limits_ironlake_dac;
8575         }
8576
8577         if (!crtc_state->clock_set &&
8578             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8579                                 refclk, NULL, &crtc_state->dpll)) {
8580                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8581                 return -EINVAL;
8582         }
8583
8584         ironlake_compute_dpll(crtc, crtc_state, NULL);
8585
8586         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8587                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8588                                  pipe_name(crtc->pipe));
8589                 return -EINVAL;
8590         }
8591
8592         return 0;
8593 }
8594
8595 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8596                                          struct intel_link_m_n *m_n)
8597 {
8598         struct drm_device *dev = crtc->base.dev;
8599         struct drm_i915_private *dev_priv = to_i915(dev);
8600         enum pipe pipe = crtc->pipe;
8601
8602         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8603         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8604         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8605                 & ~TU_SIZE_MASK;
8606         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8607         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8608                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8609 }
8610
8611 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8612                                          enum transcoder transcoder,
8613                                          struct intel_link_m_n *m_n,
8614                                          struct intel_link_m_n *m2_n2)
8615 {
8616         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8617         enum pipe pipe = crtc->pipe;
8618
8619         if (INTEL_GEN(dev_priv) >= 5) {
8620                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8621                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8622                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8623                         & ~TU_SIZE_MASK;
8624                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8625                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8626                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8627                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8628                  * gen < 8) and if DRRS is supported (to make sure the
8629                  * registers are not unnecessarily read).
8630                  */
8631                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8632                         crtc->config->has_drrs) {
8633                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8634                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8635                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8636                                         & ~TU_SIZE_MASK;
8637                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8638                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8639                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8640                 }
8641         } else {
8642                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8643                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8644                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8645                         & ~TU_SIZE_MASK;
8646                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8647                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8648                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8649         }
8650 }
8651
8652 void intel_dp_get_m_n(struct intel_crtc *crtc,
8653                       struct intel_crtc_state *pipe_config)
8654 {
8655         if (pipe_config->has_pch_encoder)
8656                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8657         else
8658                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8659                                              &pipe_config->dp_m_n,
8660                                              &pipe_config->dp_m2_n2);
8661 }
8662
8663 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8664                                         struct intel_crtc_state *pipe_config)
8665 {
8666         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8667                                      &pipe_config->fdi_m_n, NULL);
8668 }
8669
8670 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8671                                     struct intel_crtc_state *pipe_config)
8672 {
8673         struct drm_device *dev = crtc->base.dev;
8674         struct drm_i915_private *dev_priv = to_i915(dev);
8675         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8676         uint32_t ps_ctrl = 0;
8677         int id = -1;
8678         int i;
8679
8680         /* find scaler attached to this pipe */
8681         for (i = 0; i < crtc->num_scalers; i++) {
8682                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8683                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8684                         id = i;
8685                         pipe_config->pch_pfit.enabled = true;
8686                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8687                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8688                         break;
8689                 }
8690         }
8691
8692         scaler_state->scaler_id = id;
8693         if (id >= 0) {
8694                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8695         } else {
8696                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8697         }
8698 }
8699
8700 static void
8701 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8702                                  struct intel_initial_plane_config *plane_config)
8703 {
8704         struct drm_device *dev = crtc->base.dev;
8705         struct drm_i915_private *dev_priv = to_i915(dev);
8706         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8707         enum plane_id plane_id = plane->id;
8708         enum pipe pipe = crtc->pipe;
8709         u32 val, base, offset, stride_mult, tiling, alpha;
8710         int fourcc, pixel_format;
8711         unsigned int aligned_height;
8712         struct drm_framebuffer *fb;
8713         struct intel_framebuffer *intel_fb;
8714
8715         if (!plane->get_hw_state(plane))
8716                 return;
8717
8718         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8719         if (!intel_fb) {
8720                 DRM_DEBUG_KMS("failed to alloc fb\n");
8721                 return;
8722         }
8723
8724         fb = &intel_fb->base;
8725
8726         fb->dev = dev;
8727
8728         val = I915_READ(PLANE_CTL(pipe, plane_id));
8729
8730         if (INTEL_GEN(dev_priv) >= 11)
8731                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8732         else
8733                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8734
8735         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8736                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8737                 alpha &= PLANE_COLOR_ALPHA_MASK;
8738         } else {
8739                 alpha = val & PLANE_CTL_ALPHA_MASK;
8740         }
8741
8742         fourcc = skl_format_to_fourcc(pixel_format,
8743                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8744         fb->format = drm_format_info(fourcc);
8745
8746         tiling = val & PLANE_CTL_TILED_MASK;
8747         switch (tiling) {
8748         case PLANE_CTL_TILED_LINEAR:
8749                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8750                 break;
8751         case PLANE_CTL_TILED_X:
8752                 plane_config->tiling = I915_TILING_X;
8753                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8754                 break;
8755         case PLANE_CTL_TILED_Y:
8756                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8757                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8758                 else
8759                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8760                 break;
8761         case PLANE_CTL_TILED_YF:
8762                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8763                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8764                 else
8765                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8766                 break;
8767         default:
8768                 MISSING_CASE(tiling);
8769                 goto error;
8770         }
8771
8772         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8773         plane_config->base = base;
8774
8775         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8776
8777         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8778         fb->height = ((val >> 16) & 0xfff) + 1;
8779         fb->width = ((val >> 0) & 0x1fff) + 1;
8780
8781         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8782         stride_mult = intel_fb_stride_alignment(fb, 0);
8783         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8784
8785         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8786
8787         plane_config->size = fb->pitches[0] * aligned_height;
8788
8789         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8790                       crtc->base.name, plane->base.name, fb->width, fb->height,
8791                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8792                       plane_config->size);
8793
8794         plane_config->fb = intel_fb;
8795         return;
8796
8797 error:
8798         kfree(intel_fb);
8799 }
8800
8801 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8802                                      struct intel_crtc_state *pipe_config)
8803 {
8804         struct drm_device *dev = crtc->base.dev;
8805         struct drm_i915_private *dev_priv = to_i915(dev);
8806         uint32_t tmp;
8807
8808         tmp = I915_READ(PF_CTL(crtc->pipe));
8809
8810         if (tmp & PF_ENABLE) {
8811                 pipe_config->pch_pfit.enabled = true;
8812                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8813                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8814
8815                 /* We currently do not free assignements of panel fitters on
8816                  * ivb/hsw (since we don't use the higher upscaling modes which
8817                  * differentiates them) so just WARN about this case for now. */
8818                 if (IS_GEN7(dev_priv)) {
8819                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8820                                 PF_PIPE_SEL_IVB(crtc->pipe));
8821                 }
8822         }
8823 }
8824
8825 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8826                                      struct intel_crtc_state *pipe_config)
8827 {
8828         struct drm_device *dev = crtc->base.dev;
8829         struct drm_i915_private *dev_priv = to_i915(dev);
8830         enum intel_display_power_domain power_domain;
8831         uint32_t tmp;
8832         bool ret;
8833
8834         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8835         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8836                 return false;
8837
8838         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8839         pipe_config->shared_dpll = NULL;
8840
8841         ret = false;
8842         tmp = I915_READ(PIPECONF(crtc->pipe));
8843         if (!(tmp & PIPECONF_ENABLE))
8844                 goto out;
8845
8846         switch (tmp & PIPECONF_BPC_MASK) {
8847         case PIPECONF_6BPC:
8848                 pipe_config->pipe_bpp = 18;
8849                 break;
8850         case PIPECONF_8BPC:
8851                 pipe_config->pipe_bpp = 24;
8852                 break;
8853         case PIPECONF_10BPC:
8854                 pipe_config->pipe_bpp = 30;
8855                 break;
8856         case PIPECONF_12BPC:
8857                 pipe_config->pipe_bpp = 36;
8858                 break;
8859         default:
8860                 break;
8861         }
8862
8863         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8864                 pipe_config->limited_color_range = true;
8865
8866         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8867                 struct intel_shared_dpll *pll;
8868                 enum intel_dpll_id pll_id;
8869
8870                 pipe_config->has_pch_encoder = true;
8871
8872                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8873                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8874                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8875
8876                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8877
8878                 if (HAS_PCH_IBX(dev_priv)) {
8879                         /*
8880                          * The pipe->pch transcoder and pch transcoder->pll
8881                          * mapping is fixed.
8882                          */
8883                         pll_id = (enum intel_dpll_id) crtc->pipe;
8884                 } else {
8885                         tmp = I915_READ(PCH_DPLL_SEL);
8886                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8887                                 pll_id = DPLL_ID_PCH_PLL_B;
8888                         else
8889                                 pll_id= DPLL_ID_PCH_PLL_A;
8890                 }
8891
8892                 pipe_config->shared_dpll =
8893                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8894                 pll = pipe_config->shared_dpll;
8895
8896                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
8897                                                 &pipe_config->dpll_hw_state));
8898
8899                 tmp = pipe_config->dpll_hw_state.dpll;
8900                 pipe_config->pixel_multiplier =
8901                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8902                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8903
8904                 ironlake_pch_clock_get(crtc, pipe_config);
8905         } else {
8906                 pipe_config->pixel_multiplier = 1;
8907         }
8908
8909         intel_get_pipe_timings(crtc, pipe_config);
8910         intel_get_pipe_src_size(crtc, pipe_config);
8911
8912         ironlake_get_pfit_config(crtc, pipe_config);
8913
8914         ret = true;
8915
8916 out:
8917         intel_display_power_put(dev_priv, power_domain);
8918
8919         return ret;
8920 }
8921
8922 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8923 {
8924         struct drm_device *dev = &dev_priv->drm;
8925         struct intel_crtc *crtc;
8926
8927         for_each_intel_crtc(dev, crtc)
8928                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8929                      pipe_name(crtc->pipe));
8930
8931         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8932                         "Display power well on\n");
8933         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8934         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8935         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8936         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8937         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8938              "CPU PWM1 enabled\n");
8939         if (IS_HASWELL(dev_priv))
8940                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8941                      "CPU PWM2 enabled\n");
8942         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8943              "PCH PWM1 enabled\n");
8944         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8945              "Utility pin enabled\n");
8946         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8947
8948         /*
8949          * In theory we can still leave IRQs enabled, as long as only the HPD
8950          * interrupts remain enabled. We used to check for that, but since it's
8951          * gen-specific and since we only disable LCPLL after we fully disable
8952          * the interrupts, the check below should be enough.
8953          */
8954         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8955 }
8956
8957 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8958 {
8959         if (IS_HASWELL(dev_priv))
8960                 return I915_READ(D_COMP_HSW);
8961         else
8962                 return I915_READ(D_COMP_BDW);
8963 }
8964
8965 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8966 {
8967         if (IS_HASWELL(dev_priv)) {
8968                 mutex_lock(&dev_priv->pcu_lock);
8969                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8970                                             val))
8971                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8972                 mutex_unlock(&dev_priv->pcu_lock);
8973         } else {
8974                 I915_WRITE(D_COMP_BDW, val);
8975                 POSTING_READ(D_COMP_BDW);
8976         }
8977 }
8978
8979 /*
8980  * This function implements pieces of two sequences from BSpec:
8981  * - Sequence for display software to disable LCPLL
8982  * - Sequence for display software to allow package C8+
8983  * The steps implemented here are just the steps that actually touch the LCPLL
8984  * register. Callers should take care of disabling all the display engine
8985  * functions, doing the mode unset, fixing interrupts, etc.
8986  */
8987 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8988                               bool switch_to_fclk, bool allow_power_down)
8989 {
8990         uint32_t val;
8991
8992         assert_can_disable_lcpll(dev_priv);
8993
8994         val = I915_READ(LCPLL_CTL);
8995
8996         if (switch_to_fclk) {
8997                 val |= LCPLL_CD_SOURCE_FCLK;
8998                 I915_WRITE(LCPLL_CTL, val);
8999
9000                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9001                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9002                         DRM_ERROR("Switching to FCLK failed\n");
9003
9004                 val = I915_READ(LCPLL_CTL);
9005         }
9006
9007         val |= LCPLL_PLL_DISABLE;
9008         I915_WRITE(LCPLL_CTL, val);
9009         POSTING_READ(LCPLL_CTL);
9010
9011         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9012                 DRM_ERROR("LCPLL still locked\n");
9013
9014         val = hsw_read_dcomp(dev_priv);
9015         val |= D_COMP_COMP_DISABLE;
9016         hsw_write_dcomp(dev_priv, val);
9017         ndelay(100);
9018
9019         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9020                      1))
9021                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9022
9023         if (allow_power_down) {
9024                 val = I915_READ(LCPLL_CTL);
9025                 val |= LCPLL_POWER_DOWN_ALLOW;
9026                 I915_WRITE(LCPLL_CTL, val);
9027                 POSTING_READ(LCPLL_CTL);
9028         }
9029 }
9030
9031 /*
9032  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9033  * source.
9034  */
9035 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9036 {
9037         uint32_t val;
9038
9039         val = I915_READ(LCPLL_CTL);
9040
9041         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9042                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9043                 return;
9044
9045         /*
9046          * Make sure we're not on PC8 state before disabling PC8, otherwise
9047          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9048          */
9049         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9050
9051         if (val & LCPLL_POWER_DOWN_ALLOW) {
9052                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9053                 I915_WRITE(LCPLL_CTL, val);
9054                 POSTING_READ(LCPLL_CTL);
9055         }
9056
9057         val = hsw_read_dcomp(dev_priv);
9058         val |= D_COMP_COMP_FORCE;
9059         val &= ~D_COMP_COMP_DISABLE;
9060         hsw_write_dcomp(dev_priv, val);
9061
9062         val = I915_READ(LCPLL_CTL);
9063         val &= ~LCPLL_PLL_DISABLE;
9064         I915_WRITE(LCPLL_CTL, val);
9065
9066         if (intel_wait_for_register(dev_priv,
9067                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9068                                     5))
9069                 DRM_ERROR("LCPLL not locked yet\n");
9070
9071         if (val & LCPLL_CD_SOURCE_FCLK) {
9072                 val = I915_READ(LCPLL_CTL);
9073                 val &= ~LCPLL_CD_SOURCE_FCLK;
9074                 I915_WRITE(LCPLL_CTL, val);
9075
9076                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9077                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9078                         DRM_ERROR("Switching back to LCPLL failed\n");
9079         }
9080
9081         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9082
9083         intel_update_cdclk(dev_priv);
9084         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9085 }
9086
9087 /*
9088  * Package states C8 and deeper are really deep PC states that can only be
9089  * reached when all the devices on the system allow it, so even if the graphics
9090  * device allows PC8+, it doesn't mean the system will actually get to these
9091  * states. Our driver only allows PC8+ when going into runtime PM.
9092  *
9093  * The requirements for PC8+ are that all the outputs are disabled, the power
9094  * well is disabled and most interrupts are disabled, and these are also
9095  * requirements for runtime PM. When these conditions are met, we manually do
9096  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9097  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9098  * hang the machine.
9099  *
9100  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9101  * the state of some registers, so when we come back from PC8+ we need to
9102  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9103  * need to take care of the registers kept by RC6. Notice that this happens even
9104  * if we don't put the device in PCI D3 state (which is what currently happens
9105  * because of the runtime PM support).
9106  *
9107  * For more, read "Display Sequences for Package C8" on the hardware
9108  * documentation.
9109  */
9110 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9111 {
9112         uint32_t val;
9113
9114         DRM_DEBUG_KMS("Enabling package C8+\n");
9115
9116         if (HAS_PCH_LPT_LP(dev_priv)) {
9117                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9118                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9119                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9120         }
9121
9122         lpt_disable_clkout_dp(dev_priv);
9123         hsw_disable_lcpll(dev_priv, true, true);
9124 }
9125
9126 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9127 {
9128         uint32_t val;
9129
9130         DRM_DEBUG_KMS("Disabling package C8+\n");
9131
9132         hsw_restore_lcpll(dev_priv);
9133         lpt_init_pch_refclk(dev_priv);
9134
9135         if (HAS_PCH_LPT_LP(dev_priv)) {
9136                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9137                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9138                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9139         }
9140 }
9141
9142 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9143                                       struct intel_crtc_state *crtc_state)
9144 {
9145         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9146                 struct intel_encoder *encoder =
9147                         intel_ddi_get_crtc_new_encoder(crtc_state);
9148
9149                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9150                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9151                                          pipe_name(crtc->pipe));
9152                         return -EINVAL;
9153                 }
9154         }
9155
9156         return 0;
9157 }
9158
9159 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9160                                    enum port port,
9161                                    struct intel_crtc_state *pipe_config)
9162 {
9163         enum intel_dpll_id id;
9164         u32 temp;
9165
9166         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9167         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9168
9169         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9170                 return;
9171
9172         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9173 }
9174
9175 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9176                                 enum port port,
9177                                 struct intel_crtc_state *pipe_config)
9178 {
9179         enum intel_dpll_id id;
9180
9181         switch (port) {
9182         case PORT_A:
9183                 id = DPLL_ID_SKL_DPLL0;
9184                 break;
9185         case PORT_B:
9186                 id = DPLL_ID_SKL_DPLL1;
9187                 break;
9188         case PORT_C:
9189                 id = DPLL_ID_SKL_DPLL2;
9190                 break;
9191         default:
9192                 DRM_ERROR("Incorrect port type\n");
9193                 return;
9194         }
9195
9196         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9197 }
9198
9199 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9200                                 enum port port,
9201                                 struct intel_crtc_state *pipe_config)
9202 {
9203         enum intel_dpll_id id;
9204         u32 temp;
9205
9206         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9207         id = temp >> (port * 3 + 1);
9208
9209         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9210                 return;
9211
9212         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9213 }
9214
9215 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9216                                 enum port port,
9217                                 struct intel_crtc_state *pipe_config)
9218 {
9219         enum intel_dpll_id id;
9220         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9221
9222         switch (ddi_pll_sel) {
9223         case PORT_CLK_SEL_WRPLL1:
9224                 id = DPLL_ID_WRPLL1;
9225                 break;
9226         case PORT_CLK_SEL_WRPLL2:
9227                 id = DPLL_ID_WRPLL2;
9228                 break;
9229         case PORT_CLK_SEL_SPLL:
9230                 id = DPLL_ID_SPLL;
9231                 break;
9232         case PORT_CLK_SEL_LCPLL_810:
9233                 id = DPLL_ID_LCPLL_810;
9234                 break;
9235         case PORT_CLK_SEL_LCPLL_1350:
9236                 id = DPLL_ID_LCPLL_1350;
9237                 break;
9238         case PORT_CLK_SEL_LCPLL_2700:
9239                 id = DPLL_ID_LCPLL_2700;
9240                 break;
9241         default:
9242                 MISSING_CASE(ddi_pll_sel);
9243                 /* fall through */
9244         case PORT_CLK_SEL_NONE:
9245                 return;
9246         }
9247
9248         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9249 }
9250
9251 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9252                                      struct intel_crtc_state *pipe_config,
9253                                      u64 *power_domain_mask)
9254 {
9255         struct drm_device *dev = crtc->base.dev;
9256         struct drm_i915_private *dev_priv = to_i915(dev);
9257         enum intel_display_power_domain power_domain;
9258         u32 tmp;
9259
9260         /*
9261          * The pipe->transcoder mapping is fixed with the exception of the eDP
9262          * transcoder handled below.
9263          */
9264         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9265
9266         /*
9267          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9268          * consistency and less surprising code; it's in always on power).
9269          */
9270         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9271         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9272                 enum pipe trans_edp_pipe;
9273                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9274                 default:
9275                         WARN(1, "unknown pipe linked to edp transcoder\n");
9276                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9277                 case TRANS_DDI_EDP_INPUT_A_ON:
9278                         trans_edp_pipe = PIPE_A;
9279                         break;
9280                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9281                         trans_edp_pipe = PIPE_B;
9282                         break;
9283                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9284                         trans_edp_pipe = PIPE_C;
9285                         break;
9286                 }
9287
9288                 if (trans_edp_pipe == crtc->pipe)
9289                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9290         }
9291
9292         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9293         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9294                 return false;
9295         *power_domain_mask |= BIT_ULL(power_domain);
9296
9297         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9298
9299         return tmp & PIPECONF_ENABLE;
9300 }
9301
9302 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9303                                          struct intel_crtc_state *pipe_config,
9304                                          u64 *power_domain_mask)
9305 {
9306         struct drm_device *dev = crtc->base.dev;
9307         struct drm_i915_private *dev_priv = to_i915(dev);
9308         enum intel_display_power_domain power_domain;
9309         enum port port;
9310         enum transcoder cpu_transcoder;
9311         u32 tmp;
9312
9313         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9314                 if (port == PORT_A)
9315                         cpu_transcoder = TRANSCODER_DSI_A;
9316                 else
9317                         cpu_transcoder = TRANSCODER_DSI_C;
9318
9319                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9320                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9321                         continue;
9322                 *power_domain_mask |= BIT_ULL(power_domain);
9323
9324                 /*
9325                  * The PLL needs to be enabled with a valid divider
9326                  * configuration, otherwise accessing DSI registers will hang
9327                  * the machine. See BSpec North Display Engine
9328                  * registers/MIPI[BXT]. We can break out here early, since we
9329                  * need the same DSI PLL to be enabled for both DSI ports.
9330                  */
9331                 if (!intel_dsi_pll_is_enabled(dev_priv))
9332                         break;
9333
9334                 /* XXX: this works for video mode only */
9335                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9336                 if (!(tmp & DPI_ENABLE))
9337                         continue;
9338
9339                 tmp = I915_READ(MIPI_CTRL(port));
9340                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9341                         continue;
9342
9343                 pipe_config->cpu_transcoder = cpu_transcoder;
9344                 break;
9345         }
9346
9347         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9348 }
9349
9350 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9351                                        struct intel_crtc_state *pipe_config)
9352 {
9353         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9354         struct intel_shared_dpll *pll;
9355         enum port port;
9356         uint32_t tmp;
9357
9358         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9359
9360         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9361
9362         if (IS_CANNONLAKE(dev_priv))
9363                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9364         else if (IS_GEN9_BC(dev_priv))
9365                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9366         else if (IS_GEN9_LP(dev_priv))
9367                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9368         else
9369                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9370
9371         pll = pipe_config->shared_dpll;
9372         if (pll) {
9373                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9374                                                 &pipe_config->dpll_hw_state));
9375         }
9376
9377         /*
9378          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9379          * DDI E. So just check whether this pipe is wired to DDI E and whether
9380          * the PCH transcoder is on.
9381          */
9382         if (INTEL_GEN(dev_priv) < 9 &&
9383             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9384                 pipe_config->has_pch_encoder = true;
9385
9386                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9387                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9388                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9389
9390                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9391         }
9392 }
9393
9394 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9395                                     struct intel_crtc_state *pipe_config)
9396 {
9397         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9398         enum intel_display_power_domain power_domain;
9399         u64 power_domain_mask;
9400         bool active;
9401
9402         intel_crtc_init_scalers(crtc, pipe_config);
9403
9404         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9405         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9406                 return false;
9407         power_domain_mask = BIT_ULL(power_domain);
9408
9409         pipe_config->shared_dpll = NULL;
9410
9411         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9412
9413         if (IS_GEN9_LP(dev_priv) &&
9414             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9415                 WARN_ON(active);
9416                 active = true;
9417         }
9418
9419         if (!active)
9420                 goto out;
9421
9422         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9423                 haswell_get_ddi_port_state(crtc, pipe_config);
9424                 intel_get_pipe_timings(crtc, pipe_config);
9425         }
9426
9427         intel_get_pipe_src_size(crtc, pipe_config);
9428
9429         pipe_config->gamma_mode =
9430                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9431
9432         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9433                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9434                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9435
9436                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9437                         bool blend_mode_420 = tmp &
9438                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9439
9440                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9441                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9442                             pipe_config->ycbcr420 != blend_mode_420)
9443                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9444                 } else if (clrspace_yuv) {
9445                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9446                 }
9447         }
9448
9449         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9450         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9451                 power_domain_mask |= BIT_ULL(power_domain);
9452                 if (INTEL_GEN(dev_priv) >= 9)
9453                         skylake_get_pfit_config(crtc, pipe_config);
9454                 else
9455                         ironlake_get_pfit_config(crtc, pipe_config);
9456         }
9457
9458         if (hsw_crtc_supports_ips(crtc)) {
9459                 if (IS_HASWELL(dev_priv))
9460                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9461                 else {
9462                         /*
9463                          * We cannot readout IPS state on broadwell, set to
9464                          * true so we can set it to a defined state on first
9465                          * commit.
9466                          */
9467                         pipe_config->ips_enabled = true;
9468                 }
9469         }
9470
9471         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9472             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9473                 pipe_config->pixel_multiplier =
9474                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9475         } else {
9476                 pipe_config->pixel_multiplier = 1;
9477         }
9478
9479 out:
9480         for_each_power_domain(power_domain, power_domain_mask)
9481                 intel_display_power_put(dev_priv, power_domain);
9482
9483         return active;
9484 }
9485
9486 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9487 {
9488         struct drm_i915_private *dev_priv =
9489                 to_i915(plane_state->base.plane->dev);
9490         const struct drm_framebuffer *fb = plane_state->base.fb;
9491         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9492         u32 base;
9493
9494         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9495                 base = obj->phys_handle->busaddr;
9496         else
9497                 base = intel_plane_ggtt_offset(plane_state);
9498
9499         base += plane_state->main.offset;
9500
9501         /* ILK+ do this automagically */
9502         if (HAS_GMCH_DISPLAY(dev_priv) &&
9503             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9504                 base += (plane_state->base.crtc_h *
9505                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9506
9507         return base;
9508 }
9509
9510 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9511 {
9512         int x = plane_state->base.crtc_x;
9513         int y = plane_state->base.crtc_y;
9514         u32 pos = 0;
9515
9516         if (x < 0) {
9517                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9518                 x = -x;
9519         }
9520         pos |= x << CURSOR_X_SHIFT;
9521
9522         if (y < 0) {
9523                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9524                 y = -y;
9525         }
9526         pos |= y << CURSOR_Y_SHIFT;
9527
9528         return pos;
9529 }
9530
9531 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9532 {
9533         const struct drm_mode_config *config =
9534                 &plane_state->base.plane->dev->mode_config;
9535         int width = plane_state->base.crtc_w;
9536         int height = plane_state->base.crtc_h;
9537
9538         return width > 0 && width <= config->cursor_width &&
9539                 height > 0 && height <= config->cursor_height;
9540 }
9541
9542 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9543                               struct intel_plane_state *plane_state)
9544 {
9545         const struct drm_framebuffer *fb = plane_state->base.fb;
9546         int src_x, src_y;
9547         u32 offset;
9548         int ret;
9549
9550         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9551                                                   &crtc_state->base,
9552                                                   DRM_PLANE_HELPER_NO_SCALING,
9553                                                   DRM_PLANE_HELPER_NO_SCALING,
9554                                                   true, true);
9555         if (ret)
9556                 return ret;
9557
9558         if (!fb)
9559                 return 0;
9560
9561         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9562                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9563                 return -EINVAL;
9564         }
9565
9566         src_x = plane_state->base.src_x >> 16;
9567         src_y = plane_state->base.src_y >> 16;
9568
9569         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9570         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9571
9572         if (src_x != 0 || src_y != 0) {
9573                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9574                 return -EINVAL;
9575         }
9576
9577         plane_state->main.offset = offset;
9578
9579         return 0;
9580 }
9581
9582 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9583                            const struct intel_plane_state *plane_state)
9584 {
9585         const struct drm_framebuffer *fb = plane_state->base.fb;
9586
9587         return CURSOR_ENABLE |
9588                 CURSOR_GAMMA_ENABLE |
9589                 CURSOR_FORMAT_ARGB |
9590                 CURSOR_STRIDE(fb->pitches[0]);
9591 }
9592
9593 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9594 {
9595         int width = plane_state->base.crtc_w;
9596
9597         /*
9598          * 845g/865g are only limited by the width of their cursors,
9599          * the height is arbitrary up to the precision of the register.
9600          */
9601         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9602 }
9603
9604 static int i845_check_cursor(struct intel_plane *plane,
9605                              struct intel_crtc_state *crtc_state,
9606                              struct intel_plane_state *plane_state)
9607 {
9608         const struct drm_framebuffer *fb = plane_state->base.fb;
9609         int ret;
9610
9611         ret = intel_check_cursor(crtc_state, plane_state);
9612         if (ret)
9613                 return ret;
9614
9615         /* if we want to turn off the cursor ignore width and height */
9616         if (!fb)
9617                 return 0;
9618
9619         /* Check for which cursor types we support */
9620         if (!i845_cursor_size_ok(plane_state)) {
9621                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9622                           plane_state->base.crtc_w,
9623                           plane_state->base.crtc_h);
9624                 return -EINVAL;
9625         }
9626
9627         switch (fb->pitches[0]) {
9628         case 256:
9629         case 512:
9630         case 1024:
9631         case 2048:
9632                 break;
9633         default:
9634                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9635                               fb->pitches[0]);
9636                 return -EINVAL;
9637         }
9638
9639         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9640
9641         return 0;
9642 }
9643
9644 static void i845_update_cursor(struct intel_plane *plane,
9645                                const struct intel_crtc_state *crtc_state,
9646                                const struct intel_plane_state *plane_state)
9647 {
9648         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9649         u32 cntl = 0, base = 0, pos = 0, size = 0;
9650         unsigned long irqflags;
9651
9652         if (plane_state && plane_state->base.visible) {
9653                 unsigned int width = plane_state->base.crtc_w;
9654                 unsigned int height = plane_state->base.crtc_h;
9655
9656                 cntl = plane_state->ctl;
9657                 size = (height << 12) | width;
9658
9659                 base = intel_cursor_base(plane_state);
9660                 pos = intel_cursor_position(plane_state);
9661         }
9662
9663         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9664
9665         /* On these chipsets we can only modify the base/size/stride
9666          * whilst the cursor is disabled.
9667          */
9668         if (plane->cursor.base != base ||
9669             plane->cursor.size != size ||
9670             plane->cursor.cntl != cntl) {
9671                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9672                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9673                 I915_WRITE_FW(CURSIZE, size);
9674                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9675                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9676
9677                 plane->cursor.base = base;
9678                 plane->cursor.size = size;
9679                 plane->cursor.cntl = cntl;
9680         } else {
9681                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9682         }
9683
9684         POSTING_READ_FW(CURCNTR(PIPE_A));
9685
9686         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9687 }
9688
9689 static void i845_disable_cursor(struct intel_plane *plane,
9690                                 struct intel_crtc *crtc)
9691 {
9692         i845_update_cursor(plane, NULL, NULL);
9693 }
9694
9695 static bool i845_cursor_get_hw_state(struct intel_plane *plane)
9696 {
9697         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9698         enum intel_display_power_domain power_domain;
9699         bool ret;
9700
9701         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9702         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9703                 return false;
9704
9705         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9706
9707         intel_display_power_put(dev_priv, power_domain);
9708
9709         return ret;
9710 }
9711
9712 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9713                            const struct intel_plane_state *plane_state)
9714 {
9715         struct drm_i915_private *dev_priv =
9716                 to_i915(plane_state->base.plane->dev);
9717         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9718         u32 cntl;
9719
9720         cntl = MCURSOR_GAMMA_ENABLE;
9721
9722         if (HAS_DDI(dev_priv))
9723                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9724
9725         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9726                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9727
9728         switch (plane_state->base.crtc_w) {
9729         case 64:
9730                 cntl |= CURSOR_MODE_64_ARGB_AX;
9731                 break;
9732         case 128:
9733                 cntl |= CURSOR_MODE_128_ARGB_AX;
9734                 break;
9735         case 256:
9736                 cntl |= CURSOR_MODE_256_ARGB_AX;
9737                 break;
9738         default:
9739                 MISSING_CASE(plane_state->base.crtc_w);
9740                 return 0;
9741         }
9742
9743         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9744                 cntl |= CURSOR_ROTATE_180;
9745
9746         return cntl;
9747 }
9748
9749 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9750 {
9751         struct drm_i915_private *dev_priv =
9752                 to_i915(plane_state->base.plane->dev);
9753         int width = plane_state->base.crtc_w;
9754         int height = plane_state->base.crtc_h;
9755
9756         if (!intel_cursor_size_ok(plane_state))
9757                 return false;
9758
9759         /* Cursor width is limited to a few power-of-two sizes */
9760         switch (width) {
9761         case 256:
9762         case 128:
9763         case 64:
9764                 break;
9765         default:
9766                 return false;
9767         }
9768
9769         /*
9770          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9771          * height from 8 lines up to the cursor width, when the
9772          * cursor is not rotated. Everything else requires square
9773          * cursors.
9774          */
9775         if (HAS_CUR_FBC(dev_priv) &&
9776             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9777                 if (height < 8 || height > width)
9778                         return false;
9779         } else {
9780                 if (height != width)
9781                         return false;
9782         }
9783
9784         return true;
9785 }
9786
9787 static int i9xx_check_cursor(struct intel_plane *plane,
9788                              struct intel_crtc_state *crtc_state,
9789                              struct intel_plane_state *plane_state)
9790 {
9791         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9792         const struct drm_framebuffer *fb = plane_state->base.fb;
9793         enum pipe pipe = plane->pipe;
9794         int ret;
9795
9796         ret = intel_check_cursor(crtc_state, plane_state);
9797         if (ret)
9798                 return ret;
9799
9800         /* if we want to turn off the cursor ignore width and height */
9801         if (!fb)
9802                 return 0;
9803
9804         /* Check for which cursor types we support */
9805         if (!i9xx_cursor_size_ok(plane_state)) {
9806                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9807                           plane_state->base.crtc_w,
9808                           plane_state->base.crtc_h);
9809                 return -EINVAL;
9810         }
9811
9812         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9813                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9814                               fb->pitches[0], plane_state->base.crtc_w);
9815                 return -EINVAL;
9816         }
9817
9818         /*
9819          * There's something wrong with the cursor on CHV pipe C.
9820          * If it straddles the left edge of the screen then
9821          * moving it away from the edge or disabling it often
9822          * results in a pipe underrun, and often that can lead to
9823          * dead pipe (constant underrun reported, and it scans
9824          * out just a solid color). To recover from that, the
9825          * display power well must be turned off and on again.
9826          * Refuse the put the cursor into that compromised position.
9827          */
9828         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9829             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9830                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9831                 return -EINVAL;
9832         }
9833
9834         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9835
9836         return 0;
9837 }
9838
9839 static void i9xx_update_cursor(struct intel_plane *plane,
9840                                const struct intel_crtc_state *crtc_state,
9841                                const struct intel_plane_state *plane_state)
9842 {
9843         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9844         enum pipe pipe = plane->pipe;
9845         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9846         unsigned long irqflags;
9847
9848         if (plane_state && plane_state->base.visible) {
9849                 cntl = plane_state->ctl;
9850
9851                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9852                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9853
9854                 base = intel_cursor_base(plane_state);
9855                 pos = intel_cursor_position(plane_state);
9856         }
9857
9858         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9859
9860         /*
9861          * On some platforms writing CURCNTR first will also
9862          * cause CURPOS to be armed by the CURBASE write.
9863          * Without the CURCNTR write the CURPOS write would
9864          * arm itself. Thus we always start the full update
9865          * with a CURCNTR write.
9866          *
9867          * On other platforms CURPOS always requires the
9868          * CURBASE write to arm the update. Additonally
9869          * a write to any of the cursor register will cancel
9870          * an already armed cursor update. Thus leaving out
9871          * the CURBASE write after CURPOS could lead to a
9872          * cursor that doesn't appear to move, or even change
9873          * shape. Thus we always write CURBASE.
9874          *
9875          * CURCNTR and CUR_FBC_CTL are always
9876          * armed by the CURBASE write only.
9877          */
9878         if (plane->cursor.base != base ||
9879             plane->cursor.size != fbc_ctl ||
9880             plane->cursor.cntl != cntl) {
9881                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9882                 if (HAS_CUR_FBC(dev_priv))
9883                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9884                 I915_WRITE_FW(CURPOS(pipe), pos);
9885                 I915_WRITE_FW(CURBASE(pipe), base);
9886
9887                 plane->cursor.base = base;
9888                 plane->cursor.size = fbc_ctl;
9889                 plane->cursor.cntl = cntl;
9890         } else {
9891                 I915_WRITE_FW(CURPOS(pipe), pos);
9892                 I915_WRITE_FW(CURBASE(pipe), base);
9893         }
9894
9895         POSTING_READ_FW(CURBASE(pipe));
9896
9897         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9898 }
9899
9900 static void i9xx_disable_cursor(struct intel_plane *plane,
9901                                 struct intel_crtc *crtc)
9902 {
9903         i9xx_update_cursor(plane, NULL, NULL);
9904 }
9905
9906 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane)
9907 {
9908         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9909         enum intel_display_power_domain power_domain;
9910         enum pipe pipe = plane->pipe;
9911         bool ret;
9912
9913         /*
9914          * Not 100% correct for planes that can move between pipes,
9915          * but that's only the case for gen2-3 which don't have any
9916          * display power wells.
9917          */
9918         power_domain = POWER_DOMAIN_PIPE(pipe);
9919         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9920                 return false;
9921
9922         ret = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
9923
9924         intel_display_power_put(dev_priv, power_domain);
9925
9926         return ret;
9927 }
9928
9929 /* VESA 640x480x72Hz mode to set on the pipe */
9930 static const struct drm_display_mode load_detect_mode = {
9931         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9932                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9933 };
9934
9935 struct drm_framebuffer *
9936 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9937                          struct drm_mode_fb_cmd2 *mode_cmd)
9938 {
9939         struct intel_framebuffer *intel_fb;
9940         int ret;
9941
9942         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9943         if (!intel_fb)
9944                 return ERR_PTR(-ENOMEM);
9945
9946         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9947         if (ret)
9948                 goto err;
9949
9950         return &intel_fb->base;
9951
9952 err:
9953         kfree(intel_fb);
9954         return ERR_PTR(ret);
9955 }
9956
9957 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
9958                                         struct drm_crtc *crtc)
9959 {
9960         struct drm_plane *plane;
9961         struct drm_plane_state *plane_state;
9962         int ret, i;
9963
9964         ret = drm_atomic_add_affected_planes(state, crtc);
9965         if (ret)
9966                 return ret;
9967
9968         for_each_new_plane_in_state(state, plane, plane_state, i) {
9969                 if (plane_state->crtc != crtc)
9970                         continue;
9971
9972                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
9973                 if (ret)
9974                         return ret;
9975
9976                 drm_atomic_set_fb_for_plane(plane_state, NULL);
9977         }
9978
9979         return 0;
9980 }
9981
9982 int intel_get_load_detect_pipe(struct drm_connector *connector,
9983                                const struct drm_display_mode *mode,
9984                                struct intel_load_detect_pipe *old,
9985                                struct drm_modeset_acquire_ctx *ctx)
9986 {
9987         struct intel_crtc *intel_crtc;
9988         struct intel_encoder *intel_encoder =
9989                 intel_attached_encoder(connector);
9990         struct drm_crtc *possible_crtc;
9991         struct drm_encoder *encoder = &intel_encoder->base;
9992         struct drm_crtc *crtc = NULL;
9993         struct drm_device *dev = encoder->dev;
9994         struct drm_i915_private *dev_priv = to_i915(dev);
9995         struct drm_mode_config *config = &dev->mode_config;
9996         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9997         struct drm_connector_state *connector_state;
9998         struct intel_crtc_state *crtc_state;
9999         int ret, i = -1;
10000
10001         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10002                       connector->base.id, connector->name,
10003                       encoder->base.id, encoder->name);
10004
10005         old->restore_state = NULL;
10006
10007         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10008
10009         /*
10010          * Algorithm gets a little messy:
10011          *
10012          *   - if the connector already has an assigned crtc, use it (but make
10013          *     sure it's on first)
10014          *
10015          *   - try to find the first unused crtc that can drive this connector,
10016          *     and use that if we find one
10017          */
10018
10019         /* See if we already have a CRTC for this connector */
10020         if (connector->state->crtc) {
10021                 crtc = connector->state->crtc;
10022
10023                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10024                 if (ret)
10025                         goto fail;
10026
10027                 /* Make sure the crtc and connector are running */
10028                 goto found;
10029         }
10030
10031         /* Find an unused one (if possible) */
10032         for_each_crtc(dev, possible_crtc) {
10033                 i++;
10034                 if (!(encoder->possible_crtcs & (1 << i)))
10035                         continue;
10036
10037                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10038                 if (ret)
10039                         goto fail;
10040
10041                 if (possible_crtc->state->enable) {
10042                         drm_modeset_unlock(&possible_crtc->mutex);
10043                         continue;
10044                 }
10045
10046                 crtc = possible_crtc;
10047                 break;
10048         }
10049
10050         /*
10051          * If we didn't find an unused CRTC, don't use any.
10052          */
10053         if (!crtc) {
10054                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10055                 ret = -ENODEV;
10056                 goto fail;
10057         }
10058
10059 found:
10060         intel_crtc = to_intel_crtc(crtc);
10061
10062         state = drm_atomic_state_alloc(dev);
10063         restore_state = drm_atomic_state_alloc(dev);
10064         if (!state || !restore_state) {
10065                 ret = -ENOMEM;
10066                 goto fail;
10067         }
10068
10069         state->acquire_ctx = ctx;
10070         restore_state->acquire_ctx = ctx;
10071
10072         connector_state = drm_atomic_get_connector_state(state, connector);
10073         if (IS_ERR(connector_state)) {
10074                 ret = PTR_ERR(connector_state);
10075                 goto fail;
10076         }
10077
10078         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10079         if (ret)
10080                 goto fail;
10081
10082         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10083         if (IS_ERR(crtc_state)) {
10084                 ret = PTR_ERR(crtc_state);
10085                 goto fail;
10086         }
10087
10088         crtc_state->base.active = crtc_state->base.enable = true;
10089
10090         if (!mode)
10091                 mode = &load_detect_mode;
10092
10093         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10094         if (ret)
10095                 goto fail;
10096
10097         ret = intel_modeset_disable_planes(state, crtc);
10098         if (ret)
10099                 goto fail;
10100
10101         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10102         if (!ret)
10103                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10104         if (!ret)
10105                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10106         if (ret) {
10107                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10108                 goto fail;
10109         }
10110
10111         ret = drm_atomic_commit(state);
10112         if (ret) {
10113                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10114                 goto fail;
10115         }
10116
10117         old->restore_state = restore_state;
10118         drm_atomic_state_put(state);
10119
10120         /* let the connector get through one full cycle before testing */
10121         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10122         return true;
10123
10124 fail:
10125         if (state) {
10126                 drm_atomic_state_put(state);
10127                 state = NULL;
10128         }
10129         if (restore_state) {
10130                 drm_atomic_state_put(restore_state);
10131                 restore_state = NULL;
10132         }
10133
10134         if (ret == -EDEADLK)
10135                 return ret;
10136
10137         return false;
10138 }
10139
10140 void intel_release_load_detect_pipe(struct drm_connector *connector,
10141                                     struct intel_load_detect_pipe *old,
10142                                     struct drm_modeset_acquire_ctx *ctx)
10143 {
10144         struct intel_encoder *intel_encoder =
10145                 intel_attached_encoder(connector);
10146         struct drm_encoder *encoder = &intel_encoder->base;
10147         struct drm_atomic_state *state = old->restore_state;
10148         int ret;
10149
10150         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10151                       connector->base.id, connector->name,
10152                       encoder->base.id, encoder->name);
10153
10154         if (!state)
10155                 return;
10156
10157         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10158         if (ret)
10159                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10160         drm_atomic_state_put(state);
10161 }
10162
10163 static int i9xx_pll_refclk(struct drm_device *dev,
10164                            const struct intel_crtc_state *pipe_config)
10165 {
10166         struct drm_i915_private *dev_priv = to_i915(dev);
10167         u32 dpll = pipe_config->dpll_hw_state.dpll;
10168
10169         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10170                 return dev_priv->vbt.lvds_ssc_freq;
10171         else if (HAS_PCH_SPLIT(dev_priv))
10172                 return 120000;
10173         else if (!IS_GEN2(dev_priv))
10174                 return 96000;
10175         else
10176                 return 48000;
10177 }
10178
10179 /* Returns the clock of the currently programmed mode of the given pipe. */
10180 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10181                                 struct intel_crtc_state *pipe_config)
10182 {
10183         struct drm_device *dev = crtc->base.dev;
10184         struct drm_i915_private *dev_priv = to_i915(dev);
10185         int pipe = pipe_config->cpu_transcoder;
10186         u32 dpll = pipe_config->dpll_hw_state.dpll;
10187         u32 fp;
10188         struct dpll clock;
10189         int port_clock;
10190         int refclk = i9xx_pll_refclk(dev, pipe_config);
10191
10192         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10193                 fp = pipe_config->dpll_hw_state.fp0;
10194         else
10195                 fp = pipe_config->dpll_hw_state.fp1;
10196
10197         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10198         if (IS_PINEVIEW(dev_priv)) {
10199                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10200                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10201         } else {
10202                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10203                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10204         }
10205
10206         if (!IS_GEN2(dev_priv)) {
10207                 if (IS_PINEVIEW(dev_priv))
10208                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10209                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10210                 else
10211                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10212                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10213
10214                 switch (dpll & DPLL_MODE_MASK) {
10215                 case DPLLB_MODE_DAC_SERIAL:
10216                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10217                                 5 : 10;
10218                         break;
10219                 case DPLLB_MODE_LVDS:
10220                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10221                                 7 : 14;
10222                         break;
10223                 default:
10224                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10225                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10226                         return;
10227                 }
10228
10229                 if (IS_PINEVIEW(dev_priv))
10230                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10231                 else
10232                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10233         } else {
10234                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10235                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10236
10237                 if (is_lvds) {
10238                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10239                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10240
10241                         if (lvds & LVDS_CLKB_POWER_UP)
10242                                 clock.p2 = 7;
10243                         else
10244                                 clock.p2 = 14;
10245                 } else {
10246                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10247                                 clock.p1 = 2;
10248                         else {
10249                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10250                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10251                         }
10252                         if (dpll & PLL_P2_DIVIDE_BY_4)
10253                                 clock.p2 = 4;
10254                         else
10255                                 clock.p2 = 2;
10256                 }
10257
10258                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10259         }
10260
10261         /*
10262          * This value includes pixel_multiplier. We will use
10263          * port_clock to compute adjusted_mode.crtc_clock in the
10264          * encoder's get_config() function.
10265          */
10266         pipe_config->port_clock = port_clock;
10267 }
10268
10269 int intel_dotclock_calculate(int link_freq,
10270                              const struct intel_link_m_n *m_n)
10271 {
10272         /*
10273          * The calculation for the data clock is:
10274          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10275          * But we want to avoid losing precison if possible, so:
10276          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10277          *
10278          * and the link clock is simpler:
10279          * link_clock = (m * link_clock) / n
10280          */
10281
10282         if (!m_n->link_n)
10283                 return 0;
10284
10285         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10286 }
10287
10288 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10289                                    struct intel_crtc_state *pipe_config)
10290 {
10291         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10292
10293         /* read out port_clock from the DPLL */
10294         i9xx_crtc_clock_get(crtc, pipe_config);
10295
10296         /*
10297          * In case there is an active pipe without active ports,
10298          * we may need some idea for the dotclock anyway.
10299          * Calculate one based on the FDI configuration.
10300          */
10301         pipe_config->base.adjusted_mode.crtc_clock =
10302                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10303                                          &pipe_config->fdi_m_n);
10304 }
10305
10306 /* Returns the currently programmed mode of the given encoder. */
10307 struct drm_display_mode *
10308 intel_encoder_current_mode(struct intel_encoder *encoder)
10309 {
10310         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10311         struct intel_crtc_state *crtc_state;
10312         struct drm_display_mode *mode;
10313         struct intel_crtc *crtc;
10314         enum pipe pipe;
10315
10316         if (!encoder->get_hw_state(encoder, &pipe))
10317                 return NULL;
10318
10319         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10320
10321         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10322         if (!mode)
10323                 return NULL;
10324
10325         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10326         if (!crtc_state) {
10327                 kfree(mode);
10328                 return NULL;
10329         }
10330
10331         crtc_state->base.crtc = &crtc->base;
10332
10333         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10334                 kfree(crtc_state);
10335                 kfree(mode);
10336                 return NULL;
10337         }
10338
10339         encoder->get_config(encoder, crtc_state);
10340
10341         intel_mode_from_pipe_config(mode, crtc_state);
10342
10343         kfree(crtc_state);
10344
10345         return mode;
10346 }
10347
10348 static void intel_crtc_destroy(struct drm_crtc *crtc)
10349 {
10350         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10351
10352         drm_crtc_cleanup(crtc);
10353         kfree(intel_crtc);
10354 }
10355
10356 /**
10357  * intel_wm_need_update - Check whether watermarks need updating
10358  * @plane: drm plane
10359  * @state: new plane state
10360  *
10361  * Check current plane state versus the new one to determine whether
10362  * watermarks need to be recalculated.
10363  *
10364  * Returns true or false.
10365  */
10366 static bool intel_wm_need_update(struct drm_plane *plane,
10367                                  struct drm_plane_state *state)
10368 {
10369         struct intel_plane_state *new = to_intel_plane_state(state);
10370         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10371
10372         /* Update watermarks on tiling or size changes. */
10373         if (new->base.visible != cur->base.visible)
10374                 return true;
10375
10376         if (!cur->base.fb || !new->base.fb)
10377                 return false;
10378
10379         if (cur->base.fb->modifier != new->base.fb->modifier ||
10380             cur->base.rotation != new->base.rotation ||
10381             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10382             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10383             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10384             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10385                 return true;
10386
10387         return false;
10388 }
10389
10390 static bool needs_scaling(const struct intel_plane_state *state)
10391 {
10392         int src_w = drm_rect_width(&state->base.src) >> 16;
10393         int src_h = drm_rect_height(&state->base.src) >> 16;
10394         int dst_w = drm_rect_width(&state->base.dst);
10395         int dst_h = drm_rect_height(&state->base.dst);
10396
10397         return (src_w != dst_w || src_h != dst_h);
10398 }
10399
10400 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10401                                     struct drm_crtc_state *crtc_state,
10402                                     const struct intel_plane_state *old_plane_state,
10403                                     struct drm_plane_state *plane_state)
10404 {
10405         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10406         struct drm_crtc *crtc = crtc_state->crtc;
10407         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10408         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10409         struct drm_device *dev = crtc->dev;
10410         struct drm_i915_private *dev_priv = to_i915(dev);
10411         bool mode_changed = needs_modeset(crtc_state);
10412         bool was_crtc_enabled = old_crtc_state->base.active;
10413         bool is_crtc_enabled = crtc_state->active;
10414         bool turn_off, turn_on, visible, was_visible;
10415         struct drm_framebuffer *fb = plane_state->fb;
10416         int ret;
10417
10418         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10419                 ret = skl_update_scaler_plane(
10420                         to_intel_crtc_state(crtc_state),
10421                         to_intel_plane_state(plane_state));
10422                 if (ret)
10423                         return ret;
10424         }
10425
10426         was_visible = old_plane_state->base.visible;
10427         visible = plane_state->visible;
10428
10429         if (!was_crtc_enabled && WARN_ON(was_visible))
10430                 was_visible = false;
10431
10432         /*
10433          * Visibility is calculated as if the crtc was on, but
10434          * after scaler setup everything depends on it being off
10435          * when the crtc isn't active.
10436          *
10437          * FIXME this is wrong for watermarks. Watermarks should also
10438          * be computed as if the pipe would be active. Perhaps move
10439          * per-plane wm computation to the .check_plane() hook, and
10440          * only combine the results from all planes in the current place?
10441          */
10442         if (!is_crtc_enabled) {
10443                 plane_state->visible = visible = false;
10444                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10445         }
10446
10447         if (!was_visible && !visible)
10448                 return 0;
10449
10450         if (fb != old_plane_state->base.fb)
10451                 pipe_config->fb_changed = true;
10452
10453         turn_off = was_visible && (!visible || mode_changed);
10454         turn_on = visible && (!was_visible || mode_changed);
10455
10456         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10457                          intel_crtc->base.base.id, intel_crtc->base.name,
10458                          plane->base.base.id, plane->base.name,
10459                          fb ? fb->base.id : -1);
10460
10461         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10462                          plane->base.base.id, plane->base.name,
10463                          was_visible, visible,
10464                          turn_off, turn_on, mode_changed);
10465
10466         if (turn_on) {
10467                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10468                         pipe_config->update_wm_pre = true;
10469
10470                 /* must disable cxsr around plane enable/disable */
10471                 if (plane->id != PLANE_CURSOR)
10472                         pipe_config->disable_cxsr = true;
10473         } else if (turn_off) {
10474                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10475                         pipe_config->update_wm_post = true;
10476
10477                 /* must disable cxsr around plane enable/disable */
10478                 if (plane->id != PLANE_CURSOR)
10479                         pipe_config->disable_cxsr = true;
10480         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10481                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10482                         /* FIXME bollocks */
10483                         pipe_config->update_wm_pre = true;
10484                         pipe_config->update_wm_post = true;
10485                 }
10486         }
10487
10488         if (visible || was_visible)
10489                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10490
10491         /*
10492          * WaCxSRDisabledForSpriteScaling:ivb
10493          *
10494          * cstate->update_wm was already set above, so this flag will
10495          * take effect when we commit and program watermarks.
10496          */
10497         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10498             needs_scaling(to_intel_plane_state(plane_state)) &&
10499             !needs_scaling(old_plane_state))
10500                 pipe_config->disable_lp_wm = true;
10501
10502         return 0;
10503 }
10504
10505 static bool encoders_cloneable(const struct intel_encoder *a,
10506                                const struct intel_encoder *b)
10507 {
10508         /* masks could be asymmetric, so check both ways */
10509         return a == b || (a->cloneable & (1 << b->type) &&
10510                           b->cloneable & (1 << a->type));
10511 }
10512
10513 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10514                                          struct intel_crtc *crtc,
10515                                          struct intel_encoder *encoder)
10516 {
10517         struct intel_encoder *source_encoder;
10518         struct drm_connector *connector;
10519         struct drm_connector_state *connector_state;
10520         int i;
10521
10522         for_each_new_connector_in_state(state, connector, connector_state, i) {
10523                 if (connector_state->crtc != &crtc->base)
10524                         continue;
10525
10526                 source_encoder =
10527                         to_intel_encoder(connector_state->best_encoder);
10528                 if (!encoders_cloneable(encoder, source_encoder))
10529                         return false;
10530         }
10531
10532         return true;
10533 }
10534
10535 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10536                                    struct drm_crtc_state *crtc_state)
10537 {
10538         struct drm_device *dev = crtc->dev;
10539         struct drm_i915_private *dev_priv = to_i915(dev);
10540         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10541         struct intel_crtc_state *pipe_config =
10542                 to_intel_crtc_state(crtc_state);
10543         struct drm_atomic_state *state = crtc_state->state;
10544         int ret;
10545         bool mode_changed = needs_modeset(crtc_state);
10546
10547         if (mode_changed && !crtc_state->active)
10548                 pipe_config->update_wm_post = true;
10549
10550         if (mode_changed && crtc_state->enable &&
10551             dev_priv->display.crtc_compute_clock &&
10552             !WARN_ON(pipe_config->shared_dpll)) {
10553                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10554                                                            pipe_config);
10555                 if (ret)
10556                         return ret;
10557         }
10558
10559         if (crtc_state->color_mgmt_changed) {
10560                 ret = intel_color_check(crtc, crtc_state);
10561                 if (ret)
10562                         return ret;
10563
10564                 /*
10565                  * Changing color management on Intel hardware is
10566                  * handled as part of planes update.
10567                  */
10568                 crtc_state->planes_changed = true;
10569         }
10570
10571         ret = 0;
10572         if (dev_priv->display.compute_pipe_wm) {
10573                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10574                 if (ret) {
10575                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10576                         return ret;
10577                 }
10578         }
10579
10580         if (dev_priv->display.compute_intermediate_wm &&
10581             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10582                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10583                         return 0;
10584
10585                 /*
10586                  * Calculate 'intermediate' watermarks that satisfy both the
10587                  * old state and the new state.  We can program these
10588                  * immediately.
10589                  */
10590                 ret = dev_priv->display.compute_intermediate_wm(dev,
10591                                                                 intel_crtc,
10592                                                                 pipe_config);
10593                 if (ret) {
10594                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10595                         return ret;
10596                 }
10597         } else if (dev_priv->display.compute_intermediate_wm) {
10598                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10599                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10600         }
10601
10602         if (INTEL_GEN(dev_priv) >= 9) {
10603                 if (mode_changed)
10604                         ret = skl_update_scaler_crtc(pipe_config);
10605
10606                 if (!ret)
10607                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10608                                                             pipe_config);
10609                 if (!ret)
10610                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10611                                                          pipe_config);
10612         }
10613
10614         if (HAS_IPS(dev_priv))
10615                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10616
10617         return ret;
10618 }
10619
10620 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10621         .atomic_begin = intel_begin_crtc_commit,
10622         .atomic_flush = intel_finish_crtc_commit,
10623         .atomic_check = intel_crtc_atomic_check,
10624 };
10625
10626 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10627 {
10628         struct intel_connector *connector;
10629         struct drm_connector_list_iter conn_iter;
10630
10631         drm_connector_list_iter_begin(dev, &conn_iter);
10632         for_each_intel_connector_iter(connector, &conn_iter) {
10633                 if (connector->base.state->crtc)
10634                         drm_connector_unreference(&connector->base);
10635
10636                 if (connector->base.encoder) {
10637                         connector->base.state->best_encoder =
10638                                 connector->base.encoder;
10639                         connector->base.state->crtc =
10640                                 connector->base.encoder->crtc;
10641
10642                         drm_connector_reference(&connector->base);
10643                 } else {
10644                         connector->base.state->best_encoder = NULL;
10645                         connector->base.state->crtc = NULL;
10646                 }
10647         }
10648         drm_connector_list_iter_end(&conn_iter);
10649 }
10650
10651 static void
10652 connected_sink_compute_bpp(struct intel_connector *connector,
10653                            struct intel_crtc_state *pipe_config)
10654 {
10655         const struct drm_display_info *info = &connector->base.display_info;
10656         int bpp = pipe_config->pipe_bpp;
10657
10658         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10659                       connector->base.base.id,
10660                       connector->base.name);
10661
10662         /* Don't use an invalid EDID bpc value */
10663         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10664                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10665                               bpp, info->bpc * 3);
10666                 pipe_config->pipe_bpp = info->bpc * 3;
10667         }
10668
10669         /* Clamp bpp to 8 on screens without EDID 1.4 */
10670         if (info->bpc == 0 && bpp > 24) {
10671                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10672                               bpp);
10673                 pipe_config->pipe_bpp = 24;
10674         }
10675 }
10676
10677 static int
10678 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10679                           struct intel_crtc_state *pipe_config)
10680 {
10681         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10682         struct drm_atomic_state *state;
10683         struct drm_connector *connector;
10684         struct drm_connector_state *connector_state;
10685         int bpp, i;
10686
10687         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10688             IS_CHERRYVIEW(dev_priv)))
10689                 bpp = 10*3;
10690         else if (INTEL_GEN(dev_priv) >= 5)
10691                 bpp = 12*3;
10692         else
10693                 bpp = 8*3;
10694
10695
10696         pipe_config->pipe_bpp = bpp;
10697
10698         state = pipe_config->base.state;
10699
10700         /* Clamp display bpp to EDID value */
10701         for_each_new_connector_in_state(state, connector, connector_state, i) {
10702                 if (connector_state->crtc != &crtc->base)
10703                         continue;
10704
10705                 connected_sink_compute_bpp(to_intel_connector(connector),
10706                                            pipe_config);
10707         }
10708
10709         return bpp;
10710 }
10711
10712 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10713 {
10714         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10715                         "type: 0x%x flags: 0x%x\n",
10716                 mode->crtc_clock,
10717                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10718                 mode->crtc_hsync_end, mode->crtc_htotal,
10719                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10720                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10721 }
10722
10723 static inline void
10724 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10725                       unsigned int lane_count, struct intel_link_m_n *m_n)
10726 {
10727         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10728                       id, lane_count,
10729                       m_n->gmch_m, m_n->gmch_n,
10730                       m_n->link_m, m_n->link_n, m_n->tu);
10731 }
10732
10733 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10734
10735 static const char * const output_type_str[] = {
10736         OUTPUT_TYPE(UNUSED),
10737         OUTPUT_TYPE(ANALOG),
10738         OUTPUT_TYPE(DVO),
10739         OUTPUT_TYPE(SDVO),
10740         OUTPUT_TYPE(LVDS),
10741         OUTPUT_TYPE(TVOUT),
10742         OUTPUT_TYPE(HDMI),
10743         OUTPUT_TYPE(DP),
10744         OUTPUT_TYPE(EDP),
10745         OUTPUT_TYPE(DSI),
10746         OUTPUT_TYPE(DDI),
10747         OUTPUT_TYPE(DP_MST),
10748 };
10749
10750 #undef OUTPUT_TYPE
10751
10752 static void snprintf_output_types(char *buf, size_t len,
10753                                   unsigned int output_types)
10754 {
10755         char *str = buf;
10756         int i;
10757
10758         str[0] = '\0';
10759
10760         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10761                 int r;
10762
10763                 if ((output_types & BIT(i)) == 0)
10764                         continue;
10765
10766                 r = snprintf(str, len, "%s%s",
10767                              str != buf ? "," : "", output_type_str[i]);
10768                 if (r >= len)
10769                         break;
10770                 str += r;
10771                 len -= r;
10772
10773                 output_types &= ~BIT(i);
10774         }
10775
10776         WARN_ON_ONCE(output_types != 0);
10777 }
10778
10779 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10780                                    struct intel_crtc_state *pipe_config,
10781                                    const char *context)
10782 {
10783         struct drm_device *dev = crtc->base.dev;
10784         struct drm_i915_private *dev_priv = to_i915(dev);
10785         struct drm_plane *plane;
10786         struct intel_plane *intel_plane;
10787         struct intel_plane_state *state;
10788         struct drm_framebuffer *fb;
10789         char buf[64];
10790
10791         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10792                       crtc->base.base.id, crtc->base.name, context);
10793
10794         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10795         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10796                       buf, pipe_config->output_types);
10797
10798         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10799                       transcoder_name(pipe_config->cpu_transcoder),
10800                       pipe_config->pipe_bpp, pipe_config->dither);
10801
10802         if (pipe_config->has_pch_encoder)
10803                 intel_dump_m_n_config(pipe_config, "fdi",
10804                                       pipe_config->fdi_lanes,
10805                                       &pipe_config->fdi_m_n);
10806
10807         if (pipe_config->ycbcr420)
10808                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10809
10810         if (intel_crtc_has_dp_encoder(pipe_config)) {
10811                 intel_dump_m_n_config(pipe_config, "dp m_n",
10812                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10813                 if (pipe_config->has_drrs)
10814                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10815                                               pipe_config->lane_count,
10816                                               &pipe_config->dp_m2_n2);
10817         }
10818
10819         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10820                       pipe_config->has_audio, pipe_config->has_infoframe);
10821
10822         DRM_DEBUG_KMS("requested mode:\n");
10823         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10824         DRM_DEBUG_KMS("adjusted mode:\n");
10825         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10826         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10827         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10828                       pipe_config->port_clock,
10829                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10830                       pipe_config->pixel_rate);
10831
10832         if (INTEL_GEN(dev_priv) >= 9)
10833                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10834                               crtc->num_scalers,
10835                               pipe_config->scaler_state.scaler_users,
10836                               pipe_config->scaler_state.scaler_id);
10837
10838         if (HAS_GMCH_DISPLAY(dev_priv))
10839                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10840                               pipe_config->gmch_pfit.control,
10841                               pipe_config->gmch_pfit.pgm_ratios,
10842                               pipe_config->gmch_pfit.lvds_border_bits);
10843         else
10844                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10845                               pipe_config->pch_pfit.pos,
10846                               pipe_config->pch_pfit.size,
10847                               enableddisabled(pipe_config->pch_pfit.enabled));
10848
10849         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10850                       pipe_config->ips_enabled, pipe_config->double_wide);
10851
10852         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10853
10854         DRM_DEBUG_KMS("planes on this crtc\n");
10855         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10856                 struct drm_format_name_buf format_name;
10857                 intel_plane = to_intel_plane(plane);
10858                 if (intel_plane->pipe != crtc->pipe)
10859                         continue;
10860
10861                 state = to_intel_plane_state(plane->state);
10862                 fb = state->base.fb;
10863                 if (!fb) {
10864                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10865                                       plane->base.id, plane->name, state->scaler_id);
10866                         continue;
10867                 }
10868
10869                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10870                               plane->base.id, plane->name,
10871                               fb->base.id, fb->width, fb->height,
10872                               drm_get_format_name(fb->format->format, &format_name));
10873                 if (INTEL_GEN(dev_priv) >= 9)
10874                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10875                                       state->scaler_id,
10876                                       state->base.src.x1 >> 16,
10877                                       state->base.src.y1 >> 16,
10878                                       drm_rect_width(&state->base.src) >> 16,
10879                                       drm_rect_height(&state->base.src) >> 16,
10880                                       state->base.dst.x1, state->base.dst.y1,
10881                                       drm_rect_width(&state->base.dst),
10882                                       drm_rect_height(&state->base.dst));
10883         }
10884 }
10885
10886 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10887 {
10888         struct drm_device *dev = state->dev;
10889         struct drm_connector *connector;
10890         struct drm_connector_list_iter conn_iter;
10891         unsigned int used_ports = 0;
10892         unsigned int used_mst_ports = 0;
10893         bool ret = true;
10894
10895         /*
10896          * Walk the connector list instead of the encoder
10897          * list to detect the problem on ddi platforms
10898          * where there's just one encoder per digital port.
10899          */
10900         drm_connector_list_iter_begin(dev, &conn_iter);
10901         drm_for_each_connector_iter(connector, &conn_iter) {
10902                 struct drm_connector_state *connector_state;
10903                 struct intel_encoder *encoder;
10904
10905                 connector_state = drm_atomic_get_new_connector_state(state, connector);
10906                 if (!connector_state)
10907                         connector_state = connector->state;
10908
10909                 if (!connector_state->best_encoder)
10910                         continue;
10911
10912                 encoder = to_intel_encoder(connector_state->best_encoder);
10913
10914                 WARN_ON(!connector_state->crtc);
10915
10916                 switch (encoder->type) {
10917                         unsigned int port_mask;
10918                 case INTEL_OUTPUT_DDI:
10919                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
10920                                 break;
10921                 case INTEL_OUTPUT_DP:
10922                 case INTEL_OUTPUT_HDMI:
10923                 case INTEL_OUTPUT_EDP:
10924                         port_mask = 1 << encoder->port;
10925
10926                         /* the same port mustn't appear more than once */
10927                         if (used_ports & port_mask)
10928                                 ret = false;
10929
10930                         used_ports |= port_mask;
10931                         break;
10932                 case INTEL_OUTPUT_DP_MST:
10933                         used_mst_ports |=
10934                                 1 << encoder->port;
10935                         break;
10936                 default:
10937                         break;
10938                 }
10939         }
10940         drm_connector_list_iter_end(&conn_iter);
10941
10942         /* can't mix MST and SST/HDMI on the same port */
10943         if (used_ports & used_mst_ports)
10944                 return false;
10945
10946         return ret;
10947 }
10948
10949 static void
10950 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10951 {
10952         struct drm_i915_private *dev_priv =
10953                 to_i915(crtc_state->base.crtc->dev);
10954         struct intel_crtc_scaler_state scaler_state;
10955         struct intel_dpll_hw_state dpll_hw_state;
10956         struct intel_shared_dpll *shared_dpll;
10957         struct intel_crtc_wm_state wm_state;
10958         bool force_thru, ips_force_disable;
10959
10960         /* FIXME: before the switch to atomic started, a new pipe_config was
10961          * kzalloc'd. Code that depends on any field being zero should be
10962          * fixed, so that the crtc_state can be safely duplicated. For now,
10963          * only fields that are know to not cause problems are preserved. */
10964
10965         scaler_state = crtc_state->scaler_state;
10966         shared_dpll = crtc_state->shared_dpll;
10967         dpll_hw_state = crtc_state->dpll_hw_state;
10968         force_thru = crtc_state->pch_pfit.force_thru;
10969         ips_force_disable = crtc_state->ips_force_disable;
10970         if (IS_G4X(dev_priv) ||
10971             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10972                 wm_state = crtc_state->wm;
10973
10974         /* Keep base drm_crtc_state intact, only clear our extended struct */
10975         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
10976         memset(&crtc_state->base + 1, 0,
10977                sizeof(*crtc_state) - sizeof(crtc_state->base));
10978
10979         crtc_state->scaler_state = scaler_state;
10980         crtc_state->shared_dpll = shared_dpll;
10981         crtc_state->dpll_hw_state = dpll_hw_state;
10982         crtc_state->pch_pfit.force_thru = force_thru;
10983         crtc_state->ips_force_disable = ips_force_disable;
10984         if (IS_G4X(dev_priv) ||
10985             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10986                 crtc_state->wm = wm_state;
10987 }
10988
10989 static int
10990 intel_modeset_pipe_config(struct drm_crtc *crtc,
10991                           struct intel_crtc_state *pipe_config)
10992 {
10993         struct drm_atomic_state *state = pipe_config->base.state;
10994         struct intel_encoder *encoder;
10995         struct drm_connector *connector;
10996         struct drm_connector_state *connector_state;
10997         int base_bpp, ret = -EINVAL;
10998         int i;
10999         bool retry = true;
11000
11001         clear_intel_crtc_state(pipe_config);
11002
11003         pipe_config->cpu_transcoder =
11004                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11005
11006         /*
11007          * Sanitize sync polarity flags based on requested ones. If neither
11008          * positive or negative polarity is requested, treat this as meaning
11009          * negative polarity.
11010          */
11011         if (!(pipe_config->base.adjusted_mode.flags &
11012               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11013                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11014
11015         if (!(pipe_config->base.adjusted_mode.flags &
11016               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11017                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11018
11019         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11020                                              pipe_config);
11021         if (base_bpp < 0)
11022                 goto fail;
11023
11024         /*
11025          * Determine the real pipe dimensions. Note that stereo modes can
11026          * increase the actual pipe size due to the frame doubling and
11027          * insertion of additional space for blanks between the frame. This
11028          * is stored in the crtc timings. We use the requested mode to do this
11029          * computation to clearly distinguish it from the adjusted mode, which
11030          * can be changed by the connectors in the below retry loop.
11031          */
11032         drm_mode_get_hv_timing(&pipe_config->base.mode,
11033                                &pipe_config->pipe_src_w,
11034                                &pipe_config->pipe_src_h);
11035
11036         for_each_new_connector_in_state(state, connector, connector_state, i) {
11037                 if (connector_state->crtc != crtc)
11038                         continue;
11039
11040                 encoder = to_intel_encoder(connector_state->best_encoder);
11041
11042                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11043                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11044                         goto fail;
11045                 }
11046
11047                 /*
11048                  * Determine output_types before calling the .compute_config()
11049                  * hooks so that the hooks can use this information safely.
11050                  */
11051                 if (encoder->compute_output_type)
11052                         pipe_config->output_types |=
11053                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11054                                                                  connector_state));
11055                 else
11056                         pipe_config->output_types |= BIT(encoder->type);
11057         }
11058
11059 encoder_retry:
11060         /* Ensure the port clock defaults are reset when retrying. */
11061         pipe_config->port_clock = 0;
11062         pipe_config->pixel_multiplier = 1;
11063
11064         /* Fill in default crtc timings, allow encoders to overwrite them. */
11065         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11066                               CRTC_STEREO_DOUBLE);
11067
11068         /* Pass our mode to the connectors and the CRTC to give them a chance to
11069          * adjust it according to limitations or connector properties, and also
11070          * a chance to reject the mode entirely.
11071          */
11072         for_each_new_connector_in_state(state, connector, connector_state, i) {
11073                 if (connector_state->crtc != crtc)
11074                         continue;
11075
11076                 encoder = to_intel_encoder(connector_state->best_encoder);
11077
11078                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11079                         DRM_DEBUG_KMS("Encoder config failure\n");
11080                         goto fail;
11081                 }
11082         }
11083
11084         /* Set default port clock if not overwritten by the encoder. Needs to be
11085          * done afterwards in case the encoder adjusts the mode. */
11086         if (!pipe_config->port_clock)
11087                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11088                         * pipe_config->pixel_multiplier;
11089
11090         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11091         if (ret < 0) {
11092                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11093                 goto fail;
11094         }
11095
11096         if (ret == RETRY) {
11097                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11098                         ret = -EINVAL;
11099                         goto fail;
11100                 }
11101
11102                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11103                 retry = false;
11104                 goto encoder_retry;
11105         }
11106
11107         /* Dithering seems to not pass-through bits correctly when it should, so
11108          * only enable it on 6bpc panels and when its not a compliance
11109          * test requesting 6bpc video pattern.
11110          */
11111         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11112                 !pipe_config->dither_force_disable;
11113         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11114                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11115
11116 fail:
11117         return ret;
11118 }
11119
11120 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11121 {
11122         int diff;
11123
11124         if (clock1 == clock2)
11125                 return true;
11126
11127         if (!clock1 || !clock2)
11128                 return false;
11129
11130         diff = abs(clock1 - clock2);
11131
11132         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11133                 return true;
11134
11135         return false;
11136 }
11137
11138 static bool
11139 intel_compare_m_n(unsigned int m, unsigned int n,
11140                   unsigned int m2, unsigned int n2,
11141                   bool exact)
11142 {
11143         if (m == m2 && n == n2)
11144                 return true;
11145
11146         if (exact || !m || !n || !m2 || !n2)
11147                 return false;
11148
11149         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11150
11151         if (n > n2) {
11152                 while (n > n2) {
11153                         m2 <<= 1;
11154                         n2 <<= 1;
11155                 }
11156         } else if (n < n2) {
11157                 while (n < n2) {
11158                         m <<= 1;
11159                         n <<= 1;
11160                 }
11161         }
11162
11163         if (n != n2)
11164                 return false;
11165
11166         return intel_fuzzy_clock_check(m, m2);
11167 }
11168
11169 static bool
11170 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11171                        struct intel_link_m_n *m2_n2,
11172                        bool adjust)
11173 {
11174         if (m_n->tu == m2_n2->tu &&
11175             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11176                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11177             intel_compare_m_n(m_n->link_m, m_n->link_n,
11178                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11179                 if (adjust)
11180                         *m2_n2 = *m_n;
11181
11182                 return true;
11183         }
11184
11185         return false;
11186 }
11187
11188 static void __printf(3, 4)
11189 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11190 {
11191         struct va_format vaf;
11192         va_list args;
11193
11194         va_start(args, format);
11195         vaf.fmt = format;
11196         vaf.va = &args;
11197
11198         if (adjust)
11199                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11200         else
11201                 drm_err("mismatch in %s %pV", name, &vaf);
11202
11203         va_end(args);
11204 }
11205
11206 static bool
11207 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11208                           struct intel_crtc_state *current_config,
11209                           struct intel_crtc_state *pipe_config,
11210                           bool adjust)
11211 {
11212         bool ret = true;
11213         bool fixup_inherited = adjust &&
11214                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11215                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11216
11217 #define PIPE_CONF_CHECK_X(name) do { \
11218         if (current_config->name != pipe_config->name) { \
11219                 pipe_config_err(adjust, __stringify(name), \
11220                           "(expected 0x%08x, found 0x%08x)\n", \
11221                           current_config->name, \
11222                           pipe_config->name); \
11223                 ret = false; \
11224         } \
11225 } while (0)
11226
11227 #define PIPE_CONF_CHECK_I(name) do { \
11228         if (current_config->name != pipe_config->name) { \
11229                 pipe_config_err(adjust, __stringify(name), \
11230                           "(expected %i, found %i)\n", \
11231                           current_config->name, \
11232                           pipe_config->name); \
11233                 ret = false; \
11234         } \
11235 } while (0)
11236
11237 #define PIPE_CONF_CHECK_BOOL(name) do { \
11238         if (current_config->name != pipe_config->name) { \
11239                 pipe_config_err(adjust, __stringify(name), \
11240                           "(expected %s, found %s)\n", \
11241                           yesno(current_config->name), \
11242                           yesno(pipe_config->name)); \
11243                 ret = false; \
11244         } \
11245 } while (0)
11246
11247 /*
11248  * Checks state where we only read out the enabling, but not the entire
11249  * state itself (like full infoframes or ELD for audio). These states
11250  * require a full modeset on bootup to fix up.
11251  */
11252 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11253         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11254                 PIPE_CONF_CHECK_BOOL(name); \
11255         } else { \
11256                 pipe_config_err(adjust, __stringify(name), \
11257                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11258                           yesno(current_config->name), \
11259                           yesno(pipe_config->name)); \
11260                 ret = false; \
11261         } \
11262 } while (0)
11263
11264 #define PIPE_CONF_CHECK_P(name) do { \
11265         if (current_config->name != pipe_config->name) { \
11266                 pipe_config_err(adjust, __stringify(name), \
11267                           "(expected %p, found %p)\n", \
11268                           current_config->name, \
11269                           pipe_config->name); \
11270                 ret = false; \
11271         } \
11272 } while (0)
11273
11274 #define PIPE_CONF_CHECK_M_N(name) do { \
11275         if (!intel_compare_link_m_n(&current_config->name, \
11276                                     &pipe_config->name,\
11277                                     adjust)) { \
11278                 pipe_config_err(adjust, __stringify(name), \
11279                           "(expected tu %i gmch %i/%i link %i/%i, " \
11280                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11281                           current_config->name.tu, \
11282                           current_config->name.gmch_m, \
11283                           current_config->name.gmch_n, \
11284                           current_config->name.link_m, \
11285                           current_config->name.link_n, \
11286                           pipe_config->name.tu, \
11287                           pipe_config->name.gmch_m, \
11288                           pipe_config->name.gmch_n, \
11289                           pipe_config->name.link_m, \
11290                           pipe_config->name.link_n); \
11291                 ret = false; \
11292         } \
11293 } while (0)
11294
11295 /* This is required for BDW+ where there is only one set of registers for
11296  * switching between high and low RR.
11297  * This macro can be used whenever a comparison has to be made between one
11298  * hw state and multiple sw state variables.
11299  */
11300 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11301         if (!intel_compare_link_m_n(&current_config->name, \
11302                                     &pipe_config->name, adjust) && \
11303             !intel_compare_link_m_n(&current_config->alt_name, \
11304                                     &pipe_config->name, adjust)) { \
11305                 pipe_config_err(adjust, __stringify(name), \
11306                           "(expected tu %i gmch %i/%i link %i/%i, " \
11307                           "or tu %i gmch %i/%i link %i/%i, " \
11308                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11309                           current_config->name.tu, \
11310                           current_config->name.gmch_m, \
11311                           current_config->name.gmch_n, \
11312                           current_config->name.link_m, \
11313                           current_config->name.link_n, \
11314                           current_config->alt_name.tu, \
11315                           current_config->alt_name.gmch_m, \
11316                           current_config->alt_name.gmch_n, \
11317                           current_config->alt_name.link_m, \
11318                           current_config->alt_name.link_n, \
11319                           pipe_config->name.tu, \
11320                           pipe_config->name.gmch_m, \
11321                           pipe_config->name.gmch_n, \
11322                           pipe_config->name.link_m, \
11323                           pipe_config->name.link_n); \
11324                 ret = false; \
11325         } \
11326 } while (0)
11327
11328 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11329         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11330                 pipe_config_err(adjust, __stringify(name), \
11331                           "(%x) (expected %i, found %i)\n", \
11332                           (mask), \
11333                           current_config->name & (mask), \
11334                           pipe_config->name & (mask)); \
11335                 ret = false; \
11336         } \
11337 } while (0)
11338
11339 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11340         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11341                 pipe_config_err(adjust, __stringify(name), \
11342                           "(expected %i, found %i)\n", \
11343                           current_config->name, \
11344                           pipe_config->name); \
11345                 ret = false; \
11346         } \
11347 } while (0)
11348
11349 #define PIPE_CONF_QUIRK(quirk)  \
11350         ((current_config->quirks | pipe_config->quirks) & (quirk))
11351
11352         PIPE_CONF_CHECK_I(cpu_transcoder);
11353
11354         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11355         PIPE_CONF_CHECK_I(fdi_lanes);
11356         PIPE_CONF_CHECK_M_N(fdi_m_n);
11357
11358         PIPE_CONF_CHECK_I(lane_count);
11359         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11360
11361         if (INTEL_GEN(dev_priv) < 8) {
11362                 PIPE_CONF_CHECK_M_N(dp_m_n);
11363
11364                 if (current_config->has_drrs)
11365                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11366         } else
11367                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11368
11369         PIPE_CONF_CHECK_X(output_types);
11370
11371         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11372         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11373         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11374         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11375         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11376         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11377
11378         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11379         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11380         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11381         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11382         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11383         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11384
11385         PIPE_CONF_CHECK_I(pixel_multiplier);
11386         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11387         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11388             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11389                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11390
11391         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11392         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11393         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11394         PIPE_CONF_CHECK_BOOL(ycbcr420);
11395
11396         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11397
11398         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11399                               DRM_MODE_FLAG_INTERLACE);
11400
11401         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11402                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11403                                       DRM_MODE_FLAG_PHSYNC);
11404                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11405                                       DRM_MODE_FLAG_NHSYNC);
11406                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11407                                       DRM_MODE_FLAG_PVSYNC);
11408                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11409                                       DRM_MODE_FLAG_NVSYNC);
11410         }
11411
11412         PIPE_CONF_CHECK_X(gmch_pfit.control);
11413         /* pfit ratios are autocomputed by the hw on gen4+ */
11414         if (INTEL_GEN(dev_priv) < 4)
11415                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11416         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11417
11418         if (!adjust) {
11419                 PIPE_CONF_CHECK_I(pipe_src_w);
11420                 PIPE_CONF_CHECK_I(pipe_src_h);
11421
11422                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11423                 if (current_config->pch_pfit.enabled) {
11424                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11425                         PIPE_CONF_CHECK_X(pch_pfit.size);
11426                 }
11427
11428                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11429                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11430         }
11431
11432         PIPE_CONF_CHECK_BOOL(double_wide);
11433
11434         PIPE_CONF_CHECK_P(shared_dpll);
11435         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11436         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11437         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11438         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11439         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11440         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11441         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11442         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11443         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11444         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11445         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11446         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11447         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11448         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11449         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11450         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11451         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11452         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11453         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11454         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11455         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11456         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11457         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11458         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11459         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11460         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11461         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11462         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11463         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11464         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11465         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11466
11467         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11468         PIPE_CONF_CHECK_X(dsi_pll.div);
11469
11470         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11471                 PIPE_CONF_CHECK_I(pipe_bpp);
11472
11473         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11474         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11475
11476         PIPE_CONF_CHECK_I(min_voltage_level);
11477
11478 #undef PIPE_CONF_CHECK_X
11479 #undef PIPE_CONF_CHECK_I
11480 #undef PIPE_CONF_CHECK_BOOL
11481 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11482 #undef PIPE_CONF_CHECK_P
11483 #undef PIPE_CONF_CHECK_FLAGS
11484 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11485 #undef PIPE_CONF_QUIRK
11486
11487         return ret;
11488 }
11489
11490 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11491                                            const struct intel_crtc_state *pipe_config)
11492 {
11493         if (pipe_config->has_pch_encoder) {
11494                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11495                                                             &pipe_config->fdi_m_n);
11496                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11497
11498                 /*
11499                  * FDI already provided one idea for the dotclock.
11500                  * Yell if the encoder disagrees.
11501                  */
11502                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11503                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11504                      fdi_dotclock, dotclock);
11505         }
11506 }
11507
11508 static void verify_wm_state(struct drm_crtc *crtc,
11509                             struct drm_crtc_state *new_state)
11510 {
11511         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11512         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11513         struct skl_pipe_wm hw_wm, *sw_wm;
11514         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11515         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11516         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11517         const enum pipe pipe = intel_crtc->pipe;
11518         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11519
11520         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11521                 return;
11522
11523         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11524         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11525
11526         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11527         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11528
11529         if (INTEL_GEN(dev_priv) >= 11)
11530                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
11531                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
11532                                   sw_ddb->enabled_slices,
11533                                   hw_ddb.enabled_slices);
11534         /* planes */
11535         for_each_universal_plane(dev_priv, pipe, plane) {
11536                 hw_plane_wm = &hw_wm.planes[plane];
11537                 sw_plane_wm = &sw_wm->planes[plane];
11538
11539                 /* Watermarks */
11540                 for (level = 0; level <= max_level; level++) {
11541                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11542                                                 &sw_plane_wm->wm[level]))
11543                                 continue;
11544
11545                         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",
11546                                   pipe_name(pipe), plane + 1, level,
11547                                   sw_plane_wm->wm[level].plane_en,
11548                                   sw_plane_wm->wm[level].plane_res_b,
11549                                   sw_plane_wm->wm[level].plane_res_l,
11550                                   hw_plane_wm->wm[level].plane_en,
11551                                   hw_plane_wm->wm[level].plane_res_b,
11552                                   hw_plane_wm->wm[level].plane_res_l);
11553                 }
11554
11555                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11556                                          &sw_plane_wm->trans_wm)) {
11557                         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",
11558                                   pipe_name(pipe), plane + 1,
11559                                   sw_plane_wm->trans_wm.plane_en,
11560                                   sw_plane_wm->trans_wm.plane_res_b,
11561                                   sw_plane_wm->trans_wm.plane_res_l,
11562                                   hw_plane_wm->trans_wm.plane_en,
11563                                   hw_plane_wm->trans_wm.plane_res_b,
11564                                   hw_plane_wm->trans_wm.plane_res_l);
11565                 }
11566
11567                 /* DDB */
11568                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11569                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11570
11571                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11572                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11573                                   pipe_name(pipe), plane + 1,
11574                                   sw_ddb_entry->start, sw_ddb_entry->end,
11575                                   hw_ddb_entry->start, hw_ddb_entry->end);
11576                 }
11577         }
11578
11579         /*
11580          * cursor
11581          * If the cursor plane isn't active, we may not have updated it's ddb
11582          * allocation. In that case since the ddb allocation will be updated
11583          * once the plane becomes visible, we can skip this check
11584          */
11585         if (1) {
11586                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11587                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11588
11589                 /* Watermarks */
11590                 for (level = 0; level <= max_level; level++) {
11591                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11592                                                 &sw_plane_wm->wm[level]))
11593                                 continue;
11594
11595                         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",
11596                                   pipe_name(pipe), level,
11597                                   sw_plane_wm->wm[level].plane_en,
11598                                   sw_plane_wm->wm[level].plane_res_b,
11599                                   sw_plane_wm->wm[level].plane_res_l,
11600                                   hw_plane_wm->wm[level].plane_en,
11601                                   hw_plane_wm->wm[level].plane_res_b,
11602                                   hw_plane_wm->wm[level].plane_res_l);
11603                 }
11604
11605                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11606                                          &sw_plane_wm->trans_wm)) {
11607                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11608                                   pipe_name(pipe),
11609                                   sw_plane_wm->trans_wm.plane_en,
11610                                   sw_plane_wm->trans_wm.plane_res_b,
11611                                   sw_plane_wm->trans_wm.plane_res_l,
11612                                   hw_plane_wm->trans_wm.plane_en,
11613                                   hw_plane_wm->trans_wm.plane_res_b,
11614                                   hw_plane_wm->trans_wm.plane_res_l);
11615                 }
11616
11617                 /* DDB */
11618                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11619                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11620
11621                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11622                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11623                                   pipe_name(pipe),
11624                                   sw_ddb_entry->start, sw_ddb_entry->end,
11625                                   hw_ddb_entry->start, hw_ddb_entry->end);
11626                 }
11627         }
11628 }
11629
11630 static void
11631 verify_connector_state(struct drm_device *dev,
11632                        struct drm_atomic_state *state,
11633                        struct drm_crtc *crtc)
11634 {
11635         struct drm_connector *connector;
11636         struct drm_connector_state *new_conn_state;
11637         int i;
11638
11639         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11640                 struct drm_encoder *encoder = connector->encoder;
11641                 struct drm_crtc_state *crtc_state = NULL;
11642
11643                 if (new_conn_state->crtc != crtc)
11644                         continue;
11645
11646                 if (crtc)
11647                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11648
11649                 intel_connector_verify_state(crtc_state, new_conn_state);
11650
11651                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11652                      "connector's atomic encoder doesn't match legacy encoder\n");
11653         }
11654 }
11655
11656 static void
11657 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11658 {
11659         struct intel_encoder *encoder;
11660         struct drm_connector *connector;
11661         struct drm_connector_state *old_conn_state, *new_conn_state;
11662         int i;
11663
11664         for_each_intel_encoder(dev, encoder) {
11665                 bool enabled = false, found = false;
11666                 enum pipe pipe;
11667
11668                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11669                               encoder->base.base.id,
11670                               encoder->base.name);
11671
11672                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11673                                                    new_conn_state, i) {
11674                         if (old_conn_state->best_encoder == &encoder->base)
11675                                 found = true;
11676
11677                         if (new_conn_state->best_encoder != &encoder->base)
11678                                 continue;
11679                         found = enabled = true;
11680
11681                         I915_STATE_WARN(new_conn_state->crtc !=
11682                                         encoder->base.crtc,
11683                              "connector's crtc doesn't match encoder crtc\n");
11684                 }
11685
11686                 if (!found)
11687                         continue;
11688
11689                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11690                      "encoder's enabled state mismatch "
11691                      "(expected %i, found %i)\n",
11692                      !!encoder->base.crtc, enabled);
11693
11694                 if (!encoder->base.crtc) {
11695                         bool active;
11696
11697                         active = encoder->get_hw_state(encoder, &pipe);
11698                         I915_STATE_WARN(active,
11699                              "encoder detached but still enabled on pipe %c.\n",
11700                              pipe_name(pipe));
11701                 }
11702         }
11703 }
11704
11705 static void
11706 verify_crtc_state(struct drm_crtc *crtc,
11707                   struct drm_crtc_state *old_crtc_state,
11708                   struct drm_crtc_state *new_crtc_state)
11709 {
11710         struct drm_device *dev = crtc->dev;
11711         struct drm_i915_private *dev_priv = to_i915(dev);
11712         struct intel_encoder *encoder;
11713         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11714         struct intel_crtc_state *pipe_config, *sw_config;
11715         struct drm_atomic_state *old_state;
11716         bool active;
11717
11718         old_state = old_crtc_state->state;
11719         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11720         pipe_config = to_intel_crtc_state(old_crtc_state);
11721         memset(pipe_config, 0, sizeof(*pipe_config));
11722         pipe_config->base.crtc = crtc;
11723         pipe_config->base.state = old_state;
11724
11725         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11726
11727         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11728
11729         /* we keep both pipes enabled on 830 */
11730         if (IS_I830(dev_priv))
11731                 active = new_crtc_state->active;
11732
11733         I915_STATE_WARN(new_crtc_state->active != active,
11734              "crtc active state doesn't match with hw state "
11735              "(expected %i, found %i)\n", new_crtc_state->active, active);
11736
11737         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11738              "transitional active state does not match atomic hw state "
11739              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11740
11741         for_each_encoder_on_crtc(dev, crtc, encoder) {
11742                 enum pipe pipe;
11743
11744                 active = encoder->get_hw_state(encoder, &pipe);
11745                 I915_STATE_WARN(active != new_crtc_state->active,
11746                         "[ENCODER:%i] active %i with crtc active %i\n",
11747                         encoder->base.base.id, active, new_crtc_state->active);
11748
11749                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11750                                 "Encoder connected to wrong pipe %c\n",
11751                                 pipe_name(pipe));
11752
11753                 if (active)
11754                         encoder->get_config(encoder, pipe_config);
11755         }
11756
11757         intel_crtc_compute_pixel_rate(pipe_config);
11758
11759         if (!new_crtc_state->active)
11760                 return;
11761
11762         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11763
11764         sw_config = to_intel_crtc_state(new_crtc_state);
11765         if (!intel_pipe_config_compare(dev_priv, sw_config,
11766                                        pipe_config, false)) {
11767                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11768                 intel_dump_pipe_config(intel_crtc, pipe_config,
11769                                        "[hw state]");
11770                 intel_dump_pipe_config(intel_crtc, sw_config,
11771                                        "[sw state]");
11772         }
11773 }
11774
11775 static void
11776 intel_verify_planes(struct intel_atomic_state *state)
11777 {
11778         struct intel_plane *plane;
11779         const struct intel_plane_state *plane_state;
11780         int i;
11781
11782         for_each_new_intel_plane_in_state(state, plane,
11783                                           plane_state, i)
11784                 assert_plane(plane, plane_state->base.visible);
11785 }
11786
11787 static void
11788 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11789                          struct intel_shared_dpll *pll,
11790                          struct drm_crtc *crtc,
11791                          struct drm_crtc_state *new_state)
11792 {
11793         struct intel_dpll_hw_state dpll_hw_state;
11794         unsigned crtc_mask;
11795         bool active;
11796
11797         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11798
11799         DRM_DEBUG_KMS("%s\n", pll->info->name);
11800
11801         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
11802
11803         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
11804                 I915_STATE_WARN(!pll->on && pll->active_mask,
11805                      "pll in active use but not on in sw tracking\n");
11806                 I915_STATE_WARN(pll->on && !pll->active_mask,
11807                      "pll is on but not used by any active crtc\n");
11808                 I915_STATE_WARN(pll->on != active,
11809                      "pll on state mismatch (expected %i, found %i)\n",
11810                      pll->on, active);
11811         }
11812
11813         if (!crtc) {
11814                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11815                                 "more active pll users than references: %x vs %x\n",
11816                                 pll->active_mask, pll->state.crtc_mask);
11817
11818                 return;
11819         }
11820
11821         crtc_mask = 1 << drm_crtc_index(crtc);
11822
11823         if (new_state->active)
11824                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11825                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11826                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11827         else
11828                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11829                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11830                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11831
11832         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11833                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11834                         crtc_mask, pll->state.crtc_mask);
11835
11836         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11837                                           &dpll_hw_state,
11838                                           sizeof(dpll_hw_state)),
11839                         "pll hw state mismatch\n");
11840 }
11841
11842 static void
11843 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11844                          struct drm_crtc_state *old_crtc_state,
11845                          struct drm_crtc_state *new_crtc_state)
11846 {
11847         struct drm_i915_private *dev_priv = to_i915(dev);
11848         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11849         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11850
11851         if (new_state->shared_dpll)
11852                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11853
11854         if (old_state->shared_dpll &&
11855             old_state->shared_dpll != new_state->shared_dpll) {
11856                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
11857                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11858
11859                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11860                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11861                                 pipe_name(drm_crtc_index(crtc)));
11862                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11863                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11864                                 pipe_name(drm_crtc_index(crtc)));
11865         }
11866 }
11867
11868 static void
11869 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11870                           struct drm_atomic_state *state,
11871                           struct drm_crtc_state *old_state,
11872                           struct drm_crtc_state *new_state)
11873 {
11874         if (!needs_modeset(new_state) &&
11875             !to_intel_crtc_state(new_state)->update_pipe)
11876                 return;
11877
11878         verify_wm_state(crtc, new_state);
11879         verify_connector_state(crtc->dev, state, crtc);
11880         verify_crtc_state(crtc, old_state, new_state);
11881         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11882 }
11883
11884 static void
11885 verify_disabled_dpll_state(struct drm_device *dev)
11886 {
11887         struct drm_i915_private *dev_priv = to_i915(dev);
11888         int i;
11889
11890         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11891                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
11892 }
11893
11894 static void
11895 intel_modeset_verify_disabled(struct drm_device *dev,
11896                               struct drm_atomic_state *state)
11897 {
11898         verify_encoder_state(dev, state);
11899         verify_connector_state(dev, state, NULL);
11900         verify_disabled_dpll_state(dev);
11901 }
11902
11903 static void update_scanline_offset(struct intel_crtc *crtc)
11904 {
11905         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11906
11907         /*
11908          * The scanline counter increments at the leading edge of hsync.
11909          *
11910          * On most platforms it starts counting from vtotal-1 on the
11911          * first active line. That means the scanline counter value is
11912          * always one less than what we would expect. Ie. just after
11913          * start of vblank, which also occurs at start of hsync (on the
11914          * last active line), the scanline counter will read vblank_start-1.
11915          *
11916          * On gen2 the scanline counter starts counting from 1 instead
11917          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11918          * to keep the value positive), instead of adding one.
11919          *
11920          * On HSW+ the behaviour of the scanline counter depends on the output
11921          * type. For DP ports it behaves like most other platforms, but on HDMI
11922          * there's an extra 1 line difference. So we need to add two instead of
11923          * one to the value.
11924          *
11925          * On VLV/CHV DSI the scanline counter would appear to increment
11926          * approx. 1/3 of a scanline before start of vblank. Unfortunately
11927          * that means we can't tell whether we're in vblank or not while
11928          * we're on that particular line. We must still set scanline_offset
11929          * to 1 so that the vblank timestamps come out correct when we query
11930          * the scanline counter from within the vblank interrupt handler.
11931          * However if queried just before the start of vblank we'll get an
11932          * answer that's slightly in the future.
11933          */
11934         if (IS_GEN2(dev_priv)) {
11935                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
11936                 int vtotal;
11937
11938                 vtotal = adjusted_mode->crtc_vtotal;
11939                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
11940                         vtotal /= 2;
11941
11942                 crtc->scanline_offset = vtotal - 1;
11943         } else if (HAS_DDI(dev_priv) &&
11944                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
11945                 crtc->scanline_offset = 2;
11946         } else
11947                 crtc->scanline_offset = 1;
11948 }
11949
11950 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
11951 {
11952         struct drm_device *dev = state->dev;
11953         struct drm_i915_private *dev_priv = to_i915(dev);
11954         struct drm_crtc *crtc;
11955         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11956         int i;
11957
11958         if (!dev_priv->display.crtc_compute_clock)
11959                 return;
11960
11961         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11962                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11963                 struct intel_shared_dpll *old_dpll =
11964                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
11965
11966                 if (!needs_modeset(new_crtc_state))
11967                         continue;
11968
11969                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
11970
11971                 if (!old_dpll)
11972                         continue;
11973
11974                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
11975         }
11976 }
11977
11978 /*
11979  * This implements the workaround described in the "notes" section of the mode
11980  * set sequence documentation. When going from no pipes or single pipe to
11981  * multiple pipes, and planes are enabled after the pipe, we need to wait at
11982  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
11983  */
11984 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
11985 {
11986         struct drm_crtc_state *crtc_state;
11987         struct intel_crtc *intel_crtc;
11988         struct drm_crtc *crtc;
11989         struct intel_crtc_state *first_crtc_state = NULL;
11990         struct intel_crtc_state *other_crtc_state = NULL;
11991         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
11992         int i;
11993
11994         /* look at all crtc's that are going to be enabled in during modeset */
11995         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
11996                 intel_crtc = to_intel_crtc(crtc);
11997
11998                 if (!crtc_state->active || !needs_modeset(crtc_state))
11999                         continue;
12000
12001                 if (first_crtc_state) {
12002                         other_crtc_state = to_intel_crtc_state(crtc_state);
12003                         break;
12004                 } else {
12005                         first_crtc_state = to_intel_crtc_state(crtc_state);
12006                         first_pipe = intel_crtc->pipe;
12007                 }
12008         }
12009
12010         /* No workaround needed? */
12011         if (!first_crtc_state)
12012                 return 0;
12013
12014         /* w/a possibly needed, check how many crtc's are already enabled. */
12015         for_each_intel_crtc(state->dev, intel_crtc) {
12016                 struct intel_crtc_state *pipe_config;
12017
12018                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12019                 if (IS_ERR(pipe_config))
12020                         return PTR_ERR(pipe_config);
12021
12022                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12023
12024                 if (!pipe_config->base.active ||
12025                     needs_modeset(&pipe_config->base))
12026                         continue;
12027
12028                 /* 2 or more enabled crtcs means no need for w/a */
12029                 if (enabled_pipe != INVALID_PIPE)
12030                         return 0;
12031
12032                 enabled_pipe = intel_crtc->pipe;
12033         }
12034
12035         if (enabled_pipe != INVALID_PIPE)
12036                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12037         else if (other_crtc_state)
12038                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12039
12040         return 0;
12041 }
12042
12043 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12044 {
12045         struct drm_crtc *crtc;
12046
12047         /* Add all pipes to the state */
12048         for_each_crtc(state->dev, crtc) {
12049                 struct drm_crtc_state *crtc_state;
12050
12051                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12052                 if (IS_ERR(crtc_state))
12053                         return PTR_ERR(crtc_state);
12054         }
12055
12056         return 0;
12057 }
12058
12059 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12060 {
12061         struct drm_crtc *crtc;
12062
12063         /*
12064          * Add all pipes to the state, and force
12065          * a modeset on all the active ones.
12066          */
12067         for_each_crtc(state->dev, crtc) {
12068                 struct drm_crtc_state *crtc_state;
12069                 int ret;
12070
12071                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12072                 if (IS_ERR(crtc_state))
12073                         return PTR_ERR(crtc_state);
12074
12075                 if (!crtc_state->active || needs_modeset(crtc_state))
12076                         continue;
12077
12078                 crtc_state->mode_changed = true;
12079
12080                 ret = drm_atomic_add_affected_connectors(state, crtc);
12081                 if (ret)
12082                         return ret;
12083
12084                 ret = drm_atomic_add_affected_planes(state, crtc);
12085                 if (ret)
12086                         return ret;
12087         }
12088
12089         return 0;
12090 }
12091
12092 static int intel_modeset_checks(struct drm_atomic_state *state)
12093 {
12094         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12095         struct drm_i915_private *dev_priv = to_i915(state->dev);
12096         struct drm_crtc *crtc;
12097         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12098         int ret = 0, i;
12099
12100         if (!check_digital_port_conflicts(state)) {
12101                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12102                 return -EINVAL;
12103         }
12104
12105         intel_state->modeset = true;
12106         intel_state->active_crtcs = dev_priv->active_crtcs;
12107         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12108         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12109
12110         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12111                 if (new_crtc_state->active)
12112                         intel_state->active_crtcs |= 1 << i;
12113                 else
12114                         intel_state->active_crtcs &= ~(1 << i);
12115
12116                 if (old_crtc_state->active != new_crtc_state->active)
12117                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12118         }
12119
12120         /*
12121          * See if the config requires any additional preparation, e.g.
12122          * to adjust global state with pipes off.  We need to do this
12123          * here so we can get the modeset_pipe updated config for the new
12124          * mode set on this crtc.  For other crtcs we need to use the
12125          * adjusted_mode bits in the crtc directly.
12126          */
12127         if (dev_priv->display.modeset_calc_cdclk) {
12128                 ret = dev_priv->display.modeset_calc_cdclk(state);
12129                 if (ret < 0)
12130                         return ret;
12131
12132                 /*
12133                  * Writes to dev_priv->cdclk.logical must protected by
12134                  * holding all the crtc locks, even if we don't end up
12135                  * touching the hardware
12136                  */
12137                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12138                                         &intel_state->cdclk.logical)) {
12139                         ret = intel_lock_all_pipes(state);
12140                         if (ret < 0)
12141                                 return ret;
12142                 }
12143
12144                 /* All pipes must be switched off while we change the cdclk. */
12145                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12146                                               &intel_state->cdclk.actual)) {
12147                         ret = intel_modeset_all_pipes(state);
12148                         if (ret < 0)
12149                                 return ret;
12150                 }
12151
12152                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12153                               intel_state->cdclk.logical.cdclk,
12154                               intel_state->cdclk.actual.cdclk);
12155                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12156                               intel_state->cdclk.logical.voltage_level,
12157                               intel_state->cdclk.actual.voltage_level);
12158         } else {
12159                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12160         }
12161
12162         intel_modeset_clear_plls(state);
12163
12164         if (IS_HASWELL(dev_priv))
12165                 return haswell_mode_set_planes_workaround(state);
12166
12167         return 0;
12168 }
12169
12170 /*
12171  * Handle calculation of various watermark data at the end of the atomic check
12172  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12173  * handlers to ensure that all derived state has been updated.
12174  */
12175 static int calc_watermark_data(struct drm_atomic_state *state)
12176 {
12177         struct drm_device *dev = state->dev;
12178         struct drm_i915_private *dev_priv = to_i915(dev);
12179
12180         /* Is there platform-specific watermark information to calculate? */
12181         if (dev_priv->display.compute_global_watermarks)
12182                 return dev_priv->display.compute_global_watermarks(state);
12183
12184         return 0;
12185 }
12186
12187 /**
12188  * intel_atomic_check - validate state object
12189  * @dev: drm device
12190  * @state: state to validate
12191  */
12192 static int intel_atomic_check(struct drm_device *dev,
12193                               struct drm_atomic_state *state)
12194 {
12195         struct drm_i915_private *dev_priv = to_i915(dev);
12196         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12197         struct drm_crtc *crtc;
12198         struct drm_crtc_state *old_crtc_state, *crtc_state;
12199         int ret, i;
12200         bool any_ms = false;
12201
12202         /* Catch I915_MODE_FLAG_INHERITED */
12203         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12204                                       crtc_state, i) {
12205                 if (crtc_state->mode.private_flags !=
12206                     old_crtc_state->mode.private_flags)
12207                         crtc_state->mode_changed = true;
12208         }
12209
12210         ret = drm_atomic_helper_check_modeset(dev, state);
12211         if (ret)
12212                 return ret;
12213
12214         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12215                 struct intel_crtc_state *pipe_config =
12216                         to_intel_crtc_state(crtc_state);
12217
12218                 if (!needs_modeset(crtc_state))
12219                         continue;
12220
12221                 if (!crtc_state->enable) {
12222                         any_ms = true;
12223                         continue;
12224                 }
12225
12226                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12227                 if (ret) {
12228                         intel_dump_pipe_config(to_intel_crtc(crtc),
12229                                                pipe_config, "[failed]");
12230                         return ret;
12231                 }
12232
12233                 if (i915_modparams.fastboot &&
12234                     intel_pipe_config_compare(dev_priv,
12235                                         to_intel_crtc_state(old_crtc_state),
12236                                         pipe_config, true)) {
12237                         crtc_state->mode_changed = false;
12238                         pipe_config->update_pipe = true;
12239                 }
12240
12241                 if (needs_modeset(crtc_state))
12242                         any_ms = true;
12243
12244                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12245                                        needs_modeset(crtc_state) ?
12246                                        "[modeset]" : "[fastset]");
12247         }
12248
12249         if (any_ms) {
12250                 ret = intel_modeset_checks(state);
12251
12252                 if (ret)
12253                         return ret;
12254         } else {
12255                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12256         }
12257
12258         ret = drm_atomic_helper_check_planes(dev, state);
12259         if (ret)
12260                 return ret;
12261
12262         intel_fbc_choose_crtc(dev_priv, intel_state);
12263         return calc_watermark_data(state);
12264 }
12265
12266 static int intel_atomic_prepare_commit(struct drm_device *dev,
12267                                        struct drm_atomic_state *state)
12268 {
12269         return drm_atomic_helper_prepare_planes(dev, state);
12270 }
12271
12272 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12273 {
12274         struct drm_device *dev = crtc->base.dev;
12275
12276         if (!dev->max_vblank_count)
12277                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12278
12279         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12280 }
12281
12282 static void intel_update_crtc(struct drm_crtc *crtc,
12283                               struct drm_atomic_state *state,
12284                               struct drm_crtc_state *old_crtc_state,
12285                               struct drm_crtc_state *new_crtc_state)
12286 {
12287         struct drm_device *dev = crtc->dev;
12288         struct drm_i915_private *dev_priv = to_i915(dev);
12289         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12290         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12291         bool modeset = needs_modeset(new_crtc_state);
12292         struct intel_plane_state *new_plane_state =
12293                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12294                                                  to_intel_plane(crtc->primary));
12295
12296         if (modeset) {
12297                 update_scanline_offset(intel_crtc);
12298                 dev_priv->display.crtc_enable(pipe_config, state);
12299
12300                 /* vblanks work again, re-enable pipe CRC. */
12301                 intel_crtc_enable_pipe_crc(intel_crtc);
12302         } else {
12303                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12304                                        pipe_config);
12305         }
12306
12307         if (new_plane_state)
12308                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12309
12310         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12311 }
12312
12313 static void intel_update_crtcs(struct drm_atomic_state *state)
12314 {
12315         struct drm_crtc *crtc;
12316         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12317         int i;
12318
12319         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12320                 if (!new_crtc_state->active)
12321                         continue;
12322
12323                 intel_update_crtc(crtc, state, old_crtc_state,
12324                                   new_crtc_state);
12325         }
12326 }
12327
12328 static void skl_update_crtcs(struct drm_atomic_state *state)
12329 {
12330         struct drm_i915_private *dev_priv = to_i915(state->dev);
12331         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12332         struct drm_crtc *crtc;
12333         struct intel_crtc *intel_crtc;
12334         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12335         struct intel_crtc_state *cstate;
12336         unsigned int updated = 0;
12337         bool progress;
12338         enum pipe pipe;
12339         int i;
12340         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12341         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12342
12343         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12344
12345         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12346                 /* ignore allocations for crtc's that have been turned off. */
12347                 if (new_crtc_state->active)
12348                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12349
12350         /* If 2nd DBuf slice required, enable it here */
12351         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12352                 icl_dbuf_slices_update(dev_priv, required_slices);
12353
12354         /*
12355          * Whenever the number of active pipes changes, we need to make sure we
12356          * update the pipes in the right order so that their ddb allocations
12357          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12358          * cause pipe underruns and other bad stuff.
12359          */
12360         do {
12361                 progress = false;
12362
12363                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12364                         bool vbl_wait = false;
12365                         unsigned int cmask = drm_crtc_mask(crtc);
12366
12367                         intel_crtc = to_intel_crtc(crtc);
12368                         cstate = to_intel_crtc_state(new_crtc_state);
12369                         pipe = intel_crtc->pipe;
12370
12371                         if (updated & cmask || !cstate->base.active)
12372                                 continue;
12373
12374                         if (skl_ddb_allocation_overlaps(dev_priv,
12375                                                         entries,
12376                                                         &cstate->wm.skl.ddb,
12377                                                         i))
12378                                 continue;
12379
12380                         updated |= cmask;
12381                         entries[i] = &cstate->wm.skl.ddb;
12382
12383                         /*
12384                          * If this is an already active pipe, it's DDB changed,
12385                          * and this isn't the last pipe that needs updating
12386                          * then we need to wait for a vblank to pass for the
12387                          * new ddb allocation to take effect.
12388                          */
12389                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12390                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12391                             !new_crtc_state->active_changed &&
12392                             intel_state->wm_results.dirty_pipes != updated)
12393                                 vbl_wait = true;
12394
12395                         intel_update_crtc(crtc, state, old_crtc_state,
12396                                           new_crtc_state);
12397
12398                         if (vbl_wait)
12399                                 intel_wait_for_vblank(dev_priv, pipe);
12400
12401                         progress = true;
12402                 }
12403         } while (progress);
12404
12405         /* If 2nd DBuf slice is no more required disable it */
12406         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12407                 icl_dbuf_slices_update(dev_priv, required_slices);
12408 }
12409
12410 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12411 {
12412         struct intel_atomic_state *state, *next;
12413         struct llist_node *freed;
12414
12415         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12416         llist_for_each_entry_safe(state, next, freed, freed)
12417                 drm_atomic_state_put(&state->base);
12418 }
12419
12420 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12421 {
12422         struct drm_i915_private *dev_priv =
12423                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12424
12425         intel_atomic_helper_free_state(dev_priv);
12426 }
12427
12428 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12429 {
12430         struct wait_queue_entry wait_fence, wait_reset;
12431         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12432
12433         init_wait_entry(&wait_fence, 0);
12434         init_wait_entry(&wait_reset, 0);
12435         for (;;) {
12436                 prepare_to_wait(&intel_state->commit_ready.wait,
12437                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12438                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12439                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12440
12441
12442                 if (i915_sw_fence_done(&intel_state->commit_ready)
12443                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12444                         break;
12445
12446                 schedule();
12447         }
12448         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12449         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12450 }
12451
12452 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12453 {
12454         struct drm_device *dev = state->dev;
12455         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12456         struct drm_i915_private *dev_priv = to_i915(dev);
12457         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12458         struct drm_crtc *crtc;
12459         struct intel_crtc_state *intel_cstate;
12460         u64 put_domains[I915_MAX_PIPES] = {};
12461         int i;
12462
12463         intel_atomic_commit_fence_wait(intel_state);
12464
12465         drm_atomic_helper_wait_for_dependencies(state);
12466
12467         if (intel_state->modeset)
12468                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12469
12470         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12471                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12472
12473                 if (needs_modeset(new_crtc_state) ||
12474                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12475
12476                         put_domains[to_intel_crtc(crtc)->pipe] =
12477                                 modeset_get_crtc_power_domains(crtc,
12478                                         to_intel_crtc_state(new_crtc_state));
12479                 }
12480
12481                 if (!needs_modeset(new_crtc_state))
12482                         continue;
12483
12484                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12485                                        to_intel_crtc_state(new_crtc_state));
12486
12487                 if (old_crtc_state->active) {
12488                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12489
12490                         /*
12491                          * We need to disable pipe CRC before disabling the pipe,
12492                          * or we race against vblank off.
12493                          */
12494                         intel_crtc_disable_pipe_crc(intel_crtc);
12495
12496                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12497                         intel_crtc->active = false;
12498                         intel_fbc_disable(intel_crtc);
12499                         intel_disable_shared_dpll(intel_crtc);
12500
12501                         /*
12502                          * Underruns don't always raise
12503                          * interrupts, so check manually.
12504                          */
12505                         intel_check_cpu_fifo_underruns(dev_priv);
12506                         intel_check_pch_fifo_underruns(dev_priv);
12507
12508                         if (!new_crtc_state->active) {
12509                                 /*
12510                                  * Make sure we don't call initial_watermarks
12511                                  * for ILK-style watermark updates.
12512                                  *
12513                                  * No clue what this is supposed to achieve.
12514                                  */
12515                                 if (INTEL_GEN(dev_priv) >= 9)
12516                                         dev_priv->display.initial_watermarks(intel_state,
12517                                                                              to_intel_crtc_state(new_crtc_state));
12518                         }
12519                 }
12520         }
12521
12522         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12523         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12524                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12525
12526         if (intel_state->modeset) {
12527                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12528
12529                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12530
12531                 /*
12532                  * SKL workaround: bspec recommends we disable the SAGV when we
12533                  * have more then one pipe enabled
12534                  */
12535                 if (!intel_can_enable_sagv(state))
12536                         intel_disable_sagv(dev_priv);
12537
12538                 intel_modeset_verify_disabled(dev, state);
12539         }
12540
12541         /* Complete the events for pipes that have now been disabled */
12542         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12543                 bool modeset = needs_modeset(new_crtc_state);
12544
12545                 /* Complete events for now disable pipes here. */
12546                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12547                         spin_lock_irq(&dev->event_lock);
12548                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12549                         spin_unlock_irq(&dev->event_lock);
12550
12551                         new_crtc_state->event = NULL;
12552                 }
12553         }
12554
12555         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12556         dev_priv->display.update_crtcs(state);
12557
12558         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12559          * already, but still need the state for the delayed optimization. To
12560          * fix this:
12561          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12562          * - schedule that vblank worker _before_ calling hw_done
12563          * - at the start of commit_tail, cancel it _synchrously
12564          * - switch over to the vblank wait helper in the core after that since
12565          *   we don't need out special handling any more.
12566          */
12567         drm_atomic_helper_wait_for_flip_done(dev, state);
12568
12569         /*
12570          * Now that the vblank has passed, we can go ahead and program the
12571          * optimal watermarks on platforms that need two-step watermark
12572          * programming.
12573          *
12574          * TODO: Move this (and other cleanup) to an async worker eventually.
12575          */
12576         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12577                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12578
12579                 if (dev_priv->display.optimize_watermarks)
12580                         dev_priv->display.optimize_watermarks(intel_state,
12581                                                               intel_cstate);
12582         }
12583
12584         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12585                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12586
12587                 if (put_domains[i])
12588                         modeset_put_power_domains(dev_priv, put_domains[i]);
12589
12590                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12591         }
12592
12593         if (intel_state->modeset)
12594                 intel_verify_planes(intel_state);
12595
12596         if (intel_state->modeset && intel_can_enable_sagv(state))
12597                 intel_enable_sagv(dev_priv);
12598
12599         drm_atomic_helper_commit_hw_done(state);
12600
12601         if (intel_state->modeset) {
12602                 /* As one of the primary mmio accessors, KMS has a high
12603                  * likelihood of triggering bugs in unclaimed access. After we
12604                  * finish modesetting, see if an error has been flagged, and if
12605                  * so enable debugging for the next modeset - and hope we catch
12606                  * the culprit.
12607                  */
12608                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12609                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12610         }
12611
12612         drm_atomic_helper_cleanup_planes(dev, state);
12613
12614         drm_atomic_helper_commit_cleanup_done(state);
12615
12616         drm_atomic_state_put(state);
12617
12618         intel_atomic_helper_free_state(dev_priv);
12619 }
12620
12621 static void intel_atomic_commit_work(struct work_struct *work)
12622 {
12623         struct drm_atomic_state *state =
12624                 container_of(work, struct drm_atomic_state, commit_work);
12625
12626         intel_atomic_commit_tail(state);
12627 }
12628
12629 static int __i915_sw_fence_call
12630 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12631                           enum i915_sw_fence_notify notify)
12632 {
12633         struct intel_atomic_state *state =
12634                 container_of(fence, struct intel_atomic_state, commit_ready);
12635
12636         switch (notify) {
12637         case FENCE_COMPLETE:
12638                 /* we do blocking waits in the worker, nothing to do here */
12639                 break;
12640         case FENCE_FREE:
12641                 {
12642                         struct intel_atomic_helper *helper =
12643                                 &to_i915(state->base.dev)->atomic_helper;
12644
12645                         if (llist_add(&state->freed, &helper->free_list))
12646                                 schedule_work(&helper->free_work);
12647                         break;
12648                 }
12649         }
12650
12651         return NOTIFY_DONE;
12652 }
12653
12654 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12655 {
12656         struct drm_plane_state *old_plane_state, *new_plane_state;
12657         struct drm_plane *plane;
12658         int i;
12659
12660         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12661                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12662                                   intel_fb_obj(new_plane_state->fb),
12663                                   to_intel_plane(plane)->frontbuffer_bit);
12664 }
12665
12666 /**
12667  * intel_atomic_commit - commit validated state object
12668  * @dev: DRM device
12669  * @state: the top-level driver state object
12670  * @nonblock: nonblocking commit
12671  *
12672  * This function commits a top-level state object that has been validated
12673  * with drm_atomic_helper_check().
12674  *
12675  * RETURNS
12676  * Zero for success or -errno.
12677  */
12678 static int intel_atomic_commit(struct drm_device *dev,
12679                                struct drm_atomic_state *state,
12680                                bool nonblock)
12681 {
12682         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12683         struct drm_i915_private *dev_priv = to_i915(dev);
12684         int ret = 0;
12685
12686         drm_atomic_state_get(state);
12687         i915_sw_fence_init(&intel_state->commit_ready,
12688                            intel_atomic_commit_ready);
12689
12690         /*
12691          * The intel_legacy_cursor_update() fast path takes care
12692          * of avoiding the vblank waits for simple cursor
12693          * movement and flips. For cursor on/off and size changes,
12694          * we want to perform the vblank waits so that watermark
12695          * updates happen during the correct frames. Gen9+ have
12696          * double buffered watermarks and so shouldn't need this.
12697          *
12698          * Unset state->legacy_cursor_update before the call to
12699          * drm_atomic_helper_setup_commit() because otherwise
12700          * drm_atomic_helper_wait_for_flip_done() is a noop and
12701          * we get FIFO underruns because we didn't wait
12702          * for vblank.
12703          *
12704          * FIXME doing watermarks and fb cleanup from a vblank worker
12705          * (assuming we had any) would solve these problems.
12706          */
12707         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12708                 struct intel_crtc_state *new_crtc_state;
12709                 struct intel_crtc *crtc;
12710                 int i;
12711
12712                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12713                         if (new_crtc_state->wm.need_postvbl_update ||
12714                             new_crtc_state->update_wm_post)
12715                                 state->legacy_cursor_update = false;
12716         }
12717
12718         ret = intel_atomic_prepare_commit(dev, state);
12719         if (ret) {
12720                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12721                 i915_sw_fence_commit(&intel_state->commit_ready);
12722                 return ret;
12723         }
12724
12725         ret = drm_atomic_helper_setup_commit(state, nonblock);
12726         if (!ret)
12727                 ret = drm_atomic_helper_swap_state(state, true);
12728
12729         if (ret) {
12730                 i915_sw_fence_commit(&intel_state->commit_ready);
12731
12732                 drm_atomic_helper_cleanup_planes(dev, state);
12733                 return ret;
12734         }
12735         dev_priv->wm.distrust_bios_wm = false;
12736         intel_shared_dpll_swap_state(state);
12737         intel_atomic_track_fbs(state);
12738
12739         if (intel_state->modeset) {
12740                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12741                        sizeof(intel_state->min_cdclk));
12742                 memcpy(dev_priv->min_voltage_level,
12743                        intel_state->min_voltage_level,
12744                        sizeof(intel_state->min_voltage_level));
12745                 dev_priv->active_crtcs = intel_state->active_crtcs;
12746                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12747                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12748         }
12749
12750         drm_atomic_state_get(state);
12751         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12752
12753         i915_sw_fence_commit(&intel_state->commit_ready);
12754         if (nonblock && intel_state->modeset) {
12755                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12756         } else if (nonblock) {
12757                 queue_work(system_unbound_wq, &state->commit_work);
12758         } else {
12759                 if (intel_state->modeset)
12760                         flush_workqueue(dev_priv->modeset_wq);
12761                 intel_atomic_commit_tail(state);
12762         }
12763
12764         return 0;
12765 }
12766
12767 static const struct drm_crtc_funcs intel_crtc_funcs = {
12768         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12769         .set_config = drm_atomic_helper_set_config,
12770         .destroy = intel_crtc_destroy,
12771         .page_flip = drm_atomic_helper_page_flip,
12772         .atomic_duplicate_state = intel_crtc_duplicate_state,
12773         .atomic_destroy_state = intel_crtc_destroy_state,
12774         .set_crc_source = intel_crtc_set_crc_source,
12775 };
12776
12777 struct wait_rps_boost {
12778         struct wait_queue_entry wait;
12779
12780         struct drm_crtc *crtc;
12781         struct i915_request *request;
12782 };
12783
12784 static int do_rps_boost(struct wait_queue_entry *_wait,
12785                         unsigned mode, int sync, void *key)
12786 {
12787         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12788         struct i915_request *rq = wait->request;
12789
12790         /*
12791          * If we missed the vblank, but the request is already running it
12792          * is reasonable to assume that it will complete before the next
12793          * vblank without our intervention, so leave RPS alone.
12794          */
12795         if (!i915_request_started(rq))
12796                 gen6_rps_boost(rq, NULL);
12797         i915_request_put(rq);
12798
12799         drm_crtc_vblank_put(wait->crtc);
12800
12801         list_del(&wait->wait.entry);
12802         kfree(wait);
12803         return 1;
12804 }
12805
12806 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12807                                        struct dma_fence *fence)
12808 {
12809         struct wait_rps_boost *wait;
12810
12811         if (!dma_fence_is_i915(fence))
12812                 return;
12813
12814         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12815                 return;
12816
12817         if (drm_crtc_vblank_get(crtc))
12818                 return;
12819
12820         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12821         if (!wait) {
12822                 drm_crtc_vblank_put(crtc);
12823                 return;
12824         }
12825
12826         wait->request = to_request(dma_fence_get(fence));
12827         wait->crtc = crtc;
12828
12829         wait->wait.func = do_rps_boost;
12830         wait->wait.flags = 0;
12831
12832         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12833 }
12834
12835 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
12836 {
12837         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
12838         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12839         struct drm_framebuffer *fb = plane_state->base.fb;
12840         struct i915_vma *vma;
12841
12842         if (plane->id == PLANE_CURSOR &&
12843             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12844                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12845                 const int align = intel_cursor_alignment(dev_priv);
12846
12847                 return i915_gem_object_attach_phys(obj, align);
12848         }
12849
12850         vma = intel_pin_and_fence_fb_obj(fb,
12851                                          plane_state->base.rotation,
12852                                          intel_plane_uses_fence(plane_state),
12853                                          &plane_state->flags);
12854         if (IS_ERR(vma))
12855                 return PTR_ERR(vma);
12856
12857         plane_state->vma = vma;
12858
12859         return 0;
12860 }
12861
12862 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
12863 {
12864         struct i915_vma *vma;
12865
12866         vma = fetch_and_zero(&old_plane_state->vma);
12867         if (vma)
12868                 intel_unpin_fb_vma(vma, old_plane_state->flags);
12869 }
12870
12871 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
12872 {
12873         struct i915_sched_attr attr = {
12874                 .priority = I915_PRIORITY_DISPLAY,
12875         };
12876
12877         i915_gem_object_wait_priority(obj, 0, &attr);
12878 }
12879
12880 /**
12881  * intel_prepare_plane_fb - Prepare fb for usage on plane
12882  * @plane: drm plane to prepare for
12883  * @new_state: the plane state being prepared
12884  *
12885  * Prepares a framebuffer for usage on a display plane.  Generally this
12886  * involves pinning the underlying object and updating the frontbuffer tracking
12887  * bits.  Some older platforms need special physical address handling for
12888  * cursor planes.
12889  *
12890  * Must be called with struct_mutex held.
12891  *
12892  * Returns 0 on success, negative error code on failure.
12893  */
12894 int
12895 intel_prepare_plane_fb(struct drm_plane *plane,
12896                        struct drm_plane_state *new_state)
12897 {
12898         struct intel_atomic_state *intel_state =
12899                 to_intel_atomic_state(new_state->state);
12900         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12901         struct drm_framebuffer *fb = new_state->fb;
12902         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12903         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
12904         int ret;
12905
12906         if (old_obj) {
12907                 struct drm_crtc_state *crtc_state =
12908                         drm_atomic_get_new_crtc_state(new_state->state,
12909                                                       plane->state->crtc);
12910
12911                 /* Big Hammer, we also need to ensure that any pending
12912                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
12913                  * current scanout is retired before unpinning the old
12914                  * framebuffer. Note that we rely on userspace rendering
12915                  * into the buffer attached to the pipe they are waiting
12916                  * on. If not, userspace generates a GPU hang with IPEHR
12917                  * point to the MI_WAIT_FOR_EVENT.
12918                  *
12919                  * This should only fail upon a hung GPU, in which case we
12920                  * can safely continue.
12921                  */
12922                 if (needs_modeset(crtc_state)) {
12923                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12924                                                               old_obj->resv, NULL,
12925                                                               false, 0,
12926                                                               GFP_KERNEL);
12927                         if (ret < 0)
12928                                 return ret;
12929                 }
12930         }
12931
12932         if (new_state->fence) { /* explicit fencing */
12933                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
12934                                                     new_state->fence,
12935                                                     I915_FENCE_TIMEOUT,
12936                                                     GFP_KERNEL);
12937                 if (ret < 0)
12938                         return ret;
12939         }
12940
12941         if (!obj)
12942                 return 0;
12943
12944         ret = i915_gem_object_pin_pages(obj);
12945         if (ret)
12946                 return ret;
12947
12948         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
12949         if (ret) {
12950                 i915_gem_object_unpin_pages(obj);
12951                 return ret;
12952         }
12953
12954         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
12955
12956         fb_obj_bump_render_priority(obj);
12957
12958         mutex_unlock(&dev_priv->drm.struct_mutex);
12959         i915_gem_object_unpin_pages(obj);
12960         if (ret)
12961                 return ret;
12962
12963         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
12964
12965         if (!new_state->fence) { /* implicit fencing */
12966                 struct dma_fence *fence;
12967
12968                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12969                                                       obj->resv, NULL,
12970                                                       false, I915_FENCE_TIMEOUT,
12971                                                       GFP_KERNEL);
12972                 if (ret < 0)
12973                         return ret;
12974
12975                 fence = reservation_object_get_excl_rcu(obj->resv);
12976                 if (fence) {
12977                         add_rps_boost_after_vblank(new_state->crtc, fence);
12978                         dma_fence_put(fence);
12979                 }
12980         } else {
12981                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
12982         }
12983
12984         return 0;
12985 }
12986
12987 /**
12988  * intel_cleanup_plane_fb - Cleans up an fb after plane use
12989  * @plane: drm plane to clean up for
12990  * @old_state: the state from the previous modeset
12991  *
12992  * Cleans up a framebuffer that has just been removed from a plane.
12993  *
12994  * Must be called with struct_mutex held.
12995  */
12996 void
12997 intel_cleanup_plane_fb(struct drm_plane *plane,
12998                        struct drm_plane_state *old_state)
12999 {
13000         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13001
13002         /* Should only be called after a successful intel_prepare_plane_fb()! */
13003         mutex_lock(&dev_priv->drm.struct_mutex);
13004         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13005         mutex_unlock(&dev_priv->drm.struct_mutex);
13006 }
13007
13008 int
13009 skl_max_scale(struct intel_crtc *intel_crtc,
13010               struct intel_crtc_state *crtc_state,
13011               uint32_t pixel_format)
13012 {
13013         struct drm_i915_private *dev_priv;
13014         int max_scale, mult;
13015         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13016
13017         if (!intel_crtc || !crtc_state->base.enable)
13018                 return DRM_PLANE_HELPER_NO_SCALING;
13019
13020         dev_priv = to_i915(intel_crtc->base.dev);
13021
13022         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13023         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13024
13025         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13026                 max_dotclk *= 2;
13027
13028         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13029                 return DRM_PLANE_HELPER_NO_SCALING;
13030
13031         /*
13032          * skl max scale is lower of:
13033          *    close to 3 but not 3, -1 is for that purpose
13034          *            or
13035          *    cdclk/crtc_clock
13036          */
13037         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13038         tmpclk1 = (1 << 16) * mult - 1;
13039         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13040         max_scale = min(tmpclk1, tmpclk2);
13041
13042         return max_scale;
13043 }
13044
13045 static int
13046 intel_check_primary_plane(struct intel_plane *plane,
13047                           struct intel_crtc_state *crtc_state,
13048                           struct intel_plane_state *state)
13049 {
13050         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13051         struct drm_crtc *crtc = state->base.crtc;
13052         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13053         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13054         bool can_position = false;
13055         int ret;
13056         uint32_t pixel_format = 0;
13057
13058         if (INTEL_GEN(dev_priv) >= 9) {
13059                 /* use scaler when colorkey is not required */
13060                 if (!state->ckey.flags) {
13061                         min_scale = 1;
13062                         if (state->base.fb)
13063                                 pixel_format = state->base.fb->format->format;
13064                         max_scale = skl_max_scale(to_intel_crtc(crtc),
13065                                                   crtc_state, pixel_format);
13066                 }
13067                 can_position = true;
13068         }
13069
13070         ret = drm_atomic_helper_check_plane_state(&state->base,
13071                                                   &crtc_state->base,
13072                                                   min_scale, max_scale,
13073                                                   can_position, true);
13074         if (ret)
13075                 return ret;
13076
13077         if (!state->base.fb)
13078                 return 0;
13079
13080         if (INTEL_GEN(dev_priv) >= 9) {
13081                 ret = skl_check_plane_surface(crtc_state, state);
13082                 if (ret)
13083                         return ret;
13084
13085                 state->ctl = skl_plane_ctl(crtc_state, state);
13086         } else {
13087                 ret = i9xx_check_plane_surface(state);
13088                 if (ret)
13089                         return ret;
13090
13091                 state->ctl = i9xx_plane_ctl(crtc_state, state);
13092         }
13093
13094         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
13095                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
13096
13097         return 0;
13098 }
13099
13100 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13101                                     struct drm_crtc_state *old_crtc_state)
13102 {
13103         struct drm_device *dev = crtc->dev;
13104         struct drm_i915_private *dev_priv = to_i915(dev);
13105         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13106         struct intel_crtc_state *old_intel_cstate =
13107                 to_intel_crtc_state(old_crtc_state);
13108         struct intel_atomic_state *old_intel_state =
13109                 to_intel_atomic_state(old_crtc_state->state);
13110         struct intel_crtc_state *intel_cstate =
13111                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13112         bool modeset = needs_modeset(&intel_cstate->base);
13113
13114         if (!modeset &&
13115             (intel_cstate->base.color_mgmt_changed ||
13116              intel_cstate->update_pipe)) {
13117                 intel_color_set_csc(&intel_cstate->base);
13118                 intel_color_load_luts(&intel_cstate->base);
13119         }
13120
13121         /* Perform vblank evasion around commit operation */
13122         intel_pipe_update_start(intel_cstate);
13123
13124         if (modeset)
13125                 goto out;
13126
13127         if (intel_cstate->update_pipe)
13128                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13129         else if (INTEL_GEN(dev_priv) >= 9)
13130                 skl_detach_scalers(intel_crtc);
13131
13132 out:
13133         if (dev_priv->display.atomic_update_watermarks)
13134                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13135                                                            intel_cstate);
13136 }
13137
13138 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13139                                   struct intel_crtc_state *crtc_state)
13140 {
13141         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13142
13143         if (!IS_GEN2(dev_priv))
13144                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13145
13146         if (crtc_state->has_pch_encoder) {
13147                 enum pipe pch_transcoder =
13148                         intel_crtc_pch_transcoder(crtc);
13149
13150                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13151         }
13152 }
13153
13154 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13155                                      struct drm_crtc_state *old_crtc_state)
13156 {
13157         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13158         struct intel_atomic_state *old_intel_state =
13159                 to_intel_atomic_state(old_crtc_state->state);
13160         struct intel_crtc_state *new_crtc_state =
13161                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13162
13163         intel_pipe_update_end(new_crtc_state);
13164
13165         if (new_crtc_state->update_pipe &&
13166             !needs_modeset(&new_crtc_state->base) &&
13167             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13168                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13169 }
13170
13171 /**
13172  * intel_plane_destroy - destroy a plane
13173  * @plane: plane to destroy
13174  *
13175  * Common destruction function for all types of planes (primary, cursor,
13176  * sprite).
13177  */
13178 void intel_plane_destroy(struct drm_plane *plane)
13179 {
13180         drm_plane_cleanup(plane);
13181         kfree(to_intel_plane(plane));
13182 }
13183
13184 static bool i8xx_mod_supported(uint32_t format, uint64_t modifier)
13185 {
13186         switch (format) {
13187         case DRM_FORMAT_C8:
13188         case DRM_FORMAT_RGB565:
13189         case DRM_FORMAT_XRGB1555:
13190         case DRM_FORMAT_XRGB8888:
13191                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13192                         modifier == I915_FORMAT_MOD_X_TILED;
13193         default:
13194                 return false;
13195         }
13196 }
13197
13198 static bool i965_mod_supported(uint32_t format, uint64_t modifier)
13199 {
13200         switch (format) {
13201         case DRM_FORMAT_C8:
13202         case DRM_FORMAT_RGB565:
13203         case DRM_FORMAT_XRGB8888:
13204         case DRM_FORMAT_XBGR8888:
13205         case DRM_FORMAT_XRGB2101010:
13206         case DRM_FORMAT_XBGR2101010:
13207                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13208                         modifier == I915_FORMAT_MOD_X_TILED;
13209         default:
13210                 return false;
13211         }
13212 }
13213
13214 static bool skl_mod_supported(uint32_t format, uint64_t modifier)
13215 {
13216         switch (format) {
13217         case DRM_FORMAT_XRGB8888:
13218         case DRM_FORMAT_XBGR8888:
13219         case DRM_FORMAT_ARGB8888:
13220         case DRM_FORMAT_ABGR8888:
13221                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
13222                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
13223                         return true;
13224                 /* fall through */
13225         case DRM_FORMAT_RGB565:
13226         case DRM_FORMAT_XRGB2101010:
13227         case DRM_FORMAT_XBGR2101010:
13228         case DRM_FORMAT_YUYV:
13229         case DRM_FORMAT_YVYU:
13230         case DRM_FORMAT_UYVY:
13231         case DRM_FORMAT_VYUY:
13232         case DRM_FORMAT_NV12:
13233                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13234                         return true;
13235                 /* fall through */
13236         case DRM_FORMAT_C8:
13237                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13238                     modifier == I915_FORMAT_MOD_X_TILED ||
13239                     modifier == I915_FORMAT_MOD_Y_TILED)
13240                         return true;
13241                 /* fall through */
13242         default:
13243                 return false;
13244         }
13245 }
13246
13247 static bool intel_primary_plane_format_mod_supported(struct drm_plane *plane,
13248                                                      uint32_t format,
13249                                                      uint64_t modifier)
13250 {
13251         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13252
13253         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13254                 return false;
13255
13256         if ((modifier >> 56) != DRM_FORMAT_MOD_VENDOR_INTEL &&
13257             modifier != DRM_FORMAT_MOD_LINEAR)
13258                 return false;
13259
13260         if (INTEL_GEN(dev_priv) >= 9)
13261                 return skl_mod_supported(format, modifier);
13262         else if (INTEL_GEN(dev_priv) >= 4)
13263                 return i965_mod_supported(format, modifier);
13264         else
13265                 return i8xx_mod_supported(format, modifier);
13266 }
13267
13268 static bool intel_cursor_plane_format_mod_supported(struct drm_plane *plane,
13269                                                     uint32_t format,
13270                                                     uint64_t modifier)
13271 {
13272         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13273                 return false;
13274
13275         return modifier == DRM_FORMAT_MOD_LINEAR && format == DRM_FORMAT_ARGB8888;
13276 }
13277
13278 static struct drm_plane_funcs intel_plane_funcs = {
13279         .update_plane = drm_atomic_helper_update_plane,
13280         .disable_plane = drm_atomic_helper_disable_plane,
13281         .destroy = intel_plane_destroy,
13282         .atomic_get_property = intel_plane_atomic_get_property,
13283         .atomic_set_property = intel_plane_atomic_set_property,
13284         .atomic_duplicate_state = intel_plane_duplicate_state,
13285         .atomic_destroy_state = intel_plane_destroy_state,
13286         .format_mod_supported = intel_primary_plane_format_mod_supported,
13287 };
13288
13289 static int
13290 intel_legacy_cursor_update(struct drm_plane *plane,
13291                            struct drm_crtc *crtc,
13292                            struct drm_framebuffer *fb,
13293                            int crtc_x, int crtc_y,
13294                            unsigned int crtc_w, unsigned int crtc_h,
13295                            uint32_t src_x, uint32_t src_y,
13296                            uint32_t src_w, uint32_t src_h,
13297                            struct drm_modeset_acquire_ctx *ctx)
13298 {
13299         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13300         int ret;
13301         struct drm_plane_state *old_plane_state, *new_plane_state;
13302         struct intel_plane *intel_plane = to_intel_plane(plane);
13303         struct drm_framebuffer *old_fb;
13304         struct drm_crtc_state *crtc_state = crtc->state;
13305
13306         /*
13307          * When crtc is inactive or there is a modeset pending,
13308          * wait for it to complete in the slowpath
13309          */
13310         if (!crtc_state->active || needs_modeset(crtc_state) ||
13311             to_intel_crtc_state(crtc_state)->update_pipe)
13312                 goto slow;
13313
13314         old_plane_state = plane->state;
13315         /*
13316          * Don't do an async update if there is an outstanding commit modifying
13317          * the plane.  This prevents our async update's changes from getting
13318          * overridden by a previous synchronous update's state.
13319          */
13320         if (old_plane_state->commit &&
13321             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13322                 goto slow;
13323
13324         /*
13325          * If any parameters change that may affect watermarks,
13326          * take the slowpath. Only changing fb or position should be
13327          * in the fastpath.
13328          */
13329         if (old_plane_state->crtc != crtc ||
13330             old_plane_state->src_w != src_w ||
13331             old_plane_state->src_h != src_h ||
13332             old_plane_state->crtc_w != crtc_w ||
13333             old_plane_state->crtc_h != crtc_h ||
13334             !old_plane_state->fb != !fb)
13335                 goto slow;
13336
13337         new_plane_state = intel_plane_duplicate_state(plane);
13338         if (!new_plane_state)
13339                 return -ENOMEM;
13340
13341         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13342
13343         new_plane_state->src_x = src_x;
13344         new_plane_state->src_y = src_y;
13345         new_plane_state->src_w = src_w;
13346         new_plane_state->src_h = src_h;
13347         new_plane_state->crtc_x = crtc_x;
13348         new_plane_state->crtc_y = crtc_y;
13349         new_plane_state->crtc_w = crtc_w;
13350         new_plane_state->crtc_h = crtc_h;
13351
13352         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13353                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13354                                                   to_intel_plane_state(plane->state),
13355                                                   to_intel_plane_state(new_plane_state));
13356         if (ret)
13357                 goto out_free;
13358
13359         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13360         if (ret)
13361                 goto out_free;
13362
13363         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13364         if (ret)
13365                 goto out_unlock;
13366
13367         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13368
13369         old_fb = old_plane_state->fb;
13370         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13371                           intel_plane->frontbuffer_bit);
13372
13373         /* Swap plane state */
13374         plane->state = new_plane_state;
13375
13376         if (plane->state->visible) {
13377                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13378                 intel_plane->update_plane(intel_plane,
13379                                           to_intel_crtc_state(crtc->state),
13380                                           to_intel_plane_state(plane->state));
13381         } else {
13382                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13383                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13384         }
13385
13386         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13387
13388 out_unlock:
13389         mutex_unlock(&dev_priv->drm.struct_mutex);
13390 out_free:
13391         if (ret)
13392                 intel_plane_destroy_state(plane, new_plane_state);
13393         else
13394                 intel_plane_destroy_state(plane, old_plane_state);
13395         return ret;
13396
13397 slow:
13398         return drm_atomic_helper_update_plane(plane, crtc, fb,
13399                                               crtc_x, crtc_y, crtc_w, crtc_h,
13400                                               src_x, src_y, src_w, src_h, ctx);
13401 }
13402
13403 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13404         .update_plane = intel_legacy_cursor_update,
13405         .disable_plane = drm_atomic_helper_disable_plane,
13406         .destroy = intel_plane_destroy,
13407         .atomic_get_property = intel_plane_atomic_get_property,
13408         .atomic_set_property = intel_plane_atomic_set_property,
13409         .atomic_duplicate_state = intel_plane_duplicate_state,
13410         .atomic_destroy_state = intel_plane_destroy_state,
13411         .format_mod_supported = intel_cursor_plane_format_mod_supported,
13412 };
13413
13414 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13415                                enum i9xx_plane_id i9xx_plane)
13416 {
13417         if (!HAS_FBC(dev_priv))
13418                 return false;
13419
13420         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13421                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13422         else if (IS_IVYBRIDGE(dev_priv))
13423                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13424                         i9xx_plane == PLANE_C;
13425         else if (INTEL_GEN(dev_priv) >= 4)
13426                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13427         else
13428                 return i9xx_plane == PLANE_A;
13429 }
13430
13431 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13432                               enum pipe pipe, enum plane_id plane_id)
13433 {
13434         if (!HAS_FBC(dev_priv))
13435                 return false;
13436
13437         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13438 }
13439
13440 bool skl_plane_has_planar(struct drm_i915_private *dev_priv,
13441                           enum pipe pipe, enum plane_id plane_id)
13442 {
13443         if (plane_id == PLANE_PRIMARY) {
13444                 if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
13445                         return false;
13446                 else if ((INTEL_GEN(dev_priv) == 9 && pipe == PIPE_C) &&
13447                          !IS_GEMINILAKE(dev_priv))
13448                         return false;
13449         } else if (plane_id >= PLANE_SPRITE0) {
13450                 if (plane_id == PLANE_CURSOR)
13451                         return false;
13452                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) == 10) {
13453                         if (plane_id != PLANE_SPRITE0)
13454                                 return false;
13455                 } else {
13456                         if (plane_id != PLANE_SPRITE0 || pipe == PIPE_C ||
13457                             IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
13458                                 return false;
13459                 }
13460         }
13461         return true;
13462 }
13463
13464 static struct intel_plane *
13465 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13466 {
13467         struct intel_plane *primary = NULL;
13468         struct intel_plane_state *state = NULL;
13469         const uint32_t *intel_primary_formats;
13470         unsigned int supported_rotations;
13471         unsigned int num_formats;
13472         const uint64_t *modifiers;
13473         int ret;
13474
13475         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13476         if (!primary) {
13477                 ret = -ENOMEM;
13478                 goto fail;
13479         }
13480
13481         state = intel_create_plane_state(&primary->base);
13482         if (!state) {
13483                 ret = -ENOMEM;
13484                 goto fail;
13485         }
13486
13487         primary->base.state = &state->base;
13488
13489         primary->can_scale = false;
13490         primary->max_downscale = 1;
13491         if (INTEL_GEN(dev_priv) >= 9) {
13492                 primary->can_scale = true;
13493                 state->scaler_id = -1;
13494         }
13495         primary->pipe = pipe;
13496         /*
13497          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13498          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13499          */
13500         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13501                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13502         else
13503                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13504         primary->id = PLANE_PRIMARY;
13505         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13506
13507         if (INTEL_GEN(dev_priv) >= 9)
13508                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13509                                                      primary->pipe,
13510                                                      primary->id);
13511         else
13512                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13513                                                       primary->i9xx_plane);
13514
13515         if (primary->has_fbc) {
13516                 struct intel_fbc *fbc = &dev_priv->fbc;
13517
13518                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13519         }
13520
13521         primary->check_plane = intel_check_primary_plane;
13522
13523         if (INTEL_GEN(dev_priv) >= 9) {
13524                 if (skl_plane_has_planar(dev_priv, pipe, PLANE_PRIMARY)) {
13525                         intel_primary_formats = skl_pri_planar_formats;
13526                         num_formats = ARRAY_SIZE(skl_pri_planar_formats);
13527                 } else {
13528                         intel_primary_formats = skl_primary_formats;
13529                         num_formats = ARRAY_SIZE(skl_primary_formats);
13530                 }
13531
13532                 if (skl_plane_has_ccs(dev_priv, pipe, PLANE_PRIMARY))
13533                         modifiers = skl_format_modifiers_ccs;
13534                 else
13535                         modifiers = skl_format_modifiers_noccs;
13536
13537                 primary->update_plane = skl_update_plane;
13538                 primary->disable_plane = skl_disable_plane;
13539                 primary->get_hw_state = skl_plane_get_hw_state;
13540         } else if (INTEL_GEN(dev_priv) >= 4) {
13541                 intel_primary_formats = i965_primary_formats;
13542                 num_formats = ARRAY_SIZE(i965_primary_formats);
13543                 modifiers = i9xx_format_modifiers;
13544
13545                 primary->update_plane = i9xx_update_plane;
13546                 primary->disable_plane = i9xx_disable_plane;
13547                 primary->get_hw_state = i9xx_plane_get_hw_state;
13548         } else {
13549                 intel_primary_formats = i8xx_primary_formats;
13550                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13551                 modifiers = i9xx_format_modifiers;
13552
13553                 primary->update_plane = i9xx_update_plane;
13554                 primary->disable_plane = i9xx_disable_plane;
13555                 primary->get_hw_state = i9xx_plane_get_hw_state;
13556         }
13557
13558         if (INTEL_GEN(dev_priv) >= 9)
13559                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13560                                                0, &intel_plane_funcs,
13561                                                intel_primary_formats, num_formats,
13562                                                modifiers,
13563                                                DRM_PLANE_TYPE_PRIMARY,
13564                                                "plane 1%c", pipe_name(pipe));
13565         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13566                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13567                                                0, &intel_plane_funcs,
13568                                                intel_primary_formats, num_formats,
13569                                                modifiers,
13570                                                DRM_PLANE_TYPE_PRIMARY,
13571                                                "primary %c", pipe_name(pipe));
13572         else
13573                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13574                                                0, &intel_plane_funcs,
13575                                                intel_primary_formats, num_formats,
13576                                                modifiers,
13577                                                DRM_PLANE_TYPE_PRIMARY,
13578                                                "plane %c",
13579                                                plane_name(primary->i9xx_plane));
13580         if (ret)
13581                 goto fail;
13582
13583         if (INTEL_GEN(dev_priv) >= 10) {
13584                 supported_rotations =
13585                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13586                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13587                         DRM_MODE_REFLECT_X;
13588         } else if (INTEL_GEN(dev_priv) >= 9) {
13589                 supported_rotations =
13590                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13591                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13592         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13593                 supported_rotations =
13594                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13595                         DRM_MODE_REFLECT_X;
13596         } else if (INTEL_GEN(dev_priv) >= 4) {
13597                 supported_rotations =
13598                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13599         } else {
13600                 supported_rotations = DRM_MODE_ROTATE_0;
13601         }
13602
13603         if (INTEL_GEN(dev_priv) >= 4)
13604                 drm_plane_create_rotation_property(&primary->base,
13605                                                    DRM_MODE_ROTATE_0,
13606                                                    supported_rotations);
13607
13608         if (INTEL_GEN(dev_priv) >= 9)
13609                 drm_plane_create_color_properties(&primary->base,
13610                                                   BIT(DRM_COLOR_YCBCR_BT601) |
13611                                                   BIT(DRM_COLOR_YCBCR_BT709),
13612                                                   BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
13613                                                   BIT(DRM_COLOR_YCBCR_FULL_RANGE),
13614                                                   DRM_COLOR_YCBCR_BT709,
13615                                                   DRM_COLOR_YCBCR_LIMITED_RANGE);
13616
13617         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13618
13619         return primary;
13620
13621 fail:
13622         kfree(state);
13623         kfree(primary);
13624
13625         return ERR_PTR(ret);
13626 }
13627
13628 static struct intel_plane *
13629 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13630                           enum pipe pipe)
13631 {
13632         struct intel_plane *cursor = NULL;
13633         struct intel_plane_state *state = NULL;
13634         int ret;
13635
13636         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13637         if (!cursor) {
13638                 ret = -ENOMEM;
13639                 goto fail;
13640         }
13641
13642         state = intel_create_plane_state(&cursor->base);
13643         if (!state) {
13644                 ret = -ENOMEM;
13645                 goto fail;
13646         }
13647
13648         cursor->base.state = &state->base;
13649
13650         cursor->can_scale = false;
13651         cursor->max_downscale = 1;
13652         cursor->pipe = pipe;
13653         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13654         cursor->id = PLANE_CURSOR;
13655         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13656
13657         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13658                 cursor->update_plane = i845_update_cursor;
13659                 cursor->disable_plane = i845_disable_cursor;
13660                 cursor->get_hw_state = i845_cursor_get_hw_state;
13661                 cursor->check_plane = i845_check_cursor;
13662         } else {
13663                 cursor->update_plane = i9xx_update_cursor;
13664                 cursor->disable_plane = i9xx_disable_cursor;
13665                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13666                 cursor->check_plane = i9xx_check_cursor;
13667         }
13668
13669         cursor->cursor.base = ~0;
13670         cursor->cursor.cntl = ~0;
13671
13672         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13673                 cursor->cursor.size = ~0;
13674
13675         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13676                                        0, &intel_cursor_plane_funcs,
13677                                        intel_cursor_formats,
13678                                        ARRAY_SIZE(intel_cursor_formats),
13679                                        cursor_format_modifiers,
13680                                        DRM_PLANE_TYPE_CURSOR,
13681                                        "cursor %c", pipe_name(pipe));
13682         if (ret)
13683                 goto fail;
13684
13685         if (INTEL_GEN(dev_priv) >= 4)
13686                 drm_plane_create_rotation_property(&cursor->base,
13687                                                    DRM_MODE_ROTATE_0,
13688                                                    DRM_MODE_ROTATE_0 |
13689                                                    DRM_MODE_ROTATE_180);
13690
13691         if (INTEL_GEN(dev_priv) >= 9)
13692                 state->scaler_id = -1;
13693
13694         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13695
13696         return cursor;
13697
13698 fail:
13699         kfree(state);
13700         kfree(cursor);
13701
13702         return ERR_PTR(ret);
13703 }
13704
13705 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13706                                     struct intel_crtc_state *crtc_state)
13707 {
13708         struct intel_crtc_scaler_state *scaler_state =
13709                 &crtc_state->scaler_state;
13710         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13711         int i;
13712
13713         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13714         if (!crtc->num_scalers)
13715                 return;
13716
13717         for (i = 0; i < crtc->num_scalers; i++) {
13718                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13719
13720                 scaler->in_use = 0;
13721                 scaler->mode = PS_SCALER_MODE_DYN;
13722         }
13723
13724         scaler_state->scaler_id = -1;
13725 }
13726
13727 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13728 {
13729         struct intel_crtc *intel_crtc;
13730         struct intel_crtc_state *crtc_state = NULL;
13731         struct intel_plane *primary = NULL;
13732         struct intel_plane *cursor = NULL;
13733         int sprite, ret;
13734
13735         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13736         if (!intel_crtc)
13737                 return -ENOMEM;
13738
13739         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13740         if (!crtc_state) {
13741                 ret = -ENOMEM;
13742                 goto fail;
13743         }
13744         intel_crtc->config = crtc_state;
13745         intel_crtc->base.state = &crtc_state->base;
13746         crtc_state->base.crtc = &intel_crtc->base;
13747
13748         primary = intel_primary_plane_create(dev_priv, pipe);
13749         if (IS_ERR(primary)) {
13750                 ret = PTR_ERR(primary);
13751                 goto fail;
13752         }
13753         intel_crtc->plane_ids_mask |= BIT(primary->id);
13754
13755         for_each_sprite(dev_priv, pipe, sprite) {
13756                 struct intel_plane *plane;
13757
13758                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13759                 if (IS_ERR(plane)) {
13760                         ret = PTR_ERR(plane);
13761                         goto fail;
13762                 }
13763                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13764         }
13765
13766         cursor = intel_cursor_plane_create(dev_priv, pipe);
13767         if (IS_ERR(cursor)) {
13768                 ret = PTR_ERR(cursor);
13769                 goto fail;
13770         }
13771         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13772
13773         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13774                                         &primary->base, &cursor->base,
13775                                         &intel_crtc_funcs,
13776                                         "pipe %c", pipe_name(pipe));
13777         if (ret)
13778                 goto fail;
13779
13780         intel_crtc->pipe = pipe;
13781
13782         /* initialize shared scalers */
13783         intel_crtc_init_scalers(intel_crtc, crtc_state);
13784
13785         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
13786                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
13787         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
13788
13789         if (INTEL_GEN(dev_priv) < 9) {
13790                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
13791
13792                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13793                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
13794                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
13795         }
13796
13797         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13798
13799         intel_color_init(&intel_crtc->base);
13800
13801         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13802
13803         return 0;
13804
13805 fail:
13806         /*
13807          * drm_mode_config_cleanup() will free up any
13808          * crtcs/planes already initialized.
13809          */
13810         kfree(crtc_state);
13811         kfree(intel_crtc);
13812
13813         return ret;
13814 }
13815
13816 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13817 {
13818         struct drm_device *dev = connector->base.dev;
13819
13820         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13821
13822         if (!connector->base.state->crtc)
13823                 return INVALID_PIPE;
13824
13825         return to_intel_crtc(connector->base.state->crtc)->pipe;
13826 }
13827
13828 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
13829                                       struct drm_file *file)
13830 {
13831         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13832         struct drm_crtc *drmmode_crtc;
13833         struct intel_crtc *crtc;
13834
13835         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13836         if (!drmmode_crtc)
13837                 return -ENOENT;
13838
13839         crtc = to_intel_crtc(drmmode_crtc);
13840         pipe_from_crtc_id->pipe = crtc->pipe;
13841
13842         return 0;
13843 }
13844
13845 static int intel_encoder_clones(struct intel_encoder *encoder)
13846 {
13847         struct drm_device *dev = encoder->base.dev;
13848         struct intel_encoder *source_encoder;
13849         int index_mask = 0;
13850         int entry = 0;
13851
13852         for_each_intel_encoder(dev, source_encoder) {
13853                 if (encoders_cloneable(encoder, source_encoder))
13854                         index_mask |= (1 << entry);
13855
13856                 entry++;
13857         }
13858
13859         return index_mask;
13860 }
13861
13862 static bool has_edp_a(struct drm_i915_private *dev_priv)
13863 {
13864         if (!IS_MOBILE(dev_priv))
13865                 return false;
13866
13867         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13868                 return false;
13869
13870         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13871                 return false;
13872
13873         return true;
13874 }
13875
13876 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13877 {
13878         if (INTEL_GEN(dev_priv) >= 9)
13879                 return false;
13880
13881         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13882                 return false;
13883
13884         if (IS_CHERRYVIEW(dev_priv))
13885                 return false;
13886
13887         if (HAS_PCH_LPT_H(dev_priv) &&
13888             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13889                 return false;
13890
13891         /* DDI E can't be used if DDI A requires 4 lanes */
13892         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13893                 return false;
13894
13895         if (!dev_priv->vbt.int_crt_support)
13896                 return false;
13897
13898         return true;
13899 }
13900
13901 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13902 {
13903         int pps_num;
13904         int pps_idx;
13905
13906         if (HAS_DDI(dev_priv))
13907                 return;
13908         /*
13909          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13910          * everywhere where registers can be write protected.
13911          */
13912         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13913                 pps_num = 2;
13914         else
13915                 pps_num = 1;
13916
13917         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13918                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13919
13920                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13921                 I915_WRITE(PP_CONTROL(pps_idx), val);
13922         }
13923 }
13924
13925 static void intel_pps_init(struct drm_i915_private *dev_priv)
13926 {
13927         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13928                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13929         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13930                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13931         else
13932                 dev_priv->pps_mmio_base = PPS_BASE;
13933
13934         intel_pps_unlock_regs_wa(dev_priv);
13935 }
13936
13937 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13938 {
13939         struct intel_encoder *encoder;
13940         bool dpd_is_edp = false;
13941
13942         intel_pps_init(dev_priv);
13943
13944         /*
13945          * intel_edp_init_connector() depends on this completing first, to
13946          * prevent the registeration of both eDP and LVDS and the incorrect
13947          * sharing of the PPS.
13948          */
13949         intel_lvds_init(dev_priv);
13950
13951         if (intel_crt_present(dev_priv))
13952                 intel_crt_init(dev_priv);
13953
13954         if (IS_GEN9_LP(dev_priv)) {
13955                 /*
13956                  * FIXME: Broxton doesn't support port detection via the
13957                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13958                  * detect the ports.
13959                  */
13960                 intel_ddi_init(dev_priv, PORT_A);
13961                 intel_ddi_init(dev_priv, PORT_B);
13962                 intel_ddi_init(dev_priv, PORT_C);
13963
13964                 intel_dsi_init(dev_priv);
13965         } else if (HAS_DDI(dev_priv)) {
13966                 int found;
13967
13968                 /*
13969                  * Haswell uses DDI functions to detect digital outputs.
13970                  * On SKL pre-D0 the strap isn't connected, so we assume
13971                  * it's there.
13972                  */
13973                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13974                 /* WaIgnoreDDIAStrap: skl */
13975                 if (found || IS_GEN9_BC(dev_priv))
13976                         intel_ddi_init(dev_priv, PORT_A);
13977
13978                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
13979                  * register */
13980                 found = I915_READ(SFUSE_STRAP);
13981
13982                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13983                         intel_ddi_init(dev_priv, PORT_B);
13984                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13985                         intel_ddi_init(dev_priv, PORT_C);
13986                 if (found & SFUSE_STRAP_DDID_DETECTED)
13987                         intel_ddi_init(dev_priv, PORT_D);
13988                 if (found & SFUSE_STRAP_DDIF_DETECTED)
13989                         intel_ddi_init(dev_priv, PORT_F);
13990                 /*
13991                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13992                  */
13993                 if (IS_GEN9_BC(dev_priv) &&
13994                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13995                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13996                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13997                         intel_ddi_init(dev_priv, PORT_E);
13998
13999         } else if (HAS_PCH_SPLIT(dev_priv)) {
14000                 int found;
14001                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14002
14003                 if (has_edp_a(dev_priv))
14004                         intel_dp_init(dev_priv, DP_A, PORT_A);
14005
14006                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14007                         /* PCH SDVOB multiplex with HDMIB */
14008                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14009                         if (!found)
14010                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14011                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14012                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14013                 }
14014
14015                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14016                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14017
14018                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14019                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14020
14021                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14022                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14023
14024                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14025                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14026         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14027                 bool has_edp, has_port;
14028
14029                 /*
14030                  * The DP_DETECTED bit is the latched state of the DDC
14031                  * SDA pin at boot. However since eDP doesn't require DDC
14032                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14033                  * eDP ports may have been muxed to an alternate function.
14034                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14035                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14036                  * detect eDP ports.
14037                  *
14038                  * Sadly the straps seem to be missing sometimes even for HDMI
14039                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14040                  * and VBT for the presence of the port. Additionally we can't
14041                  * trust the port type the VBT declares as we've seen at least
14042                  * HDMI ports that the VBT claim are DP or eDP.
14043                  */
14044                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14045                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14046                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14047                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14048                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14049                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14050
14051                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14052                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14053                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14054                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14055                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14056                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14057
14058                 if (IS_CHERRYVIEW(dev_priv)) {
14059                         /*
14060                          * eDP not supported on port D,
14061                          * so no need to worry about it
14062                          */
14063                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14064                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14065                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14066                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14067                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14068                 }
14069
14070                 intel_dsi_init(dev_priv);
14071         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14072                 bool found = false;
14073
14074                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14075                         DRM_DEBUG_KMS("probing SDVOB\n");
14076                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14077                         if (!found && IS_G4X(dev_priv)) {
14078                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14079                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14080                         }
14081
14082                         if (!found && IS_G4X(dev_priv))
14083                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14084                 }
14085
14086                 /* Before G4X SDVOC doesn't have its own detect register */
14087
14088                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14089                         DRM_DEBUG_KMS("probing SDVOC\n");
14090                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14091                 }
14092
14093                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14094
14095                         if (IS_G4X(dev_priv)) {
14096                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14097                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14098                         }
14099                         if (IS_G4X(dev_priv))
14100                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14101                 }
14102
14103                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14104                         intel_dp_init(dev_priv, DP_D, PORT_D);
14105         } else if (IS_GEN2(dev_priv))
14106                 intel_dvo_init(dev_priv);
14107
14108         if (SUPPORTS_TV(dev_priv))
14109                 intel_tv_init(dev_priv);
14110
14111         intel_psr_init(dev_priv);
14112
14113         for_each_intel_encoder(&dev_priv->drm, encoder) {
14114                 encoder->base.possible_crtcs = encoder->crtc_mask;
14115                 encoder->base.possible_clones =
14116                         intel_encoder_clones(encoder);
14117         }
14118
14119         intel_init_pch_refclk(dev_priv);
14120
14121         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14122 }
14123
14124 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14125 {
14126         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14127
14128         drm_framebuffer_cleanup(fb);
14129
14130         i915_gem_object_lock(intel_fb->obj);
14131         WARN_ON(!intel_fb->obj->framebuffer_references--);
14132         i915_gem_object_unlock(intel_fb->obj);
14133
14134         i915_gem_object_put(intel_fb->obj);
14135
14136         kfree(intel_fb);
14137 }
14138
14139 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14140                                                 struct drm_file *file,
14141                                                 unsigned int *handle)
14142 {
14143         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14144         struct drm_i915_gem_object *obj = intel_fb->obj;
14145
14146         if (obj->userptr.mm) {
14147                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14148                 return -EINVAL;
14149         }
14150
14151         return drm_gem_handle_create(file, &obj->base, handle);
14152 }
14153
14154 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14155                                         struct drm_file *file,
14156                                         unsigned flags, unsigned color,
14157                                         struct drm_clip_rect *clips,
14158                                         unsigned num_clips)
14159 {
14160         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14161
14162         i915_gem_object_flush_if_display(obj);
14163         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14164
14165         return 0;
14166 }
14167
14168 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14169         .destroy = intel_user_framebuffer_destroy,
14170         .create_handle = intel_user_framebuffer_create_handle,
14171         .dirty = intel_user_framebuffer_dirty,
14172 };
14173
14174 static
14175 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14176                          uint64_t fb_modifier, uint32_t pixel_format)
14177 {
14178         u32 gen = INTEL_GEN(dev_priv);
14179
14180         if (gen >= 9) {
14181                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14182
14183                 /* "The stride in bytes must not exceed the of the size of 8K
14184                  *  pixels and 32K bytes."
14185                  */
14186                 return min(8192 * cpp, 32768);
14187         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
14188                 return 32*1024;
14189         } else if (gen >= 4) {
14190                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14191                         return 16*1024;
14192                 else
14193                         return 32*1024;
14194         } else if (gen >= 3) {
14195                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14196                         return 8*1024;
14197                 else
14198                         return 16*1024;
14199         } else {
14200                 /* XXX DSPC is limited to 4k tiled */
14201                 return 8*1024;
14202         }
14203 }
14204
14205 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14206                                   struct drm_i915_gem_object *obj,
14207                                   struct drm_mode_fb_cmd2 *mode_cmd)
14208 {
14209         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14210         struct drm_framebuffer *fb = &intel_fb->base;
14211         struct drm_format_name_buf format_name;
14212         u32 pitch_limit;
14213         unsigned int tiling, stride;
14214         int ret = -EINVAL;
14215         int i;
14216
14217         i915_gem_object_lock(obj);
14218         obj->framebuffer_references++;
14219         tiling = i915_gem_object_get_tiling(obj);
14220         stride = i915_gem_object_get_stride(obj);
14221         i915_gem_object_unlock(obj);
14222
14223         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14224                 /*
14225                  * If there's a fence, enforce that
14226                  * the fb modifier and tiling mode match.
14227                  */
14228                 if (tiling != I915_TILING_NONE &&
14229                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14230                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14231                         goto err;
14232                 }
14233         } else {
14234                 if (tiling == I915_TILING_X) {
14235                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14236                 } else if (tiling == I915_TILING_Y) {
14237                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14238                         goto err;
14239                 }
14240         }
14241
14242         /* Passed in modifier sanity checking. */
14243         switch (mode_cmd->modifier[0]) {
14244         case I915_FORMAT_MOD_Y_TILED_CCS:
14245         case I915_FORMAT_MOD_Yf_TILED_CCS:
14246                 switch (mode_cmd->pixel_format) {
14247                 case DRM_FORMAT_XBGR8888:
14248                 case DRM_FORMAT_ABGR8888:
14249                 case DRM_FORMAT_XRGB8888:
14250                 case DRM_FORMAT_ARGB8888:
14251                         break;
14252                 default:
14253                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14254                         goto err;
14255                 }
14256                 /* fall through */
14257         case I915_FORMAT_MOD_Y_TILED:
14258         case I915_FORMAT_MOD_Yf_TILED:
14259                 if (INTEL_GEN(dev_priv) < 9) {
14260                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14261                                       mode_cmd->modifier[0]);
14262                         goto err;
14263                 }
14264         case DRM_FORMAT_MOD_LINEAR:
14265         case I915_FORMAT_MOD_X_TILED:
14266                 break;
14267         default:
14268                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14269                               mode_cmd->modifier[0]);
14270                 goto err;
14271         }
14272
14273         /*
14274          * gen2/3 display engine uses the fence if present,
14275          * so the tiling mode must match the fb modifier exactly.
14276          */
14277         if (INTEL_GEN(dev_priv) < 4 &&
14278             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14279                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14280                 goto err;
14281         }
14282
14283         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14284                                            mode_cmd->pixel_format);
14285         if (mode_cmd->pitches[0] > pitch_limit) {
14286                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14287                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14288                               "tiled" : "linear",
14289                               mode_cmd->pitches[0], pitch_limit);
14290                 goto err;
14291         }
14292
14293         /*
14294          * If there's a fence, enforce that
14295          * the fb pitch and fence stride match.
14296          */
14297         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14298                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14299                               mode_cmd->pitches[0], stride);
14300                 goto err;
14301         }
14302
14303         /* Reject formats not supported by any plane early. */
14304         switch (mode_cmd->pixel_format) {
14305         case DRM_FORMAT_C8:
14306         case DRM_FORMAT_RGB565:
14307         case DRM_FORMAT_XRGB8888:
14308         case DRM_FORMAT_ARGB8888:
14309                 break;
14310         case DRM_FORMAT_XRGB1555:
14311                 if (INTEL_GEN(dev_priv) > 3) {
14312                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14313                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14314                         goto err;
14315                 }
14316                 break;
14317         case DRM_FORMAT_ABGR8888:
14318                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14319                     INTEL_GEN(dev_priv) < 9) {
14320                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14321                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14322                         goto err;
14323                 }
14324                 break;
14325         case DRM_FORMAT_XBGR8888:
14326         case DRM_FORMAT_XRGB2101010:
14327         case DRM_FORMAT_XBGR2101010:
14328                 if (INTEL_GEN(dev_priv) < 4) {
14329                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14330                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14331                         goto err;
14332                 }
14333                 break;
14334         case DRM_FORMAT_ABGR2101010:
14335                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14336                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14337                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14338                         goto err;
14339                 }
14340                 break;
14341         case DRM_FORMAT_YUYV:
14342         case DRM_FORMAT_UYVY:
14343         case DRM_FORMAT_YVYU:
14344         case DRM_FORMAT_VYUY:
14345                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14346                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14347                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14348                         goto err;
14349                 }
14350                 break;
14351         case DRM_FORMAT_NV12:
14352                 if (mode_cmd->modifier[0] == I915_FORMAT_MOD_Y_TILED_CCS ||
14353                     mode_cmd->modifier[0] == I915_FORMAT_MOD_Yf_TILED_CCS) {
14354                         DRM_DEBUG_KMS("RC not to be enabled with NV12\n");
14355                         goto err;
14356                 }
14357                 if (INTEL_GEN(dev_priv) < 9 || IS_SKYLAKE(dev_priv) ||
14358                     IS_BROXTON(dev_priv)) {
14359                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14360                                       drm_get_format_name(mode_cmd->pixel_format,
14361                                                           &format_name));
14362                         goto err;
14363                 }
14364                 break;
14365         default:
14366                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14367                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14368                 goto err;
14369         }
14370
14371         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14372         if (mode_cmd->offsets[0] != 0)
14373                 goto err;
14374
14375         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14376
14377         if (fb->format->format == DRM_FORMAT_NV12 &&
14378             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14379              fb->height < SKL_MIN_YUV_420_SRC_H ||
14380              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14381                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14382                 return -EINVAL;
14383         }
14384
14385         for (i = 0; i < fb->format->num_planes; i++) {
14386                 u32 stride_alignment;
14387
14388                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14389                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14390                         goto err;
14391                 }
14392
14393                 stride_alignment = intel_fb_stride_alignment(fb, i);
14394
14395                 /*
14396                  * Display WA #0531: skl,bxt,kbl,glk
14397                  *
14398                  * Render decompression and plane width > 3840
14399                  * combined with horizontal panning requires the
14400                  * plane stride to be a multiple of 4. We'll just
14401                  * require the entire fb to accommodate that to avoid
14402                  * potential runtime errors at plane configuration time.
14403                  */
14404                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14405                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14406                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14407                         stride_alignment *= 4;
14408
14409                 if (fb->pitches[i] & (stride_alignment - 1)) {
14410                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14411                                       i, fb->pitches[i], stride_alignment);
14412                         goto err;
14413                 }
14414         }
14415
14416         intel_fb->obj = obj;
14417
14418         ret = intel_fill_fb_info(dev_priv, fb);
14419         if (ret)
14420                 goto err;
14421
14422         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14423         if (ret) {
14424                 DRM_ERROR("framebuffer init failed %d\n", ret);
14425                 goto err;
14426         }
14427
14428         return 0;
14429
14430 err:
14431         i915_gem_object_lock(obj);
14432         obj->framebuffer_references--;
14433         i915_gem_object_unlock(obj);
14434         return ret;
14435 }
14436
14437 static struct drm_framebuffer *
14438 intel_user_framebuffer_create(struct drm_device *dev,
14439                               struct drm_file *filp,
14440                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14441 {
14442         struct drm_framebuffer *fb;
14443         struct drm_i915_gem_object *obj;
14444         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14445
14446         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14447         if (!obj)
14448                 return ERR_PTR(-ENOENT);
14449
14450         fb = intel_framebuffer_create(obj, &mode_cmd);
14451         if (IS_ERR(fb))
14452                 i915_gem_object_put(obj);
14453
14454         return fb;
14455 }
14456
14457 static void intel_atomic_state_free(struct drm_atomic_state *state)
14458 {
14459         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14460
14461         drm_atomic_state_default_release(state);
14462
14463         i915_sw_fence_fini(&intel_state->commit_ready);
14464
14465         kfree(state);
14466 }
14467
14468 static enum drm_mode_status
14469 intel_mode_valid(struct drm_device *dev,
14470                  const struct drm_display_mode *mode)
14471 {
14472         /*
14473          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14474          * of DBLSCAN modes to the output's mode list when they detect
14475          * the scaling mode property on the connector. And they don't
14476          * ask the kernel to validate those modes in any way until
14477          * modeset time at which point the client gets a protocol error.
14478          * So in order to not upset those clients we silently ignore the
14479          * DBLSCAN flag on such connectors. For other connectors we will
14480          * reject modes with the DBLSCAN flag in encoder->compute_config().
14481          * And we always reject DBLSCAN modes in connector->mode_valid()
14482          * as we never want such modes on the connector's mode list.
14483          */
14484
14485         if (mode->vscan > 1)
14486                 return MODE_NO_VSCAN;
14487
14488         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14489                 return MODE_H_ILLEGAL;
14490
14491         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14492                            DRM_MODE_FLAG_NCSYNC |
14493                            DRM_MODE_FLAG_PCSYNC))
14494                 return MODE_HSYNC;
14495
14496         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14497                            DRM_MODE_FLAG_PIXMUX |
14498                            DRM_MODE_FLAG_CLKDIV2))
14499                 return MODE_BAD;
14500
14501         return MODE_OK;
14502 }
14503
14504 static const struct drm_mode_config_funcs intel_mode_funcs = {
14505         .fb_create = intel_user_framebuffer_create,
14506         .get_format_info = intel_get_format_info,
14507         .output_poll_changed = intel_fbdev_output_poll_changed,
14508         .mode_valid = intel_mode_valid,
14509         .atomic_check = intel_atomic_check,
14510         .atomic_commit = intel_atomic_commit,
14511         .atomic_state_alloc = intel_atomic_state_alloc,
14512         .atomic_state_clear = intel_atomic_state_clear,
14513         .atomic_state_free = intel_atomic_state_free,
14514 };
14515
14516 /**
14517  * intel_init_display_hooks - initialize the display modesetting hooks
14518  * @dev_priv: device private
14519  */
14520 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14521 {
14522         intel_init_cdclk_hooks(dev_priv);
14523
14524         if (INTEL_GEN(dev_priv) >= 9) {
14525                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14526                 dev_priv->display.get_initial_plane_config =
14527                         skylake_get_initial_plane_config;
14528                 dev_priv->display.crtc_compute_clock =
14529                         haswell_crtc_compute_clock;
14530                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14531                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14532         } else if (HAS_DDI(dev_priv)) {
14533                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14534                 dev_priv->display.get_initial_plane_config =
14535                         i9xx_get_initial_plane_config;
14536                 dev_priv->display.crtc_compute_clock =
14537                         haswell_crtc_compute_clock;
14538                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14539                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14540         } else if (HAS_PCH_SPLIT(dev_priv)) {
14541                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14542                 dev_priv->display.get_initial_plane_config =
14543                         i9xx_get_initial_plane_config;
14544                 dev_priv->display.crtc_compute_clock =
14545                         ironlake_crtc_compute_clock;
14546                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14547                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14548         } else if (IS_CHERRYVIEW(dev_priv)) {
14549                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14550                 dev_priv->display.get_initial_plane_config =
14551                         i9xx_get_initial_plane_config;
14552                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14553                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14554                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14555         } else if (IS_VALLEYVIEW(dev_priv)) {
14556                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14557                 dev_priv->display.get_initial_plane_config =
14558                         i9xx_get_initial_plane_config;
14559                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14560                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14561                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14562         } else if (IS_G4X(dev_priv)) {
14563                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14564                 dev_priv->display.get_initial_plane_config =
14565                         i9xx_get_initial_plane_config;
14566                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14567                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14568                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14569         } else if (IS_PINEVIEW(dev_priv)) {
14570                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14571                 dev_priv->display.get_initial_plane_config =
14572                         i9xx_get_initial_plane_config;
14573                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14574                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14575                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14576         } else if (!IS_GEN2(dev_priv)) {
14577                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14578                 dev_priv->display.get_initial_plane_config =
14579                         i9xx_get_initial_plane_config;
14580                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14581                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14582                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14583         } else {
14584                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14585                 dev_priv->display.get_initial_plane_config =
14586                         i9xx_get_initial_plane_config;
14587                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14588                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14589                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14590         }
14591
14592         if (IS_GEN5(dev_priv)) {
14593                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14594         } else if (IS_GEN6(dev_priv)) {
14595                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14596         } else if (IS_IVYBRIDGE(dev_priv)) {
14597                 /* FIXME: detect B0+ stepping and use auto training */
14598                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14599         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14600                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14601         }
14602
14603         if (INTEL_GEN(dev_priv) >= 9)
14604                 dev_priv->display.update_crtcs = skl_update_crtcs;
14605         else
14606                 dev_priv->display.update_crtcs = intel_update_crtcs;
14607 }
14608
14609 /*
14610  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14611  */
14612 static void quirk_ssc_force_disable(struct drm_device *dev)
14613 {
14614         struct drm_i915_private *dev_priv = to_i915(dev);
14615         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14616         DRM_INFO("applying lvds SSC disable quirk\n");
14617 }
14618
14619 /*
14620  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14621  * brightness value
14622  */
14623 static void quirk_invert_brightness(struct drm_device *dev)
14624 {
14625         struct drm_i915_private *dev_priv = to_i915(dev);
14626         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14627         DRM_INFO("applying inverted panel brightness quirk\n");
14628 }
14629
14630 /* Some VBT's incorrectly indicate no backlight is present */
14631 static void quirk_backlight_present(struct drm_device *dev)
14632 {
14633         struct drm_i915_private *dev_priv = to_i915(dev);
14634         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14635         DRM_INFO("applying backlight present quirk\n");
14636 }
14637
14638 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14639  * which is 300 ms greater than eDP spec T12 min.
14640  */
14641 static void quirk_increase_t12_delay(struct drm_device *dev)
14642 {
14643         struct drm_i915_private *dev_priv = to_i915(dev);
14644
14645         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14646         DRM_INFO("Applying T12 delay quirk\n");
14647 }
14648
14649 /*
14650  * GeminiLake NUC HDMI outputs require additional off time
14651  * this allows the onboard retimer to correctly sync to signal
14652  */
14653 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14654 {
14655         struct drm_i915_private *dev_priv = to_i915(dev);
14656
14657         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14658         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14659 }
14660
14661 struct intel_quirk {
14662         int device;
14663         int subsystem_vendor;
14664         int subsystem_device;
14665         void (*hook)(struct drm_device *dev);
14666 };
14667
14668 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14669 struct intel_dmi_quirk {
14670         void (*hook)(struct drm_device *dev);
14671         const struct dmi_system_id (*dmi_id_list)[];
14672 };
14673
14674 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14675 {
14676         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14677         return 1;
14678 }
14679
14680 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14681         {
14682                 .dmi_id_list = &(const struct dmi_system_id[]) {
14683                         {
14684                                 .callback = intel_dmi_reverse_brightness,
14685                                 .ident = "NCR Corporation",
14686                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14687                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14688                                 },
14689                         },
14690                         { }  /* terminating entry */
14691                 },
14692                 .hook = quirk_invert_brightness,
14693         },
14694 };
14695
14696 static struct intel_quirk intel_quirks[] = {
14697         /* Lenovo U160 cannot use SSC on LVDS */
14698         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14699
14700         /* Sony Vaio Y cannot use SSC on LVDS */
14701         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14702
14703         /* Acer Aspire 5734Z must invert backlight brightness */
14704         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14705
14706         /* Acer/eMachines G725 */
14707         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14708
14709         /* Acer/eMachines e725 */
14710         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14711
14712         /* Acer/Packard Bell NCL20 */
14713         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14714
14715         /* Acer Aspire 4736Z */
14716         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14717
14718         /* Acer Aspire 5336 */
14719         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14720
14721         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14722         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14723
14724         /* Acer C720 Chromebook (Core i3 4005U) */
14725         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14726
14727         /* Apple Macbook 2,1 (Core 2 T7400) */
14728         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14729
14730         /* Apple Macbook 4,1 */
14731         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14732
14733         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14734         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14735
14736         /* HP Chromebook 14 (Celeron 2955U) */
14737         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14738
14739         /* Dell Chromebook 11 */
14740         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14741
14742         /* Dell Chromebook 11 (2015 version) */
14743         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14744
14745         /* Toshiba Satellite P50-C-18C */
14746         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14747
14748         /* GeminiLake NUC */
14749         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14750         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14751         /* ASRock ITX*/
14752         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14753         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14754 };
14755
14756 static void intel_init_quirks(struct drm_device *dev)
14757 {
14758         struct pci_dev *d = dev->pdev;
14759         int i;
14760
14761         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14762                 struct intel_quirk *q = &intel_quirks[i];
14763
14764                 if (d->device == q->device &&
14765                     (d->subsystem_vendor == q->subsystem_vendor ||
14766                      q->subsystem_vendor == PCI_ANY_ID) &&
14767                     (d->subsystem_device == q->subsystem_device ||
14768                      q->subsystem_device == PCI_ANY_ID))
14769                         q->hook(dev);
14770         }
14771         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14772                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14773                         intel_dmi_quirks[i].hook(dev);
14774         }
14775 }
14776
14777 /* Disable the VGA plane that we never use */
14778 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14779 {
14780         struct pci_dev *pdev = dev_priv->drm.pdev;
14781         u8 sr1;
14782         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14783
14784         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14785         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14786         outb(SR01, VGA_SR_INDEX);
14787         sr1 = inb(VGA_SR_DATA);
14788         outb(sr1 | 1<<5, VGA_SR_DATA);
14789         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14790         udelay(300);
14791
14792         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14793         POSTING_READ(vga_reg);
14794 }
14795
14796 void intel_modeset_init_hw(struct drm_device *dev)
14797 {
14798         struct drm_i915_private *dev_priv = to_i915(dev);
14799
14800         intel_update_cdclk(dev_priv);
14801         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14802         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14803 }
14804
14805 /*
14806  * Calculate what we think the watermarks should be for the state we've read
14807  * out of the hardware and then immediately program those watermarks so that
14808  * we ensure the hardware settings match our internal state.
14809  *
14810  * We can calculate what we think WM's should be by creating a duplicate of the
14811  * current state (which was constructed during hardware readout) and running it
14812  * through the atomic check code to calculate new watermark values in the
14813  * state object.
14814  */
14815 static void sanitize_watermarks(struct drm_device *dev)
14816 {
14817         struct drm_i915_private *dev_priv = to_i915(dev);
14818         struct drm_atomic_state *state;
14819         struct intel_atomic_state *intel_state;
14820         struct drm_crtc *crtc;
14821         struct drm_crtc_state *cstate;
14822         struct drm_modeset_acquire_ctx ctx;
14823         int ret;
14824         int i;
14825
14826         /* Only supported on platforms that use atomic watermark design */
14827         if (!dev_priv->display.optimize_watermarks)
14828                 return;
14829
14830         /*
14831          * We need to hold connection_mutex before calling duplicate_state so
14832          * that the connector loop is protected.
14833          */
14834         drm_modeset_acquire_init(&ctx, 0);
14835 retry:
14836         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14837         if (ret == -EDEADLK) {
14838                 drm_modeset_backoff(&ctx);
14839                 goto retry;
14840         } else if (WARN_ON(ret)) {
14841                 goto fail;
14842         }
14843
14844         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14845         if (WARN_ON(IS_ERR(state)))
14846                 goto fail;
14847
14848         intel_state = to_intel_atomic_state(state);
14849
14850         /*
14851          * Hardware readout is the only time we don't want to calculate
14852          * intermediate watermarks (since we don't trust the current
14853          * watermarks).
14854          */
14855         if (!HAS_GMCH_DISPLAY(dev_priv))
14856                 intel_state->skip_intermediate_wm = true;
14857
14858         ret = intel_atomic_check(dev, state);
14859         if (ret) {
14860                 /*
14861                  * If we fail here, it means that the hardware appears to be
14862                  * programmed in a way that shouldn't be possible, given our
14863                  * understanding of watermark requirements.  This might mean a
14864                  * mistake in the hardware readout code or a mistake in the
14865                  * watermark calculations for a given platform.  Raise a WARN
14866                  * so that this is noticeable.
14867                  *
14868                  * If this actually happens, we'll have to just leave the
14869                  * BIOS-programmed watermarks untouched and hope for the best.
14870                  */
14871                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14872                 goto put_state;
14873         }
14874
14875         /* Write calculated watermark values back */
14876         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14877                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14878
14879                 cs->wm.need_postvbl_update = true;
14880                 dev_priv->display.optimize_watermarks(intel_state, cs);
14881
14882                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14883         }
14884
14885 put_state:
14886         drm_atomic_state_put(state);
14887 fail:
14888         drm_modeset_drop_locks(&ctx);
14889         drm_modeset_acquire_fini(&ctx);
14890 }
14891
14892 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14893 {
14894         if (IS_GEN5(dev_priv)) {
14895                 u32 fdi_pll_clk =
14896                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14897
14898                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14899         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14900                 dev_priv->fdi_pll_freq = 270000;
14901         } else {
14902                 return;
14903         }
14904
14905         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14906 }
14907
14908 int intel_modeset_init(struct drm_device *dev)
14909 {
14910         struct drm_i915_private *dev_priv = to_i915(dev);
14911         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14912         enum pipe pipe;
14913         struct intel_crtc *crtc;
14914
14915         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
14916
14917         drm_mode_config_init(dev);
14918
14919         dev->mode_config.min_width = 0;
14920         dev->mode_config.min_height = 0;
14921
14922         dev->mode_config.preferred_depth = 24;
14923         dev->mode_config.prefer_shadow = 1;
14924
14925         dev->mode_config.allow_fb_modifiers = true;
14926
14927         dev->mode_config.funcs = &intel_mode_funcs;
14928
14929         init_llist_head(&dev_priv->atomic_helper.free_list);
14930         INIT_WORK(&dev_priv->atomic_helper.free_work,
14931                   intel_atomic_helper_free_state_worker);
14932
14933         intel_init_quirks(dev);
14934
14935         intel_init_pm(dev_priv);
14936
14937         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14938                 return 0;
14939
14940         /*
14941          * There may be no VBT; and if the BIOS enabled SSC we can
14942          * just keep using it to avoid unnecessary flicker.  Whereas if the
14943          * BIOS isn't using it, don't assume it will work even if the VBT
14944          * indicates as much.
14945          */
14946         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
14947                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14948                                             DREF_SSC1_ENABLE);
14949
14950                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14951                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14952                                      bios_lvds_use_ssc ? "en" : "dis",
14953                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14954                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14955                 }
14956         }
14957
14958         if (IS_GEN2(dev_priv)) {
14959                 dev->mode_config.max_width = 2048;
14960                 dev->mode_config.max_height = 2048;
14961         } else if (IS_GEN3(dev_priv)) {
14962                 dev->mode_config.max_width = 4096;
14963                 dev->mode_config.max_height = 4096;
14964         } else {
14965                 dev->mode_config.max_width = 8192;
14966                 dev->mode_config.max_height = 8192;
14967         }
14968
14969         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14970                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
14971                 dev->mode_config.cursor_height = 1023;
14972         } else if (IS_GEN2(dev_priv)) {
14973                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14974                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14975         } else {
14976                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14977                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14978         }
14979
14980         dev->mode_config.fb_base = ggtt->gmadr.start;
14981
14982         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14983                       INTEL_INFO(dev_priv)->num_pipes,
14984                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
14985
14986         for_each_pipe(dev_priv, pipe) {
14987                 int ret;
14988
14989                 ret = intel_crtc_init(dev_priv, pipe);
14990                 if (ret) {
14991                         drm_mode_config_cleanup(dev);
14992                         return ret;
14993                 }
14994         }
14995
14996         intel_shared_dpll_init(dev);
14997         intel_update_fdi_pll_freq(dev_priv);
14998
14999         intel_update_czclk(dev_priv);
15000         intel_modeset_init_hw(dev);
15001
15002         if (dev_priv->max_cdclk_freq == 0)
15003                 intel_update_max_cdclk(dev_priv);
15004
15005         /* Just disable it once at startup */
15006         i915_disable_vga(dev_priv);
15007         intel_setup_outputs(dev_priv);
15008
15009         drm_modeset_lock_all(dev);
15010         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15011         drm_modeset_unlock_all(dev);
15012
15013         for_each_intel_crtc(dev, crtc) {
15014                 struct intel_initial_plane_config plane_config = {};
15015
15016                 if (!crtc->active)
15017                         continue;
15018
15019                 /*
15020                  * Note that reserving the BIOS fb up front prevents us
15021                  * from stuffing other stolen allocations like the ring
15022                  * on top.  This prevents some ugliness at boot time, and
15023                  * can even allow for smooth boot transitions if the BIOS
15024                  * fb is large enough for the active pipe configuration.
15025                  */
15026                 dev_priv->display.get_initial_plane_config(crtc,
15027                                                            &plane_config);
15028
15029                 /*
15030                  * If the fb is shared between multiple heads, we'll
15031                  * just get the first one.
15032                  */
15033                 intel_find_initial_plane_obj(crtc, &plane_config);
15034         }
15035
15036         /*
15037          * Make sure hardware watermarks really match the state we read out.
15038          * Note that we need to do this after reconstructing the BIOS fb's
15039          * since the watermark calculation done here will use pstate->fb.
15040          */
15041         if (!HAS_GMCH_DISPLAY(dev_priv))
15042                 sanitize_watermarks(dev);
15043
15044         return 0;
15045 }
15046
15047 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15048 {
15049         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15050         /* 640x480@60Hz, ~25175 kHz */
15051         struct dpll clock = {
15052                 .m1 = 18,
15053                 .m2 = 7,
15054                 .p1 = 13,
15055                 .p2 = 4,
15056                 .n = 2,
15057         };
15058         u32 dpll, fp;
15059         int i;
15060
15061         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15062
15063         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15064                       pipe_name(pipe), clock.vco, clock.dot);
15065
15066         fp = i9xx_dpll_compute_fp(&clock);
15067         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15068                 DPLL_VGA_MODE_DIS |
15069                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15070                 PLL_P2_DIVIDE_BY_4 |
15071                 PLL_REF_INPUT_DREFCLK |
15072                 DPLL_VCO_ENABLE;
15073
15074         I915_WRITE(FP0(pipe), fp);
15075         I915_WRITE(FP1(pipe), fp);
15076
15077         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15078         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15079         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15080         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15081         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15082         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15083         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15084
15085         /*
15086          * Apparently we need to have VGA mode enabled prior to changing
15087          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15088          * dividers, even though the register value does change.
15089          */
15090         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15091         I915_WRITE(DPLL(pipe), dpll);
15092
15093         /* Wait for the clocks to stabilize. */
15094         POSTING_READ(DPLL(pipe));
15095         udelay(150);
15096
15097         /* The pixel multiplier can only be updated once the
15098          * DPLL is enabled and the clocks are stable.
15099          *
15100          * So write it again.
15101          */
15102         I915_WRITE(DPLL(pipe), dpll);
15103
15104         /* We do this three times for luck */
15105         for (i = 0; i < 3 ; i++) {
15106                 I915_WRITE(DPLL(pipe), dpll);
15107                 POSTING_READ(DPLL(pipe));
15108                 udelay(150); /* wait for warmup */
15109         }
15110
15111         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15112         POSTING_READ(PIPECONF(pipe));
15113
15114         intel_wait_for_pipe_scanline_moving(crtc);
15115 }
15116
15117 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15118 {
15119         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15120
15121         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15122                       pipe_name(pipe));
15123
15124         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15125         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15126         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15127         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & CURSOR_MODE);
15128         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & CURSOR_MODE);
15129
15130         I915_WRITE(PIPECONF(pipe), 0);
15131         POSTING_READ(PIPECONF(pipe));
15132
15133         intel_wait_for_pipe_scanline_stopped(crtc);
15134
15135         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15136         POSTING_READ(DPLL(pipe));
15137 }
15138
15139 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
15140                                    struct intel_plane *plane)
15141 {
15142         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15143         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
15144         u32 val = I915_READ(DSPCNTR(i9xx_plane));
15145
15146         return (val & DISPLAY_PLANE_ENABLE) == 0 ||
15147                 (val & DISPPLANE_SEL_PIPE_MASK) == DISPPLANE_SEL_PIPE(crtc->pipe);
15148 }
15149
15150 static void
15151 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15152 {
15153         struct intel_crtc *crtc;
15154
15155         if (INTEL_GEN(dev_priv) >= 4)
15156                 return;
15157
15158         for_each_intel_crtc(&dev_priv->drm, crtc) {
15159                 struct intel_plane *plane =
15160                         to_intel_plane(crtc->base.primary);
15161
15162                 if (intel_plane_mapping_ok(crtc, plane))
15163                         continue;
15164
15165                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
15166                               plane->base.name);
15167                 intel_plane_disable_noatomic(crtc, plane);
15168         }
15169 }
15170
15171 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15172 {
15173         struct drm_device *dev = crtc->base.dev;
15174         struct intel_encoder *encoder;
15175
15176         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15177                 return true;
15178
15179         return false;
15180 }
15181
15182 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15183 {
15184         struct drm_device *dev = encoder->base.dev;
15185         struct intel_connector *connector;
15186
15187         for_each_connector_on_encoder(dev, &encoder->base, connector)
15188                 return connector;
15189
15190         return NULL;
15191 }
15192
15193 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15194                               enum pipe pch_transcoder)
15195 {
15196         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15197                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15198 }
15199
15200 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15201                                 struct drm_modeset_acquire_ctx *ctx)
15202 {
15203         struct drm_device *dev = crtc->base.dev;
15204         struct drm_i915_private *dev_priv = to_i915(dev);
15205         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15206
15207         /* Clear any frame start delays used for debugging left by the BIOS */
15208         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15209                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15210
15211                 I915_WRITE(reg,
15212                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15213         }
15214
15215         /* restore vblank interrupts to correct state */
15216         drm_crtc_vblank_reset(&crtc->base);
15217         if (crtc->active) {
15218                 struct intel_plane *plane;
15219
15220                 drm_crtc_vblank_on(&crtc->base);
15221
15222                 /* Disable everything but the primary plane */
15223                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15224                         const struct intel_plane_state *plane_state =
15225                                 to_intel_plane_state(plane->base.state);
15226
15227                         if (plane_state->base.visible &&
15228                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15229                                 intel_plane_disable_noatomic(crtc, plane);
15230                 }
15231         }
15232
15233         /* Adjust the state of the output pipe according to whether we
15234          * have active connectors/encoders. */
15235         if (crtc->active && !intel_crtc_has_encoders(crtc))
15236                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15237
15238         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15239                 /*
15240                  * We start out with underrun reporting disabled to avoid races.
15241                  * For correct bookkeeping mark this on active crtcs.
15242                  *
15243                  * Also on gmch platforms we dont have any hardware bits to
15244                  * disable the underrun reporting. Which means we need to start
15245                  * out with underrun reporting disabled also on inactive pipes,
15246                  * since otherwise we'll complain about the garbage we read when
15247                  * e.g. coming up after runtime pm.
15248                  *
15249                  * No protection against concurrent access is required - at
15250                  * worst a fifo underrun happens which also sets this to false.
15251                  */
15252                 crtc->cpu_fifo_underrun_disabled = true;
15253                 /*
15254                  * We track the PCH trancoder underrun reporting state
15255                  * within the crtc. With crtc for pipe A housing the underrun
15256                  * reporting state for PCH transcoder A, crtc for pipe B housing
15257                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15258                  * and marking underrun reporting as disabled for the non-existing
15259                  * PCH transcoders B and C would prevent enabling the south
15260                  * error interrupt (see cpt_can_enable_serr_int()).
15261                  */
15262                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15263                         crtc->pch_fifo_underrun_disabled = true;
15264         }
15265 }
15266
15267 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15268 {
15269         struct intel_connector *connector;
15270
15271         /* We need to check both for a crtc link (meaning that the
15272          * encoder is active and trying to read from a pipe) and the
15273          * pipe itself being active. */
15274         bool has_active_crtc = encoder->base.crtc &&
15275                 to_intel_crtc(encoder->base.crtc)->active;
15276
15277         connector = intel_encoder_find_connector(encoder);
15278         if (connector && !has_active_crtc) {
15279                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15280                               encoder->base.base.id,
15281                               encoder->base.name);
15282
15283                 /* Connector is active, but has no active pipe. This is
15284                  * fallout from our resume register restoring. Disable
15285                  * the encoder manually again. */
15286                 if (encoder->base.crtc) {
15287                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15288
15289                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15290                                       encoder->base.base.id,
15291                                       encoder->base.name);
15292                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15293                         if (encoder->post_disable)
15294                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15295                 }
15296                 encoder->base.crtc = NULL;
15297
15298                 /* Inconsistent output/port/pipe state happens presumably due to
15299                  * a bug in one of the get_hw_state functions. Or someplace else
15300                  * in our code, like the register restore mess on resume. Clamp
15301                  * things to off as a safer default. */
15302
15303                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15304                 connector->base.encoder = NULL;
15305         }
15306 }
15307
15308 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15309 {
15310         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15311
15312         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15313                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15314                 i915_disable_vga(dev_priv);
15315         }
15316 }
15317
15318 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15319 {
15320         /* This function can be called both from intel_modeset_setup_hw_state or
15321          * at a very early point in our resume sequence, where the power well
15322          * structures are not yet restored. Since this function is at a very
15323          * paranoid "someone might have enabled VGA while we were not looking"
15324          * level, just check if the power well is enabled instead of trying to
15325          * follow the "don't touch the power well if we don't need it" policy
15326          * the rest of the driver uses. */
15327         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15328                 return;
15329
15330         i915_redisable_vga_power_on(dev_priv);
15331
15332         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15333 }
15334
15335 /* FIXME read out full plane state for all planes */
15336 static void readout_plane_state(struct intel_crtc *crtc)
15337 {
15338         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15339         struct intel_crtc_state *crtc_state =
15340                 to_intel_crtc_state(crtc->base.state);
15341         struct intel_plane *plane;
15342
15343         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
15344                 struct intel_plane_state *plane_state =
15345                         to_intel_plane_state(plane->base.state);
15346                 bool visible = plane->get_hw_state(plane);
15347
15348                 intel_set_plane_visible(crtc_state, plane_state, visible);
15349         }
15350 }
15351
15352 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15353 {
15354         struct drm_i915_private *dev_priv = to_i915(dev);
15355         enum pipe pipe;
15356         struct intel_crtc *crtc;
15357         struct intel_encoder *encoder;
15358         struct intel_connector *connector;
15359         struct drm_connector_list_iter conn_iter;
15360         int i;
15361
15362         dev_priv->active_crtcs = 0;
15363
15364         for_each_intel_crtc(dev, crtc) {
15365                 struct intel_crtc_state *crtc_state =
15366                         to_intel_crtc_state(crtc->base.state);
15367
15368                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15369                 memset(crtc_state, 0, sizeof(*crtc_state));
15370                 crtc_state->base.crtc = &crtc->base;
15371
15372                 crtc_state->base.active = crtc_state->base.enable =
15373                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15374
15375                 crtc->base.enabled = crtc_state->base.enable;
15376                 crtc->active = crtc_state->base.active;
15377
15378                 if (crtc_state->base.active)
15379                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15380
15381                 readout_plane_state(crtc);
15382
15383                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15384                               crtc->base.base.id, crtc->base.name,
15385                               enableddisabled(crtc_state->base.active));
15386         }
15387
15388         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15389                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15390
15391                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15392                                                         &pll->state.hw_state);
15393                 pll->state.crtc_mask = 0;
15394                 for_each_intel_crtc(dev, crtc) {
15395                         struct intel_crtc_state *crtc_state =
15396                                 to_intel_crtc_state(crtc->base.state);
15397
15398                         if (crtc_state->base.active &&
15399                             crtc_state->shared_dpll == pll)
15400                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15401                 }
15402                 pll->active_mask = pll->state.crtc_mask;
15403
15404                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15405                               pll->info->name, pll->state.crtc_mask, pll->on);
15406         }
15407
15408         for_each_intel_encoder(dev, encoder) {
15409                 pipe = 0;
15410
15411                 if (encoder->get_hw_state(encoder, &pipe)) {
15412                         struct intel_crtc_state *crtc_state;
15413
15414                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15415                         crtc_state = to_intel_crtc_state(crtc->base.state);
15416
15417                         encoder->base.crtc = &crtc->base;
15418                         encoder->get_config(encoder, crtc_state);
15419                 } else {
15420                         encoder->base.crtc = NULL;
15421                 }
15422
15423                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15424                               encoder->base.base.id, encoder->base.name,
15425                               enableddisabled(encoder->base.crtc),
15426                               pipe_name(pipe));
15427         }
15428
15429         drm_connector_list_iter_begin(dev, &conn_iter);
15430         for_each_intel_connector_iter(connector, &conn_iter) {
15431                 if (connector->get_hw_state(connector)) {
15432                         connector->base.dpms = DRM_MODE_DPMS_ON;
15433
15434                         encoder = connector->encoder;
15435                         connector->base.encoder = &encoder->base;
15436
15437                         if (encoder->base.crtc &&
15438                             encoder->base.crtc->state->active) {
15439                                 /*
15440                                  * This has to be done during hardware readout
15441                                  * because anything calling .crtc_disable may
15442                                  * rely on the connector_mask being accurate.
15443                                  */
15444                                 encoder->base.crtc->state->connector_mask |=
15445                                         1 << drm_connector_index(&connector->base);
15446                                 encoder->base.crtc->state->encoder_mask |=
15447                                         1 << drm_encoder_index(&encoder->base);
15448                         }
15449
15450                 } else {
15451                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15452                         connector->base.encoder = NULL;
15453                 }
15454                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15455                               connector->base.base.id, connector->base.name,
15456                               enableddisabled(connector->base.encoder));
15457         }
15458         drm_connector_list_iter_end(&conn_iter);
15459
15460         for_each_intel_crtc(dev, crtc) {
15461                 struct intel_crtc_state *crtc_state =
15462                         to_intel_crtc_state(crtc->base.state);
15463                 int min_cdclk = 0;
15464
15465                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15466                 if (crtc_state->base.active) {
15467                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15468                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15469                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15470                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15471                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15472
15473                         /*
15474                          * The initial mode needs to be set in order to keep
15475                          * the atomic core happy. It wants a valid mode if the
15476                          * crtc's enabled, so we do the above call.
15477                          *
15478                          * But we don't set all the derived state fully, hence
15479                          * set a flag to indicate that a full recalculation is
15480                          * needed on the next commit.
15481                          */
15482                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15483
15484                         intel_crtc_compute_pixel_rate(crtc_state);
15485
15486                         if (dev_priv->display.modeset_calc_cdclk) {
15487                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15488                                 if (WARN_ON(min_cdclk < 0))
15489                                         min_cdclk = 0;
15490                         }
15491
15492                         drm_calc_timestamping_constants(&crtc->base,
15493                                                         &crtc_state->base.adjusted_mode);
15494                         update_scanline_offset(crtc);
15495                 }
15496
15497                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15498                 dev_priv->min_voltage_level[crtc->pipe] =
15499                         crtc_state->min_voltage_level;
15500
15501                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15502         }
15503 }
15504
15505 static void
15506 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15507 {
15508         struct intel_encoder *encoder;
15509
15510         for_each_intel_encoder(&dev_priv->drm, encoder) {
15511                 u64 get_domains;
15512                 enum intel_display_power_domain domain;
15513
15514                 if (!encoder->get_power_domains)
15515                         continue;
15516
15517                 get_domains = encoder->get_power_domains(encoder);
15518                 for_each_power_domain(domain, get_domains)
15519                         intel_display_power_get(dev_priv, domain);
15520         }
15521 }
15522
15523 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15524 {
15525         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15526         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15527                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15528                            DARBF_GATING_DIS);
15529
15530         if (IS_HASWELL(dev_priv)) {
15531                 /*
15532                  * WaRsPkgCStateDisplayPMReq:hsw
15533                  * System hang if this isn't done before disabling all planes!
15534                  */
15535                 I915_WRITE(CHICKEN_PAR1_1,
15536                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15537         }
15538 }
15539
15540 /* Scan out the current hw modeset state,
15541  * and sanitizes it to the current state
15542  */
15543 static void
15544 intel_modeset_setup_hw_state(struct drm_device *dev,
15545                              struct drm_modeset_acquire_ctx *ctx)
15546 {
15547         struct drm_i915_private *dev_priv = to_i915(dev);
15548         enum pipe pipe;
15549         struct intel_crtc *crtc;
15550         struct intel_encoder *encoder;
15551         int i;
15552
15553         intel_early_display_was(dev_priv);
15554         intel_modeset_readout_hw_state(dev);
15555
15556         /* HW state is read out, now we need to sanitize this mess. */
15557         get_encoder_power_domains(dev_priv);
15558
15559         intel_sanitize_plane_mapping(dev_priv);
15560
15561         for_each_intel_encoder(dev, encoder) {
15562                 intel_sanitize_encoder(encoder);
15563         }
15564
15565         for_each_pipe(dev_priv, pipe) {
15566                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15567
15568                 intel_sanitize_crtc(crtc, ctx);
15569                 intel_dump_pipe_config(crtc, crtc->config,
15570                                        "[setup_hw_state]");
15571         }
15572
15573         intel_modeset_update_connector_atomic_state(dev);
15574
15575         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15576                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15577
15578                 if (!pll->on || pll->active_mask)
15579                         continue;
15580
15581                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15582                               pll->info->name);
15583
15584                 pll->info->funcs->disable(dev_priv, pll);
15585                 pll->on = false;
15586         }
15587
15588         if (IS_G4X(dev_priv)) {
15589                 g4x_wm_get_hw_state(dev);
15590                 g4x_wm_sanitize(dev_priv);
15591         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15592                 vlv_wm_get_hw_state(dev);
15593                 vlv_wm_sanitize(dev_priv);
15594         } else if (INTEL_GEN(dev_priv) >= 9) {
15595                 skl_wm_get_hw_state(dev);
15596         } else if (HAS_PCH_SPLIT(dev_priv)) {
15597                 ilk_wm_get_hw_state(dev);
15598         }
15599
15600         for_each_intel_crtc(dev, crtc) {
15601                 u64 put_domains;
15602
15603                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15604                 if (WARN_ON(put_domains))
15605                         modeset_put_power_domains(dev_priv, put_domains);
15606         }
15607         intel_display_set_init_power(dev_priv, false);
15608
15609         intel_power_domains_verify_state(dev_priv);
15610
15611         intel_fbc_init_pipe_state(dev_priv);
15612 }
15613
15614 void intel_display_resume(struct drm_device *dev)
15615 {
15616         struct drm_i915_private *dev_priv = to_i915(dev);
15617         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15618         struct drm_modeset_acquire_ctx ctx;
15619         int ret;
15620
15621         dev_priv->modeset_restore_state = NULL;
15622         if (state)
15623                 state->acquire_ctx = &ctx;
15624
15625         drm_modeset_acquire_init(&ctx, 0);
15626
15627         while (1) {
15628                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15629                 if (ret != -EDEADLK)
15630                         break;
15631
15632                 drm_modeset_backoff(&ctx);
15633         }
15634
15635         if (!ret)
15636                 ret = __intel_display_resume(dev, state, &ctx);
15637
15638         intel_enable_ipc(dev_priv);
15639         drm_modeset_drop_locks(&ctx);
15640         drm_modeset_acquire_fini(&ctx);
15641
15642         if (ret)
15643                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15644         if (state)
15645                 drm_atomic_state_put(state);
15646 }
15647
15648 int intel_connector_register(struct drm_connector *connector)
15649 {
15650         struct intel_connector *intel_connector = to_intel_connector(connector);
15651         int ret;
15652
15653         ret = intel_backlight_device_register(intel_connector);
15654         if (ret)
15655                 goto err;
15656
15657         return 0;
15658
15659 err:
15660         return ret;
15661 }
15662
15663 void intel_connector_unregister(struct drm_connector *connector)
15664 {
15665         struct intel_connector *intel_connector = to_intel_connector(connector);
15666
15667         intel_backlight_device_unregister(intel_connector);
15668         intel_panel_destroy_backlight(connector);
15669 }
15670
15671 static void intel_hpd_poll_fini(struct drm_device *dev)
15672 {
15673         struct intel_connector *connector;
15674         struct drm_connector_list_iter conn_iter;
15675
15676         /* Kill all the work that may have been queued by hpd. */
15677         drm_connector_list_iter_begin(dev, &conn_iter);
15678         for_each_intel_connector_iter(connector, &conn_iter) {
15679                 if (connector->modeset_retry_work.func)
15680                         cancel_work_sync(&connector->modeset_retry_work);
15681                 if (connector->hdcp_shim) {
15682                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15683                         cancel_work_sync(&connector->hdcp_prop_work);
15684                 }
15685         }
15686         drm_connector_list_iter_end(&conn_iter);
15687 }
15688
15689 void intel_modeset_cleanup(struct drm_device *dev)
15690 {
15691         struct drm_i915_private *dev_priv = to_i915(dev);
15692
15693         flush_work(&dev_priv->atomic_helper.free_work);
15694         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15695
15696         intel_disable_gt_powersave(dev_priv);
15697
15698         /*
15699          * Interrupts and polling as the first thing to avoid creating havoc.
15700          * Too much stuff here (turning of connectors, ...) would
15701          * experience fancy races otherwise.
15702          */
15703         intel_irq_uninstall(dev_priv);
15704
15705         /*
15706          * Due to the hpd irq storm handling the hotplug work can re-arm the
15707          * poll handlers. Hence disable polling after hpd handling is shut down.
15708          */
15709         intel_hpd_poll_fini(dev);
15710
15711         /* poll work can call into fbdev, hence clean that up afterwards */
15712         intel_fbdev_fini(dev_priv);
15713
15714         intel_unregister_dsm_handler();
15715
15716         intel_fbc_global_disable(dev_priv);
15717
15718         /* flush any delayed tasks or pending work */
15719         flush_scheduled_work();
15720
15721         drm_mode_config_cleanup(dev);
15722
15723         intel_cleanup_overlay(dev_priv);
15724
15725         intel_cleanup_gt_powersave(dev_priv);
15726
15727         intel_teardown_gmbus(dev_priv);
15728
15729         destroy_workqueue(dev_priv->modeset_wq);
15730 }
15731
15732 void intel_connector_attach_encoder(struct intel_connector *connector,
15733                                     struct intel_encoder *encoder)
15734 {
15735         connector->encoder = encoder;
15736         drm_mode_connector_attach_encoder(&connector->base,
15737                                           &encoder->base);
15738 }
15739
15740 /*
15741  * set vga decode state - true == enable VGA decode
15742  */
15743 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15744 {
15745         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15746         u16 gmch_ctrl;
15747
15748         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15749                 DRM_ERROR("failed to read control word\n");
15750                 return -EIO;
15751         }
15752
15753         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15754                 return 0;
15755
15756         if (state)
15757                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15758         else
15759                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15760
15761         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15762                 DRM_ERROR("failed to write control word\n");
15763                 return -EIO;
15764         }
15765
15766         return 0;
15767 }
15768
15769 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15770
15771 struct intel_display_error_state {
15772
15773         u32 power_well_driver;
15774
15775         int num_transcoders;
15776
15777         struct intel_cursor_error_state {
15778                 u32 control;
15779                 u32 position;
15780                 u32 base;
15781                 u32 size;
15782         } cursor[I915_MAX_PIPES];
15783
15784         struct intel_pipe_error_state {
15785                 bool power_domain_on;
15786                 u32 source;
15787                 u32 stat;
15788         } pipe[I915_MAX_PIPES];
15789
15790         struct intel_plane_error_state {
15791                 u32 control;
15792                 u32 stride;
15793                 u32 size;
15794                 u32 pos;
15795                 u32 addr;
15796                 u32 surface;
15797                 u32 tile_offset;
15798         } plane[I915_MAX_PIPES];
15799
15800         struct intel_transcoder_error_state {
15801                 bool power_domain_on;
15802                 enum transcoder cpu_transcoder;
15803
15804                 u32 conf;
15805
15806                 u32 htotal;
15807                 u32 hblank;
15808                 u32 hsync;
15809                 u32 vtotal;
15810                 u32 vblank;
15811                 u32 vsync;
15812         } transcoder[4];
15813 };
15814
15815 struct intel_display_error_state *
15816 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15817 {
15818         struct intel_display_error_state *error;
15819         int transcoders[] = {
15820                 TRANSCODER_A,
15821                 TRANSCODER_B,
15822                 TRANSCODER_C,
15823                 TRANSCODER_EDP,
15824         };
15825         int i;
15826
15827         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15828                 return NULL;
15829
15830         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15831         if (error == NULL)
15832                 return NULL;
15833
15834         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15835                 error->power_well_driver =
15836                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
15837
15838         for_each_pipe(dev_priv, i) {
15839                 error->pipe[i].power_domain_on =
15840                         __intel_display_power_is_enabled(dev_priv,
15841                                                          POWER_DOMAIN_PIPE(i));
15842                 if (!error->pipe[i].power_domain_on)
15843                         continue;
15844
15845                 error->cursor[i].control = I915_READ(CURCNTR(i));
15846                 error->cursor[i].position = I915_READ(CURPOS(i));
15847                 error->cursor[i].base = I915_READ(CURBASE(i));
15848
15849                 error->plane[i].control = I915_READ(DSPCNTR(i));
15850                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15851                 if (INTEL_GEN(dev_priv) <= 3) {
15852                         error->plane[i].size = I915_READ(DSPSIZE(i));
15853                         error->plane[i].pos = I915_READ(DSPPOS(i));
15854                 }
15855                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15856                         error->plane[i].addr = I915_READ(DSPADDR(i));
15857                 if (INTEL_GEN(dev_priv) >= 4) {
15858                         error->plane[i].surface = I915_READ(DSPSURF(i));
15859                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15860                 }
15861
15862                 error->pipe[i].source = I915_READ(PIPESRC(i));
15863
15864                 if (HAS_GMCH_DISPLAY(dev_priv))
15865                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15866         }
15867
15868         /* Note: this does not include DSI transcoders. */
15869         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15870         if (HAS_DDI(dev_priv))
15871                 error->num_transcoders++; /* Account for eDP. */
15872
15873         for (i = 0; i < error->num_transcoders; i++) {
15874                 enum transcoder cpu_transcoder = transcoders[i];
15875
15876                 error->transcoder[i].power_domain_on =
15877                         __intel_display_power_is_enabled(dev_priv,
15878                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15879                 if (!error->transcoder[i].power_domain_on)
15880                         continue;
15881
15882                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15883
15884                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15885                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15886                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15887                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15888                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15889                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15890                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15891         }
15892
15893         return error;
15894 }
15895
15896 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15897
15898 void
15899 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15900                                 struct intel_display_error_state *error)
15901 {
15902         struct drm_i915_private *dev_priv = m->i915;
15903         int i;
15904
15905         if (!error)
15906                 return;
15907
15908         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15909         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15910                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15911                            error->power_well_driver);
15912         for_each_pipe(dev_priv, i) {
15913                 err_printf(m, "Pipe [%d]:\n", i);
15914                 err_printf(m, "  Power: %s\n",
15915                            onoff(error->pipe[i].power_domain_on));
15916                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15917                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15918
15919                 err_printf(m, "Plane [%d]:\n", i);
15920                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15921                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15922                 if (INTEL_GEN(dev_priv) <= 3) {
15923                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15924                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15925                 }
15926                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15927                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15928                 if (INTEL_GEN(dev_priv) >= 4) {
15929                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15930                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15931                 }
15932
15933                 err_printf(m, "Cursor [%d]:\n", i);
15934                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15935                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15936                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15937         }
15938
15939         for (i = 0; i < error->num_transcoders; i++) {
15940                 err_printf(m, "CPU transcoder: %s\n",
15941                            transcoder_name(error->transcoder[i].cpu_transcoder));
15942                 err_printf(m, "  Power: %s\n",
15943                            onoff(error->transcoder[i].power_domain_on));
15944                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15945                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15946                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15947                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15948                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15949                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15950                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15951         }
15952 }
15953
15954 #endif