]> Git Repo - J-linux.git/blob - drivers/gpu/drm/i915/intel_display.c
Merge tag 'drm-misc-next-2018-09-27' of git://anongit.freedesktop.org/drm/drm-misc...
[J-linux.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 <[email protected]>
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 <drm/drm_atomic_uapi.h>
50 #include <linux/dma_remapping.h>
51 #include <linux/reservation.h>
52
53 /* Primary plane formats for gen <= 3 */
54 static const uint32_t i8xx_primary_formats[] = {
55         DRM_FORMAT_C8,
56         DRM_FORMAT_RGB565,
57         DRM_FORMAT_XRGB1555,
58         DRM_FORMAT_XRGB8888,
59 };
60
61 /* Primary plane formats for gen >= 4 */
62 static const uint32_t i965_primary_formats[] = {
63         DRM_FORMAT_C8,
64         DRM_FORMAT_RGB565,
65         DRM_FORMAT_XRGB8888,
66         DRM_FORMAT_XBGR8888,
67         DRM_FORMAT_XRGB2101010,
68         DRM_FORMAT_XBGR2101010,
69 };
70
71 static const uint64_t i9xx_format_modifiers[] = {
72         I915_FORMAT_MOD_X_TILED,
73         DRM_FORMAT_MOD_LINEAR,
74         DRM_FORMAT_MOD_INVALID
75 };
76
77 static const uint32_t skl_primary_formats[] = {
78         DRM_FORMAT_C8,
79         DRM_FORMAT_RGB565,
80         DRM_FORMAT_XRGB8888,
81         DRM_FORMAT_XBGR8888,
82         DRM_FORMAT_ARGB8888,
83         DRM_FORMAT_ABGR8888,
84         DRM_FORMAT_XRGB2101010,
85         DRM_FORMAT_XBGR2101010,
86         DRM_FORMAT_YUYV,
87         DRM_FORMAT_YVYU,
88         DRM_FORMAT_UYVY,
89         DRM_FORMAT_VYUY,
90 };
91
92 static const uint32_t skl_pri_planar_formats[] = {
93         DRM_FORMAT_C8,
94         DRM_FORMAT_RGB565,
95         DRM_FORMAT_XRGB8888,
96         DRM_FORMAT_XBGR8888,
97         DRM_FORMAT_ARGB8888,
98         DRM_FORMAT_ABGR8888,
99         DRM_FORMAT_XRGB2101010,
100         DRM_FORMAT_XBGR2101010,
101         DRM_FORMAT_YUYV,
102         DRM_FORMAT_YVYU,
103         DRM_FORMAT_UYVY,
104         DRM_FORMAT_VYUY,
105         DRM_FORMAT_NV12,
106 };
107
108 static const uint64_t skl_format_modifiers_noccs[] = {
109         I915_FORMAT_MOD_Yf_TILED,
110         I915_FORMAT_MOD_Y_TILED,
111         I915_FORMAT_MOD_X_TILED,
112         DRM_FORMAT_MOD_LINEAR,
113         DRM_FORMAT_MOD_INVALID
114 };
115
116 static const uint64_t skl_format_modifiers_ccs[] = {
117         I915_FORMAT_MOD_Yf_TILED_CCS,
118         I915_FORMAT_MOD_Y_TILED_CCS,
119         I915_FORMAT_MOD_Yf_TILED,
120         I915_FORMAT_MOD_Y_TILED,
121         I915_FORMAT_MOD_X_TILED,
122         DRM_FORMAT_MOD_LINEAR,
123         DRM_FORMAT_MOD_INVALID
124 };
125
126 /* Cursor formats */
127 static const uint32_t intel_cursor_formats[] = {
128         DRM_FORMAT_ARGB8888,
129 };
130
131 static const uint64_t cursor_format_modifiers[] = {
132         DRM_FORMAT_MOD_LINEAR,
133         DRM_FORMAT_MOD_INVALID
134 };
135
136 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
137                                 struct intel_crtc_state *pipe_config);
138 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
139                                    struct intel_crtc_state *pipe_config);
140
141 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
142                                   struct drm_i915_gem_object *obj,
143                                   struct drm_mode_fb_cmd2 *mode_cmd);
144 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
145 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
146 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
147 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
148                                          struct intel_link_m_n *m_n,
149                                          struct intel_link_m_n *m2_n2);
150 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
151 static void haswell_set_pipeconf(struct drm_crtc *crtc);
152 static void haswell_set_pipemisc(struct drm_crtc *crtc);
153 static void vlv_prepare_pll(struct intel_crtc *crtc,
154                             const struct intel_crtc_state *pipe_config);
155 static void chv_prepare_pll(struct intel_crtc *crtc,
156                             const struct intel_crtc_state *pipe_config);
157 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
158 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
159 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
160                                     struct intel_crtc_state *crtc_state);
161 static void skylake_pfit_enable(struct intel_crtc *crtc);
162 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
163 static void ironlake_pfit_enable(struct intel_crtc *crtc);
164 static void intel_modeset_setup_hw_state(struct drm_device *dev,
165                                          struct drm_modeset_acquire_ctx *ctx);
166 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
167
168 struct intel_limit {
169         struct {
170                 int min, max;
171         } dot, vco, n, m, m1, m2, p, p1;
172
173         struct {
174                 int dot_limit;
175                 int p2_slow, p2_fast;
176         } p2;
177 };
178
179 /* returns HPLL frequency in kHz */
180 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
181 {
182         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
183
184         /* Obtain SKU information */
185         mutex_lock(&dev_priv->sb_lock);
186         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
187                 CCK_FUSE_HPLL_FREQ_MASK;
188         mutex_unlock(&dev_priv->sb_lock);
189
190         return vco_freq[hpll_freq] * 1000;
191 }
192
193 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
194                       const char *name, u32 reg, int ref_freq)
195 {
196         u32 val;
197         int divider;
198
199         mutex_lock(&dev_priv->sb_lock);
200         val = vlv_cck_read(dev_priv, reg);
201         mutex_unlock(&dev_priv->sb_lock);
202
203         divider = val & CCK_FREQUENCY_VALUES;
204
205         WARN((val & CCK_FREQUENCY_STATUS) !=
206              (divider << CCK_FREQUENCY_STATUS_SHIFT),
207              "%s change in progress\n", name);
208
209         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
210 }
211
212 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
213                            const char *name, u32 reg)
214 {
215         if (dev_priv->hpll_freq == 0)
216                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
217
218         return vlv_get_cck_clock(dev_priv, name, reg,
219                                  dev_priv->hpll_freq);
220 }
221
222 static void intel_update_czclk(struct drm_i915_private *dev_priv)
223 {
224         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
225                 return;
226
227         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
228                                                       CCK_CZ_CLOCK_CONTROL);
229
230         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
231 }
232
233 static inline u32 /* units of 100MHz */
234 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
235                     const struct intel_crtc_state *pipe_config)
236 {
237         if (HAS_DDI(dev_priv))
238                 return pipe_config->port_clock; /* SPLL */
239         else
240                 return dev_priv->fdi_pll_freq;
241 }
242
243 static const struct intel_limit intel_limits_i8xx_dac = {
244         .dot = { .min = 25000, .max = 350000 },
245         .vco = { .min = 908000, .max = 1512000 },
246         .n = { .min = 2, .max = 16 },
247         .m = { .min = 96, .max = 140 },
248         .m1 = { .min = 18, .max = 26 },
249         .m2 = { .min = 6, .max = 16 },
250         .p = { .min = 4, .max = 128 },
251         .p1 = { .min = 2, .max = 33 },
252         .p2 = { .dot_limit = 165000,
253                 .p2_slow = 4, .p2_fast = 2 },
254 };
255
256 static const struct intel_limit intel_limits_i8xx_dvo = {
257         .dot = { .min = 25000, .max = 350000 },
258         .vco = { .min = 908000, .max = 1512000 },
259         .n = { .min = 2, .max = 16 },
260         .m = { .min = 96, .max = 140 },
261         .m1 = { .min = 18, .max = 26 },
262         .m2 = { .min = 6, .max = 16 },
263         .p = { .min = 4, .max = 128 },
264         .p1 = { .min = 2, .max = 33 },
265         .p2 = { .dot_limit = 165000,
266                 .p2_slow = 4, .p2_fast = 4 },
267 };
268
269 static const struct intel_limit intel_limits_i8xx_lvds = {
270         .dot = { .min = 25000, .max = 350000 },
271         .vco = { .min = 908000, .max = 1512000 },
272         .n = { .min = 2, .max = 16 },
273         .m = { .min = 96, .max = 140 },
274         .m1 = { .min = 18, .max = 26 },
275         .m2 = { .min = 6, .max = 16 },
276         .p = { .min = 4, .max = 128 },
277         .p1 = { .min = 1, .max = 6 },
278         .p2 = { .dot_limit = 165000,
279                 .p2_slow = 14, .p2_fast = 7 },
280 };
281
282 static const struct intel_limit intel_limits_i9xx_sdvo = {
283         .dot = { .min = 20000, .max = 400000 },
284         .vco = { .min = 1400000, .max = 2800000 },
285         .n = { .min = 1, .max = 6 },
286         .m = { .min = 70, .max = 120 },
287         .m1 = { .min = 8, .max = 18 },
288         .m2 = { .min = 3, .max = 7 },
289         .p = { .min = 5, .max = 80 },
290         .p1 = { .min = 1, .max = 8 },
291         .p2 = { .dot_limit = 200000,
292                 .p2_slow = 10, .p2_fast = 5 },
293 };
294
295 static const struct intel_limit intel_limits_i9xx_lvds = {
296         .dot = { .min = 20000, .max = 400000 },
297         .vco = { .min = 1400000, .max = 2800000 },
298         .n = { .min = 1, .max = 6 },
299         .m = { .min = 70, .max = 120 },
300         .m1 = { .min = 8, .max = 18 },
301         .m2 = { .min = 3, .max = 7 },
302         .p = { .min = 7, .max = 98 },
303         .p1 = { .min = 1, .max = 8 },
304         .p2 = { .dot_limit = 112000,
305                 .p2_slow = 14, .p2_fast = 7 },
306 };
307
308
309 static const struct intel_limit intel_limits_g4x_sdvo = {
310         .dot = { .min = 25000, .max = 270000 },
311         .vco = { .min = 1750000, .max = 3500000},
312         .n = { .min = 1, .max = 4 },
313         .m = { .min = 104, .max = 138 },
314         .m1 = { .min = 17, .max = 23 },
315         .m2 = { .min = 5, .max = 11 },
316         .p = { .min = 10, .max = 30 },
317         .p1 = { .min = 1, .max = 3},
318         .p2 = { .dot_limit = 270000,
319                 .p2_slow = 10,
320                 .p2_fast = 10
321         },
322 };
323
324 static const struct intel_limit intel_limits_g4x_hdmi = {
325         .dot = { .min = 22000, .max = 400000 },
326         .vco = { .min = 1750000, .max = 3500000},
327         .n = { .min = 1, .max = 4 },
328         .m = { .min = 104, .max = 138 },
329         .m1 = { .min = 16, .max = 23 },
330         .m2 = { .min = 5, .max = 11 },
331         .p = { .min = 5, .max = 80 },
332         .p1 = { .min = 1, .max = 8},
333         .p2 = { .dot_limit = 165000,
334                 .p2_slow = 10, .p2_fast = 5 },
335 };
336
337 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
338         .dot = { .min = 20000, .max = 115000 },
339         .vco = { .min = 1750000, .max = 3500000 },
340         .n = { .min = 1, .max = 3 },
341         .m = { .min = 104, .max = 138 },
342         .m1 = { .min = 17, .max = 23 },
343         .m2 = { .min = 5, .max = 11 },
344         .p = { .min = 28, .max = 112 },
345         .p1 = { .min = 2, .max = 8 },
346         .p2 = { .dot_limit = 0,
347                 .p2_slow = 14, .p2_fast = 14
348         },
349 };
350
351 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
352         .dot = { .min = 80000, .max = 224000 },
353         .vco = { .min = 1750000, .max = 3500000 },
354         .n = { .min = 1, .max = 3 },
355         .m = { .min = 104, .max = 138 },
356         .m1 = { .min = 17, .max = 23 },
357         .m2 = { .min = 5, .max = 11 },
358         .p = { .min = 14, .max = 42 },
359         .p1 = { .min = 2, .max = 6 },
360         .p2 = { .dot_limit = 0,
361                 .p2_slow = 7, .p2_fast = 7
362         },
363 };
364
365 static const struct intel_limit intel_limits_pineview_sdvo = {
366         .dot = { .min = 20000, .max = 400000},
367         .vco = { .min = 1700000, .max = 3500000 },
368         /* Pineview's Ncounter is a ring counter */
369         .n = { .min = 3, .max = 6 },
370         .m = { .min = 2, .max = 256 },
371         /* Pineview only has one combined m divider, which we treat as m2. */
372         .m1 = { .min = 0, .max = 0 },
373         .m2 = { .min = 0, .max = 254 },
374         .p = { .min = 5, .max = 80 },
375         .p1 = { .min = 1, .max = 8 },
376         .p2 = { .dot_limit = 200000,
377                 .p2_slow = 10, .p2_fast = 5 },
378 };
379
380 static const struct intel_limit intel_limits_pineview_lvds = {
381         .dot = { .min = 20000, .max = 400000 },
382         .vco = { .min = 1700000, .max = 3500000 },
383         .n = { .min = 3, .max = 6 },
384         .m = { .min = 2, .max = 256 },
385         .m1 = { .min = 0, .max = 0 },
386         .m2 = { .min = 0, .max = 254 },
387         .p = { .min = 7, .max = 112 },
388         .p1 = { .min = 1, .max = 8 },
389         .p2 = { .dot_limit = 112000,
390                 .p2_slow = 14, .p2_fast = 14 },
391 };
392
393 /* Ironlake / Sandybridge
394  *
395  * We calculate clock using (register_value + 2) for N/M1/M2, so here
396  * the range value for them is (actual_value - 2).
397  */
398 static const struct intel_limit intel_limits_ironlake_dac = {
399         .dot = { .min = 25000, .max = 350000 },
400         .vco = { .min = 1760000, .max = 3510000 },
401         .n = { .min = 1, .max = 5 },
402         .m = { .min = 79, .max = 127 },
403         .m1 = { .min = 12, .max = 22 },
404         .m2 = { .min = 5, .max = 9 },
405         .p = { .min = 5, .max = 80 },
406         .p1 = { .min = 1, .max = 8 },
407         .p2 = { .dot_limit = 225000,
408                 .p2_slow = 10, .p2_fast = 5 },
409 };
410
411 static const struct intel_limit intel_limits_ironlake_single_lvds = {
412         .dot = { .min = 25000, .max = 350000 },
413         .vco = { .min = 1760000, .max = 3510000 },
414         .n = { .min = 1, .max = 3 },
415         .m = { .min = 79, .max = 118 },
416         .m1 = { .min = 12, .max = 22 },
417         .m2 = { .min = 5, .max = 9 },
418         .p = { .min = 28, .max = 112 },
419         .p1 = { .min = 2, .max = 8 },
420         .p2 = { .dot_limit = 225000,
421                 .p2_slow = 14, .p2_fast = 14 },
422 };
423
424 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
425         .dot = { .min = 25000, .max = 350000 },
426         .vco = { .min = 1760000, .max = 3510000 },
427         .n = { .min = 1, .max = 3 },
428         .m = { .min = 79, .max = 127 },
429         .m1 = { .min = 12, .max = 22 },
430         .m2 = { .min = 5, .max = 9 },
431         .p = { .min = 14, .max = 56 },
432         .p1 = { .min = 2, .max = 8 },
433         .p2 = { .dot_limit = 225000,
434                 .p2_slow = 7, .p2_fast = 7 },
435 };
436
437 /* LVDS 100mhz refclk limits. */
438 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
439         .dot = { .min = 25000, .max = 350000 },
440         .vco = { .min = 1760000, .max = 3510000 },
441         .n = { .min = 1, .max = 2 },
442         .m = { .min = 79, .max = 126 },
443         .m1 = { .min = 12, .max = 22 },
444         .m2 = { .min = 5, .max = 9 },
445         .p = { .min = 28, .max = 112 },
446         .p1 = { .min = 2, .max = 8 },
447         .p2 = { .dot_limit = 225000,
448                 .p2_slow = 14, .p2_fast = 14 },
449 };
450
451 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
452         .dot = { .min = 25000, .max = 350000 },
453         .vco = { .min = 1760000, .max = 3510000 },
454         .n = { .min = 1, .max = 3 },
455         .m = { .min = 79, .max = 126 },
456         .m1 = { .min = 12, .max = 22 },
457         .m2 = { .min = 5, .max = 9 },
458         .p = { .min = 14, .max = 42 },
459         .p1 = { .min = 2, .max = 6 },
460         .p2 = { .dot_limit = 225000,
461                 .p2_slow = 7, .p2_fast = 7 },
462 };
463
464 static const struct intel_limit intel_limits_vlv = {
465          /*
466           * These are the data rate limits (measured in fast clocks)
467           * since those are the strictest limits we have. The fast
468           * clock and actual rate limits are more relaxed, so checking
469           * them would make no difference.
470           */
471         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
472         .vco = { .min = 4000000, .max = 6000000 },
473         .n = { .min = 1, .max = 7 },
474         .m1 = { .min = 2, .max = 3 },
475         .m2 = { .min = 11, .max = 156 },
476         .p1 = { .min = 2, .max = 3 },
477         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
478 };
479
480 static const struct intel_limit intel_limits_chv = {
481         /*
482          * These are the data rate limits (measured in fast clocks)
483          * since those are the strictest limits we have.  The fast
484          * clock and actual rate limits are more relaxed, so checking
485          * them would make no difference.
486          */
487         .dot = { .min = 25000 * 5, .max = 540000 * 5},
488         .vco = { .min = 4800000, .max = 6480000 },
489         .n = { .min = 1, .max = 1 },
490         .m1 = { .min = 2, .max = 2 },
491         .m2 = { .min = 24 << 22, .max = 175 << 22 },
492         .p1 = { .min = 2, .max = 4 },
493         .p2 = { .p2_slow = 1, .p2_fast = 14 },
494 };
495
496 static const struct intel_limit intel_limits_bxt = {
497         /* FIXME: find real dot limits */
498         .dot = { .min = 0, .max = INT_MAX },
499         .vco = { .min = 4800000, .max = 6700000 },
500         .n = { .min = 1, .max = 1 },
501         .m1 = { .min = 2, .max = 2 },
502         /* FIXME: find real m2 limits */
503         .m2 = { .min = 2 << 22, .max = 255 << 22 },
504         .p1 = { .min = 2, .max = 4 },
505         .p2 = { .p2_slow = 1, .p2_fast = 20 },
506 };
507
508 static void
509 skl_wa_528(struct drm_i915_private *dev_priv, int pipe, bool enable)
510 {
511         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
512                 return;
513
514         if (enable)
515                 I915_WRITE(CHICKEN_PIPESL_1(pipe), HSW_FBCQ_DIS);
516         else
517                 I915_WRITE(CHICKEN_PIPESL_1(pipe), 0);
518 }
519
520 static void
521 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
522 {
523         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
524                 return;
525
526         if (enable)
527                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
528                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
529         else
530                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
531                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
532                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
533 }
534
535 static bool
536 needs_modeset(const struct drm_crtc_state *state)
537 {
538         return drm_atomic_crtc_needs_modeset(state);
539 }
540
541 /*
542  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
543  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
544  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
545  * The helpers' return value is the rate of the clock that is fed to the
546  * display engine's pipe which can be the above fast dot clock rate or a
547  * divided-down version of it.
548  */
549 /* m1 is reserved as 0 in Pineview, n is a ring counter */
550 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
551 {
552         clock->m = clock->m2 + 2;
553         clock->p = clock->p1 * clock->p2;
554         if (WARN_ON(clock->n == 0 || clock->p == 0))
555                 return 0;
556         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
557         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
558
559         return clock->dot;
560 }
561
562 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
563 {
564         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
565 }
566
567 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
568 {
569         clock->m = i9xx_dpll_compute_m(clock);
570         clock->p = clock->p1 * clock->p2;
571         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
572                 return 0;
573         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
574         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
575
576         return clock->dot;
577 }
578
579 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
580 {
581         clock->m = clock->m1 * clock->m2;
582         clock->p = clock->p1 * clock->p2;
583         if (WARN_ON(clock->n == 0 || clock->p == 0))
584                 return 0;
585         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
586         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
587
588         return clock->dot / 5;
589 }
590
591 int chv_calc_dpll_params(int refclk, struct dpll *clock)
592 {
593         clock->m = clock->m1 * clock->m2;
594         clock->p = clock->p1 * clock->p2;
595         if (WARN_ON(clock->n == 0 || clock->p == 0))
596                 return 0;
597         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
598                         clock->n << 22);
599         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
600
601         return clock->dot / 5;
602 }
603
604 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
605
606 /*
607  * Returns whether the given set of divisors are valid for a given refclk with
608  * the given connectors.
609  */
610 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
611                                const struct intel_limit *limit,
612                                const struct dpll *clock)
613 {
614         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
615                 INTELPllInvalid("n out of range\n");
616         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
617                 INTELPllInvalid("p1 out of range\n");
618         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
619                 INTELPllInvalid("m2 out of range\n");
620         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
621                 INTELPllInvalid("m1 out of range\n");
622
623         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
624             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
625                 if (clock->m1 <= clock->m2)
626                         INTELPllInvalid("m1 <= m2\n");
627
628         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
629             !IS_GEN9_LP(dev_priv)) {
630                 if (clock->p < limit->p.min || limit->p.max < clock->p)
631                         INTELPllInvalid("p out of range\n");
632                 if (clock->m < limit->m.min || limit->m.max < clock->m)
633                         INTELPllInvalid("m out of range\n");
634         }
635
636         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
637                 INTELPllInvalid("vco out of range\n");
638         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
639          * connector, etc., rather than just a single range.
640          */
641         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
642                 INTELPllInvalid("dot out of range\n");
643
644         return true;
645 }
646
647 static int
648 i9xx_select_p2_div(const struct intel_limit *limit,
649                    const struct intel_crtc_state *crtc_state,
650                    int target)
651 {
652         struct drm_device *dev = crtc_state->base.crtc->dev;
653
654         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
655                 /*
656                  * For LVDS just rely on its current settings for dual-channel.
657                  * We haven't figured out how to reliably set up different
658                  * single/dual channel state, if we even can.
659                  */
660                 if (intel_is_dual_link_lvds(dev))
661                         return limit->p2.p2_fast;
662                 else
663                         return limit->p2.p2_slow;
664         } else {
665                 if (target < limit->p2.dot_limit)
666                         return limit->p2.p2_slow;
667                 else
668                         return limit->p2.p2_fast;
669         }
670 }
671
672 /*
673  * Returns a set of divisors for the desired target clock with the given
674  * refclk, or FALSE.  The returned values represent the clock equation:
675  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
676  *
677  * Target and reference clocks are specified in kHz.
678  *
679  * If match_clock is provided, then best_clock P divider must match the P
680  * divider from @match_clock used for LVDS downclocking.
681  */
682 static bool
683 i9xx_find_best_dpll(const struct intel_limit *limit,
684                     struct intel_crtc_state *crtc_state,
685                     int target, int refclk, struct dpll *match_clock,
686                     struct dpll *best_clock)
687 {
688         struct drm_device *dev = crtc_state->base.crtc->dev;
689         struct dpll clock;
690         int err = target;
691
692         memset(best_clock, 0, sizeof(*best_clock));
693
694         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
695
696         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
697              clock.m1++) {
698                 for (clock.m2 = limit->m2.min;
699                      clock.m2 <= limit->m2.max; clock.m2++) {
700                         if (clock.m2 >= clock.m1)
701                                 break;
702                         for (clock.n = limit->n.min;
703                              clock.n <= limit->n.max; clock.n++) {
704                                 for (clock.p1 = limit->p1.min;
705                                         clock.p1 <= limit->p1.max; clock.p1++) {
706                                         int this_err;
707
708                                         i9xx_calc_dpll_params(refclk, &clock);
709                                         if (!intel_PLL_is_valid(to_i915(dev),
710                                                                 limit,
711                                                                 &clock))
712                                                 continue;
713                                         if (match_clock &&
714                                             clock.p != match_clock->p)
715                                                 continue;
716
717                                         this_err = abs(clock.dot - target);
718                                         if (this_err < err) {
719                                                 *best_clock = clock;
720                                                 err = this_err;
721                                         }
722                                 }
723                         }
724                 }
725         }
726
727         return (err != target);
728 }
729
730 /*
731  * Returns a set of divisors for the desired target clock with the given
732  * refclk, or FALSE.  The returned values represent the clock equation:
733  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
734  *
735  * Target and reference clocks are specified in kHz.
736  *
737  * If match_clock is provided, then best_clock P divider must match the P
738  * divider from @match_clock used for LVDS downclocking.
739  */
740 static bool
741 pnv_find_best_dpll(const struct intel_limit *limit,
742                    struct intel_crtc_state *crtc_state,
743                    int target, int refclk, struct dpll *match_clock,
744                    struct dpll *best_clock)
745 {
746         struct drm_device *dev = crtc_state->base.crtc->dev;
747         struct dpll clock;
748         int err = target;
749
750         memset(best_clock, 0, sizeof(*best_clock));
751
752         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
753
754         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
755              clock.m1++) {
756                 for (clock.m2 = limit->m2.min;
757                      clock.m2 <= limit->m2.max; clock.m2++) {
758                         for (clock.n = limit->n.min;
759                              clock.n <= limit->n.max; clock.n++) {
760                                 for (clock.p1 = limit->p1.min;
761                                         clock.p1 <= limit->p1.max; clock.p1++) {
762                                         int this_err;
763
764                                         pnv_calc_dpll_params(refclk, &clock);
765                                         if (!intel_PLL_is_valid(to_i915(dev),
766                                                                 limit,
767                                                                 &clock))
768                                                 continue;
769                                         if (match_clock &&
770                                             clock.p != match_clock->p)
771                                                 continue;
772
773                                         this_err = abs(clock.dot - target);
774                                         if (this_err < err) {
775                                                 *best_clock = clock;
776                                                 err = this_err;
777                                         }
778                                 }
779                         }
780                 }
781         }
782
783         return (err != target);
784 }
785
786 /*
787  * Returns a set of divisors for the desired target clock with the given
788  * refclk, or FALSE.  The returned values represent the clock equation:
789  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
790  *
791  * Target and reference clocks are specified in kHz.
792  *
793  * If match_clock is provided, then best_clock P divider must match the P
794  * divider from @match_clock used for LVDS downclocking.
795  */
796 static bool
797 g4x_find_best_dpll(const struct intel_limit *limit,
798                    struct intel_crtc_state *crtc_state,
799                    int target, int refclk, struct dpll *match_clock,
800                    struct dpll *best_clock)
801 {
802         struct drm_device *dev = crtc_state->base.crtc->dev;
803         struct dpll clock;
804         int max_n;
805         bool found = false;
806         /* approximately equals target * 0.00585 */
807         int err_most = (target >> 8) + (target >> 9);
808
809         memset(best_clock, 0, sizeof(*best_clock));
810
811         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
812
813         max_n = limit->n.max;
814         /* based on hardware requirement, prefer smaller n to precision */
815         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
816                 /* based on hardware requirement, prefere larger m1,m2 */
817                 for (clock.m1 = limit->m1.max;
818                      clock.m1 >= limit->m1.min; clock.m1--) {
819                         for (clock.m2 = limit->m2.max;
820                              clock.m2 >= limit->m2.min; clock.m2--) {
821                                 for (clock.p1 = limit->p1.max;
822                                      clock.p1 >= limit->p1.min; clock.p1--) {
823                                         int this_err;
824
825                                         i9xx_calc_dpll_params(refclk, &clock);
826                                         if (!intel_PLL_is_valid(to_i915(dev),
827                                                                 limit,
828                                                                 &clock))
829                                                 continue;
830
831                                         this_err = abs(clock.dot - target);
832                                         if (this_err < err_most) {
833                                                 *best_clock = clock;
834                                                 err_most = this_err;
835                                                 max_n = clock.n;
836                                                 found = true;
837                                         }
838                                 }
839                         }
840                 }
841         }
842         return found;
843 }
844
845 /*
846  * Check if the calculated PLL configuration is more optimal compared to the
847  * best configuration and error found so far. Return the calculated error.
848  */
849 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
850                                const struct dpll *calculated_clock,
851                                const struct dpll *best_clock,
852                                unsigned int best_error_ppm,
853                                unsigned int *error_ppm)
854 {
855         /*
856          * For CHV ignore the error and consider only the P value.
857          * Prefer a bigger P value based on HW requirements.
858          */
859         if (IS_CHERRYVIEW(to_i915(dev))) {
860                 *error_ppm = 0;
861
862                 return calculated_clock->p > best_clock->p;
863         }
864
865         if (WARN_ON_ONCE(!target_freq))
866                 return false;
867
868         *error_ppm = div_u64(1000000ULL *
869                                 abs(target_freq - calculated_clock->dot),
870                              target_freq);
871         /*
872          * Prefer a better P value over a better (smaller) error if the error
873          * is small. Ensure this preference for future configurations too by
874          * setting the error to 0.
875          */
876         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
877                 *error_ppm = 0;
878
879                 return true;
880         }
881
882         return *error_ppm + 10 < best_error_ppm;
883 }
884
885 /*
886  * Returns a set of divisors for the desired target clock with the given
887  * refclk, or FALSE.  The returned values represent the clock equation:
888  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
889  */
890 static bool
891 vlv_find_best_dpll(const struct intel_limit *limit,
892                    struct intel_crtc_state *crtc_state,
893                    int target, int refclk, struct dpll *match_clock,
894                    struct dpll *best_clock)
895 {
896         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
897         struct drm_device *dev = crtc->base.dev;
898         struct dpll clock;
899         unsigned int bestppm = 1000000;
900         /* min update 19.2 MHz */
901         int max_n = min(limit->n.max, refclk / 19200);
902         bool found = false;
903
904         target *= 5; /* fast clock */
905
906         memset(best_clock, 0, sizeof(*best_clock));
907
908         /* based on hardware requirement, prefer smaller n to precision */
909         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
910                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
911                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
912                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
913                                 clock.p = clock.p1 * clock.p2;
914                                 /* based on hardware requirement, prefer bigger m1,m2 values */
915                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
916                                         unsigned int ppm;
917
918                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
919                                                                      refclk * clock.m1);
920
921                                         vlv_calc_dpll_params(refclk, &clock);
922
923                                         if (!intel_PLL_is_valid(to_i915(dev),
924                                                                 limit,
925                                                                 &clock))
926                                                 continue;
927
928                                         if (!vlv_PLL_is_optimal(dev, target,
929                                                                 &clock,
930                                                                 best_clock,
931                                                                 bestppm, &ppm))
932                                                 continue;
933
934                                         *best_clock = clock;
935                                         bestppm = ppm;
936                                         found = true;
937                                 }
938                         }
939                 }
940         }
941
942         return found;
943 }
944
945 /*
946  * Returns a set of divisors for the desired target clock with the given
947  * refclk, or FALSE.  The returned values represent the clock equation:
948  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
949  */
950 static bool
951 chv_find_best_dpll(const struct intel_limit *limit,
952                    struct intel_crtc_state *crtc_state,
953                    int target, int refclk, struct dpll *match_clock,
954                    struct dpll *best_clock)
955 {
956         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
957         struct drm_device *dev = crtc->base.dev;
958         unsigned int best_error_ppm;
959         struct dpll clock;
960         uint64_t m2;
961         int found = false;
962
963         memset(best_clock, 0, sizeof(*best_clock));
964         best_error_ppm = 1000000;
965
966         /*
967          * Based on hardware doc, the n always set to 1, and m1 always
968          * set to 2.  If requires to support 200Mhz refclk, we need to
969          * revisit this because n may not 1 anymore.
970          */
971         clock.n = 1, clock.m1 = 2;
972         target *= 5;    /* fast clock */
973
974         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
975                 for (clock.p2 = limit->p2.p2_fast;
976                                 clock.p2 >= limit->p2.p2_slow;
977                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
978                         unsigned int error_ppm;
979
980                         clock.p = clock.p1 * clock.p2;
981
982                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
983                                         clock.n) << 22, refclk * clock.m1);
984
985                         if (m2 > INT_MAX/clock.m1)
986                                 continue;
987
988                         clock.m2 = m2;
989
990                         chv_calc_dpll_params(refclk, &clock);
991
992                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
993                                 continue;
994
995                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
996                                                 best_error_ppm, &error_ppm))
997                                 continue;
998
999                         *best_clock = clock;
1000                         best_error_ppm = error_ppm;
1001                         found = true;
1002                 }
1003         }
1004
1005         return found;
1006 }
1007
1008 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1009                         struct dpll *best_clock)
1010 {
1011         int refclk = 100000;
1012         const struct intel_limit *limit = &intel_limits_bxt;
1013
1014         return chv_find_best_dpll(limit, crtc_state,
1015                                   target_clock, refclk, NULL, best_clock);
1016 }
1017
1018 bool intel_crtc_active(struct intel_crtc *crtc)
1019 {
1020         /* Be paranoid as we can arrive here with only partial
1021          * state retrieved from the hardware during setup.
1022          *
1023          * We can ditch the adjusted_mode.crtc_clock check as soon
1024          * as Haswell has gained clock readout/fastboot support.
1025          *
1026          * We can ditch the crtc->primary->state->fb check as soon as we can
1027          * properly reconstruct framebuffers.
1028          *
1029          * FIXME: The intel_crtc->active here should be switched to
1030          * crtc->state->active once we have proper CRTC states wired up
1031          * for atomic.
1032          */
1033         return crtc->active && crtc->base.primary->state->fb &&
1034                 crtc->config->base.adjusted_mode.crtc_clock;
1035 }
1036
1037 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1038                                              enum pipe pipe)
1039 {
1040         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1041
1042         return crtc->config->cpu_transcoder;
1043 }
1044
1045 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1046                                     enum pipe pipe)
1047 {
1048         i915_reg_t reg = PIPEDSL(pipe);
1049         u32 line1, line2;
1050         u32 line_mask;
1051
1052         if (IS_GEN2(dev_priv))
1053                 line_mask = DSL_LINEMASK_GEN2;
1054         else
1055                 line_mask = DSL_LINEMASK_GEN3;
1056
1057         line1 = I915_READ(reg) & line_mask;
1058         msleep(5);
1059         line2 = I915_READ(reg) & line_mask;
1060
1061         return line1 != line2;
1062 }
1063
1064 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1065 {
1066         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1067         enum pipe pipe = crtc->pipe;
1068
1069         /* Wait for the display line to settle/start moving */
1070         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1071                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1072                           pipe_name(pipe), onoff(state));
1073 }
1074
1075 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1076 {
1077         wait_for_pipe_scanline_moving(crtc, false);
1078 }
1079
1080 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1081 {
1082         wait_for_pipe_scanline_moving(crtc, true);
1083 }
1084
1085 static void
1086 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1087 {
1088         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1089         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1090
1091         if (INTEL_GEN(dev_priv) >= 4) {
1092                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1093                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1094
1095                 /* Wait for the Pipe State to go off */
1096                 if (intel_wait_for_register(dev_priv,
1097                                             reg, I965_PIPECONF_ACTIVE, 0,
1098                                             100))
1099                         WARN(1, "pipe_off wait timed out\n");
1100         } else {
1101                 intel_wait_for_pipe_scanline_stopped(crtc);
1102         }
1103 }
1104
1105 /* Only for pre-ILK configs */
1106 void assert_pll(struct drm_i915_private *dev_priv,
1107                 enum pipe pipe, bool state)
1108 {
1109         u32 val;
1110         bool cur_state;
1111
1112         val = I915_READ(DPLL(pipe));
1113         cur_state = !!(val & DPLL_VCO_ENABLE);
1114         I915_STATE_WARN(cur_state != state,
1115              "PLL state assertion failure (expected %s, current %s)\n",
1116                         onoff(state), onoff(cur_state));
1117 }
1118
1119 /* XXX: the dsi pll is shared between MIPI DSI ports */
1120 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1121 {
1122         u32 val;
1123         bool cur_state;
1124
1125         mutex_lock(&dev_priv->sb_lock);
1126         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1127         mutex_unlock(&dev_priv->sb_lock);
1128
1129         cur_state = val & DSI_PLL_VCO_EN;
1130         I915_STATE_WARN(cur_state != state,
1131              "DSI PLL state assertion failure (expected %s, current %s)\n",
1132                         onoff(state), onoff(cur_state));
1133 }
1134
1135 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1136                           enum pipe pipe, bool state)
1137 {
1138         bool cur_state;
1139         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1140                                                                       pipe);
1141
1142         if (HAS_DDI(dev_priv)) {
1143                 /* DDI does not have a specific FDI_TX register */
1144                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1145                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1146         } else {
1147                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1148                 cur_state = !!(val & FDI_TX_ENABLE);
1149         }
1150         I915_STATE_WARN(cur_state != state,
1151              "FDI TX state assertion failure (expected %s, current %s)\n",
1152                         onoff(state), onoff(cur_state));
1153 }
1154 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1155 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1156
1157 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1158                           enum pipe pipe, bool state)
1159 {
1160         u32 val;
1161         bool cur_state;
1162
1163         val = I915_READ(FDI_RX_CTL(pipe));
1164         cur_state = !!(val & FDI_RX_ENABLE);
1165         I915_STATE_WARN(cur_state != state,
1166              "FDI RX state assertion failure (expected %s, current %s)\n",
1167                         onoff(state), onoff(cur_state));
1168 }
1169 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1170 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1171
1172 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1173                                       enum pipe pipe)
1174 {
1175         u32 val;
1176
1177         /* ILK FDI PLL is always enabled */
1178         if (IS_GEN5(dev_priv))
1179                 return;
1180
1181         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1182         if (HAS_DDI(dev_priv))
1183                 return;
1184
1185         val = I915_READ(FDI_TX_CTL(pipe));
1186         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1187 }
1188
1189 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1190                        enum pipe pipe, bool state)
1191 {
1192         u32 val;
1193         bool cur_state;
1194
1195         val = I915_READ(FDI_RX_CTL(pipe));
1196         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1197         I915_STATE_WARN(cur_state != state,
1198              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1199                         onoff(state), onoff(cur_state));
1200 }
1201
1202 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1203 {
1204         i915_reg_t pp_reg;
1205         u32 val;
1206         enum pipe panel_pipe = INVALID_PIPE;
1207         bool locked = true;
1208
1209         if (WARN_ON(HAS_DDI(dev_priv)))
1210                 return;
1211
1212         if (HAS_PCH_SPLIT(dev_priv)) {
1213                 u32 port_sel;
1214
1215                 pp_reg = PP_CONTROL(0);
1216                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1217
1218                 switch (port_sel) {
1219                 case PANEL_PORT_SELECT_LVDS:
1220                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1221                         break;
1222                 case PANEL_PORT_SELECT_DPA:
1223                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1224                         break;
1225                 case PANEL_PORT_SELECT_DPC:
1226                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1227                         break;
1228                 case PANEL_PORT_SELECT_DPD:
1229                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1230                         break;
1231                 default:
1232                         MISSING_CASE(port_sel);
1233                         break;
1234                 }
1235         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1236                 /* presumably write lock depends on pipe, not port select */
1237                 pp_reg = PP_CONTROL(pipe);
1238                 panel_pipe = pipe;
1239         } else {
1240                 u32 port_sel;
1241
1242                 pp_reg = PP_CONTROL(0);
1243                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1244
1245                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1246                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1247         }
1248
1249         val = I915_READ(pp_reg);
1250         if (!(val & PANEL_POWER_ON) ||
1251             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1252                 locked = false;
1253
1254         I915_STATE_WARN(panel_pipe == pipe && locked,
1255              "panel assertion failure, pipe %c regs locked\n",
1256              pipe_name(pipe));
1257 }
1258
1259 void assert_pipe(struct drm_i915_private *dev_priv,
1260                  enum pipe pipe, bool state)
1261 {
1262         bool cur_state;
1263         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1264                                                                       pipe);
1265         enum intel_display_power_domain power_domain;
1266
1267         /* we keep both pipes enabled on 830 */
1268         if (IS_I830(dev_priv))
1269                 state = true;
1270
1271         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1272         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1273                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1274                 cur_state = !!(val & PIPECONF_ENABLE);
1275
1276                 intel_display_power_put(dev_priv, power_domain);
1277         } else {
1278                 cur_state = false;
1279         }
1280
1281         I915_STATE_WARN(cur_state != state,
1282              "pipe %c assertion failure (expected %s, current %s)\n",
1283                         pipe_name(pipe), onoff(state), onoff(cur_state));
1284 }
1285
1286 static void assert_plane(struct intel_plane *plane, bool state)
1287 {
1288         enum pipe pipe;
1289         bool cur_state;
1290
1291         cur_state = plane->get_hw_state(plane, &pipe);
1292
1293         I915_STATE_WARN(cur_state != state,
1294                         "%s assertion failure (expected %s, current %s)\n",
1295                         plane->base.name, onoff(state), onoff(cur_state));
1296 }
1297
1298 #define assert_plane_enabled(p) assert_plane(p, true)
1299 #define assert_plane_disabled(p) assert_plane(p, false)
1300
1301 static void assert_planes_disabled(struct intel_crtc *crtc)
1302 {
1303         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1304         struct intel_plane *plane;
1305
1306         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1307                 assert_plane_disabled(plane);
1308 }
1309
1310 static void assert_vblank_disabled(struct drm_crtc *crtc)
1311 {
1312         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1313                 drm_crtc_vblank_put(crtc);
1314 }
1315
1316 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1317                                     enum pipe pipe)
1318 {
1319         u32 val;
1320         bool enabled;
1321
1322         val = I915_READ(PCH_TRANSCONF(pipe));
1323         enabled = !!(val & TRANS_ENABLE);
1324         I915_STATE_WARN(enabled,
1325              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1326              pipe_name(pipe));
1327 }
1328
1329 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1330                                    enum pipe pipe, enum port port,
1331                                    i915_reg_t dp_reg)
1332 {
1333         enum pipe port_pipe;
1334         bool state;
1335
1336         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1337
1338         I915_STATE_WARN(state && port_pipe == pipe,
1339                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1340                         port_name(port), pipe_name(pipe));
1341
1342         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1343                         "IBX PCH DP %c still using transcoder B\n",
1344                         port_name(port));
1345 }
1346
1347 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1348                                      enum pipe pipe, enum port port,
1349                                      i915_reg_t hdmi_reg)
1350 {
1351         enum pipe port_pipe;
1352         bool state;
1353
1354         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1355
1356         I915_STATE_WARN(state && port_pipe == pipe,
1357                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1358                         port_name(port), pipe_name(pipe));
1359
1360         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1361                         "IBX PCH HDMI %c still using transcoder B\n",
1362                         port_name(port));
1363 }
1364
1365 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1366                                       enum pipe pipe)
1367 {
1368         enum pipe port_pipe;
1369
1370         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1371         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1372         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1373
1374         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1375                         port_pipe == pipe,
1376                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1377                         pipe_name(pipe));
1378
1379         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1380                         port_pipe == pipe,
1381                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1382                         pipe_name(pipe));
1383
1384         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1385         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1386         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1387 }
1388
1389 static void _vlv_enable_pll(struct intel_crtc *crtc,
1390                             const struct intel_crtc_state *pipe_config)
1391 {
1392         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1393         enum pipe pipe = crtc->pipe;
1394
1395         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1396         POSTING_READ(DPLL(pipe));
1397         udelay(150);
1398
1399         if (intel_wait_for_register(dev_priv,
1400                                     DPLL(pipe),
1401                                     DPLL_LOCK_VLV,
1402                                     DPLL_LOCK_VLV,
1403                                     1))
1404                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1405 }
1406
1407 static void vlv_enable_pll(struct intel_crtc *crtc,
1408                            const struct intel_crtc_state *pipe_config)
1409 {
1410         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1411         enum pipe pipe = crtc->pipe;
1412
1413         assert_pipe_disabled(dev_priv, pipe);
1414
1415         /* PLL is protected by panel, make sure we can write it */
1416         assert_panel_unlocked(dev_priv, pipe);
1417
1418         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1419                 _vlv_enable_pll(crtc, pipe_config);
1420
1421         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1422         POSTING_READ(DPLL_MD(pipe));
1423 }
1424
1425
1426 static void _chv_enable_pll(struct intel_crtc *crtc,
1427                             const struct intel_crtc_state *pipe_config)
1428 {
1429         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1430         enum pipe pipe = crtc->pipe;
1431         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1432         u32 tmp;
1433
1434         mutex_lock(&dev_priv->sb_lock);
1435
1436         /* Enable back the 10bit clock to display controller */
1437         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1438         tmp |= DPIO_DCLKP_EN;
1439         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1440
1441         mutex_unlock(&dev_priv->sb_lock);
1442
1443         /*
1444          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1445          */
1446         udelay(1);
1447
1448         /* Enable PLL */
1449         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1450
1451         /* Check PLL is locked */
1452         if (intel_wait_for_register(dev_priv,
1453                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1454                                     1))
1455                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1456 }
1457
1458 static void chv_enable_pll(struct intel_crtc *crtc,
1459                            const struct intel_crtc_state *pipe_config)
1460 {
1461         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1462         enum pipe pipe = crtc->pipe;
1463
1464         assert_pipe_disabled(dev_priv, pipe);
1465
1466         /* PLL is protected by panel, make sure we can write it */
1467         assert_panel_unlocked(dev_priv, pipe);
1468
1469         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1470                 _chv_enable_pll(crtc, pipe_config);
1471
1472         if (pipe != PIPE_A) {
1473                 /*
1474                  * WaPixelRepeatModeFixForC0:chv
1475                  *
1476                  * DPLLCMD is AWOL. Use chicken bits to propagate
1477                  * the value from DPLLBMD to either pipe B or C.
1478                  */
1479                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1480                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1481                 I915_WRITE(CBR4_VLV, 0);
1482                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1483
1484                 /*
1485                  * DPLLB VGA mode also seems to cause problems.
1486                  * We should always have it disabled.
1487                  */
1488                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1489         } else {
1490                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1491                 POSTING_READ(DPLL_MD(pipe));
1492         }
1493 }
1494
1495 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1496 {
1497         struct intel_crtc *crtc;
1498         int count = 0;
1499
1500         for_each_intel_crtc(&dev_priv->drm, crtc) {
1501                 count += crtc->base.state->active &&
1502                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1503         }
1504
1505         return count;
1506 }
1507
1508 static void i9xx_enable_pll(struct intel_crtc *crtc,
1509                             const struct intel_crtc_state *crtc_state)
1510 {
1511         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1512         i915_reg_t reg = DPLL(crtc->pipe);
1513         u32 dpll = crtc_state->dpll_hw_state.dpll;
1514         int i;
1515
1516         assert_pipe_disabled(dev_priv, crtc->pipe);
1517
1518         /* PLL is protected by panel, make sure we can write it */
1519         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1520                 assert_panel_unlocked(dev_priv, crtc->pipe);
1521
1522         /* Enable DVO 2x clock on both PLLs if necessary */
1523         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1524                 /*
1525                  * It appears to be important that we don't enable this
1526                  * for the current pipe before otherwise configuring the
1527                  * PLL. No idea how this should be handled if multiple
1528                  * DVO outputs are enabled simultaneosly.
1529                  */
1530                 dpll |= DPLL_DVO_2X_MODE;
1531                 I915_WRITE(DPLL(!crtc->pipe),
1532                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1533         }
1534
1535         /*
1536          * Apparently we need to have VGA mode enabled prior to changing
1537          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1538          * dividers, even though the register value does change.
1539          */
1540         I915_WRITE(reg, 0);
1541
1542         I915_WRITE(reg, dpll);
1543
1544         /* Wait for the clocks to stabilize. */
1545         POSTING_READ(reg);
1546         udelay(150);
1547
1548         if (INTEL_GEN(dev_priv) >= 4) {
1549                 I915_WRITE(DPLL_MD(crtc->pipe),
1550                            crtc_state->dpll_hw_state.dpll_md);
1551         } else {
1552                 /* The pixel multiplier can only be updated once the
1553                  * DPLL is enabled and the clocks are stable.
1554                  *
1555                  * So write it again.
1556                  */
1557                 I915_WRITE(reg, dpll);
1558         }
1559
1560         /* We do this three times for luck */
1561         for (i = 0; i < 3; i++) {
1562                 I915_WRITE(reg, dpll);
1563                 POSTING_READ(reg);
1564                 udelay(150); /* wait for warmup */
1565         }
1566 }
1567
1568 static void i9xx_disable_pll(struct intel_crtc *crtc)
1569 {
1570         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1571         enum pipe pipe = crtc->pipe;
1572
1573         /* Disable DVO 2x clock on both PLLs if necessary */
1574         if (IS_I830(dev_priv) &&
1575             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1576             !intel_num_dvo_pipes(dev_priv)) {
1577                 I915_WRITE(DPLL(PIPE_B),
1578                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1579                 I915_WRITE(DPLL(PIPE_A),
1580                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1581         }
1582
1583         /* Don't disable pipe or pipe PLLs if needed */
1584         if (IS_I830(dev_priv))
1585                 return;
1586
1587         /* Make sure the pipe isn't still relying on us */
1588         assert_pipe_disabled(dev_priv, pipe);
1589
1590         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1591         POSTING_READ(DPLL(pipe));
1592 }
1593
1594 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1595 {
1596         u32 val;
1597
1598         /* Make sure the pipe isn't still relying on us */
1599         assert_pipe_disabled(dev_priv, pipe);
1600
1601         val = DPLL_INTEGRATED_REF_CLK_VLV |
1602                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1603         if (pipe != PIPE_A)
1604                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1605
1606         I915_WRITE(DPLL(pipe), val);
1607         POSTING_READ(DPLL(pipe));
1608 }
1609
1610 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1611 {
1612         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1613         u32 val;
1614
1615         /* Make sure the pipe isn't still relying on us */
1616         assert_pipe_disabled(dev_priv, pipe);
1617
1618         val = DPLL_SSC_REF_CLK_CHV |
1619                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1620         if (pipe != PIPE_A)
1621                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1622
1623         I915_WRITE(DPLL(pipe), val);
1624         POSTING_READ(DPLL(pipe));
1625
1626         mutex_lock(&dev_priv->sb_lock);
1627
1628         /* Disable 10bit clock to display controller */
1629         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1630         val &= ~DPIO_DCLKP_EN;
1631         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1632
1633         mutex_unlock(&dev_priv->sb_lock);
1634 }
1635
1636 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1637                          struct intel_digital_port *dport,
1638                          unsigned int expected_mask)
1639 {
1640         u32 port_mask;
1641         i915_reg_t dpll_reg;
1642
1643         switch (dport->base.port) {
1644         case PORT_B:
1645                 port_mask = DPLL_PORTB_READY_MASK;
1646                 dpll_reg = DPLL(0);
1647                 break;
1648         case PORT_C:
1649                 port_mask = DPLL_PORTC_READY_MASK;
1650                 dpll_reg = DPLL(0);
1651                 expected_mask <<= 4;
1652                 break;
1653         case PORT_D:
1654                 port_mask = DPLL_PORTD_READY_MASK;
1655                 dpll_reg = DPIO_PHY_STATUS;
1656                 break;
1657         default:
1658                 BUG();
1659         }
1660
1661         if (intel_wait_for_register(dev_priv,
1662                                     dpll_reg, port_mask, expected_mask,
1663                                     1000))
1664                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1665                      port_name(dport->base.port),
1666                      I915_READ(dpll_reg) & port_mask, expected_mask);
1667 }
1668
1669 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1670                                            enum pipe pipe)
1671 {
1672         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1673                                                                 pipe);
1674         i915_reg_t reg;
1675         uint32_t val, pipeconf_val;
1676
1677         /* Make sure PCH DPLL is enabled */
1678         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1679
1680         /* FDI must be feeding us bits for PCH ports */
1681         assert_fdi_tx_enabled(dev_priv, pipe);
1682         assert_fdi_rx_enabled(dev_priv, pipe);
1683
1684         if (HAS_PCH_CPT(dev_priv)) {
1685                 /* Workaround: Set the timing override bit before enabling the
1686                  * pch transcoder. */
1687                 reg = TRANS_CHICKEN2(pipe);
1688                 val = I915_READ(reg);
1689                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1690                 I915_WRITE(reg, val);
1691         }
1692
1693         reg = PCH_TRANSCONF(pipe);
1694         val = I915_READ(reg);
1695         pipeconf_val = I915_READ(PIPECONF(pipe));
1696
1697         if (HAS_PCH_IBX(dev_priv)) {
1698                 /*
1699                  * Make the BPC in transcoder be consistent with
1700                  * that in pipeconf reg. For HDMI we must use 8bpc
1701                  * here for both 8bpc and 12bpc.
1702                  */
1703                 val &= ~PIPECONF_BPC_MASK;
1704                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1705                         val |= PIPECONF_8BPC;
1706                 else
1707                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1708         }
1709
1710         val &= ~TRANS_INTERLACE_MASK;
1711         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1712                 if (HAS_PCH_IBX(dev_priv) &&
1713                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1714                         val |= TRANS_LEGACY_INTERLACED_ILK;
1715                 else
1716                         val |= TRANS_INTERLACED;
1717         else
1718                 val |= TRANS_PROGRESSIVE;
1719
1720         I915_WRITE(reg, val | TRANS_ENABLE);
1721         if (intel_wait_for_register(dev_priv,
1722                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1723                                     100))
1724                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1725 }
1726
1727 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1728                                       enum transcoder cpu_transcoder)
1729 {
1730         u32 val, pipeconf_val;
1731
1732         /* FDI must be feeding us bits for PCH ports */
1733         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1734         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1735
1736         /* Workaround: set timing override bit. */
1737         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1738         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1739         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1740
1741         val = TRANS_ENABLE;
1742         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1743
1744         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1745             PIPECONF_INTERLACED_ILK)
1746                 val |= TRANS_INTERLACED;
1747         else
1748                 val |= TRANS_PROGRESSIVE;
1749
1750         I915_WRITE(LPT_TRANSCONF, val);
1751         if (intel_wait_for_register(dev_priv,
1752                                     LPT_TRANSCONF,
1753                                     TRANS_STATE_ENABLE,
1754                                     TRANS_STATE_ENABLE,
1755                                     100))
1756                 DRM_ERROR("Failed to enable PCH transcoder\n");
1757 }
1758
1759 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1760                                             enum pipe pipe)
1761 {
1762         i915_reg_t reg;
1763         uint32_t val;
1764
1765         /* FDI relies on the transcoder */
1766         assert_fdi_tx_disabled(dev_priv, pipe);
1767         assert_fdi_rx_disabled(dev_priv, pipe);
1768
1769         /* Ports must be off as well */
1770         assert_pch_ports_disabled(dev_priv, pipe);
1771
1772         reg = PCH_TRANSCONF(pipe);
1773         val = I915_READ(reg);
1774         val &= ~TRANS_ENABLE;
1775         I915_WRITE(reg, val);
1776         /* wait for PCH transcoder off, transcoder state */
1777         if (intel_wait_for_register(dev_priv,
1778                                     reg, TRANS_STATE_ENABLE, 0,
1779                                     50))
1780                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1781
1782         if (HAS_PCH_CPT(dev_priv)) {
1783                 /* Workaround: Clear the timing override chicken bit again. */
1784                 reg = TRANS_CHICKEN2(pipe);
1785                 val = I915_READ(reg);
1786                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1787                 I915_WRITE(reg, val);
1788         }
1789 }
1790
1791 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1792 {
1793         u32 val;
1794
1795         val = I915_READ(LPT_TRANSCONF);
1796         val &= ~TRANS_ENABLE;
1797         I915_WRITE(LPT_TRANSCONF, val);
1798         /* wait for PCH transcoder off, transcoder state */
1799         if (intel_wait_for_register(dev_priv,
1800                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1801                                     50))
1802                 DRM_ERROR("Failed to disable PCH transcoder\n");
1803
1804         /* Workaround: clear timing override bit. */
1805         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1806         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1807         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1808 }
1809
1810 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1811 {
1812         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1813
1814         if (HAS_PCH_LPT(dev_priv))
1815                 return PIPE_A;
1816         else
1817                 return crtc->pipe;
1818 }
1819
1820 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1821 {
1822         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1823         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1824         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1825         enum pipe pipe = crtc->pipe;
1826         i915_reg_t reg;
1827         u32 val;
1828
1829         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1830
1831         assert_planes_disabled(crtc);
1832
1833         /*
1834          * A pipe without a PLL won't actually be able to drive bits from
1835          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1836          * need the check.
1837          */
1838         if (HAS_GMCH_DISPLAY(dev_priv)) {
1839                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1840                         assert_dsi_pll_enabled(dev_priv);
1841                 else
1842                         assert_pll_enabled(dev_priv, pipe);
1843         } else {
1844                 if (new_crtc_state->has_pch_encoder) {
1845                         /* if driving the PCH, we need FDI enabled */
1846                         assert_fdi_rx_pll_enabled(dev_priv,
1847                                                   intel_crtc_pch_transcoder(crtc));
1848                         assert_fdi_tx_pll_enabled(dev_priv,
1849                                                   (enum pipe) cpu_transcoder);
1850                 }
1851                 /* FIXME: assert CPU port conditions for SNB+ */
1852         }
1853
1854         reg = PIPECONF(cpu_transcoder);
1855         val = I915_READ(reg);
1856         if (val & PIPECONF_ENABLE) {
1857                 /* we keep both pipes enabled on 830 */
1858                 WARN_ON(!IS_I830(dev_priv));
1859                 return;
1860         }
1861
1862         I915_WRITE(reg, val | PIPECONF_ENABLE);
1863         POSTING_READ(reg);
1864
1865         /*
1866          * Until the pipe starts PIPEDSL reads will return a stale value,
1867          * which causes an apparent vblank timestamp jump when PIPEDSL
1868          * resets to its proper value. That also messes up the frame count
1869          * when it's derived from the timestamps. So let's wait for the
1870          * pipe to start properly before we call drm_crtc_vblank_on()
1871          */
1872         if (dev_priv->drm.max_vblank_count == 0)
1873                 intel_wait_for_pipe_scanline_moving(crtc);
1874 }
1875
1876 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1877 {
1878         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1879         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1880         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1881         enum pipe pipe = crtc->pipe;
1882         i915_reg_t reg;
1883         u32 val;
1884
1885         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1886
1887         /*
1888          * Make sure planes won't keep trying to pump pixels to us,
1889          * or we might hang the display.
1890          */
1891         assert_planes_disabled(crtc);
1892
1893         reg = PIPECONF(cpu_transcoder);
1894         val = I915_READ(reg);
1895         if ((val & PIPECONF_ENABLE) == 0)
1896                 return;
1897
1898         /*
1899          * Double wide has implications for planes
1900          * so best keep it disabled when not needed.
1901          */
1902         if (old_crtc_state->double_wide)
1903                 val &= ~PIPECONF_DOUBLE_WIDE;
1904
1905         /* Don't disable pipe or pipe PLLs if needed */
1906         if (!IS_I830(dev_priv))
1907                 val &= ~PIPECONF_ENABLE;
1908
1909         I915_WRITE(reg, val);
1910         if ((val & PIPECONF_ENABLE) == 0)
1911                 intel_wait_for_pipe_off(old_crtc_state);
1912 }
1913
1914 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1915 {
1916         return IS_GEN2(dev_priv) ? 2048 : 4096;
1917 }
1918
1919 static unsigned int
1920 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1921 {
1922         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1923         unsigned int cpp = fb->format->cpp[plane];
1924
1925         switch (fb->modifier) {
1926         case DRM_FORMAT_MOD_LINEAR:
1927                 return cpp;
1928         case I915_FORMAT_MOD_X_TILED:
1929                 if (IS_GEN2(dev_priv))
1930                         return 128;
1931                 else
1932                         return 512;
1933         case I915_FORMAT_MOD_Y_TILED_CCS:
1934                 if (plane == 1)
1935                         return 128;
1936                 /* fall through */
1937         case I915_FORMAT_MOD_Y_TILED:
1938                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1939                         return 128;
1940                 else
1941                         return 512;
1942         case I915_FORMAT_MOD_Yf_TILED_CCS:
1943                 if (plane == 1)
1944                         return 128;
1945                 /* fall through */
1946         case I915_FORMAT_MOD_Yf_TILED:
1947                 switch (cpp) {
1948                 case 1:
1949                         return 64;
1950                 case 2:
1951                 case 4:
1952                         return 128;
1953                 case 8:
1954                 case 16:
1955                         return 256;
1956                 default:
1957                         MISSING_CASE(cpp);
1958                         return cpp;
1959                 }
1960                 break;
1961         default:
1962                 MISSING_CASE(fb->modifier);
1963                 return cpp;
1964         }
1965 }
1966
1967 static unsigned int
1968 intel_tile_height(const struct drm_framebuffer *fb, int plane)
1969 {
1970         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1971                 return 1;
1972         else
1973                 return intel_tile_size(to_i915(fb->dev)) /
1974                         intel_tile_width_bytes(fb, plane);
1975 }
1976
1977 /* Return the tile dimensions in pixel units */
1978 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
1979                             unsigned int *tile_width,
1980                             unsigned int *tile_height)
1981 {
1982         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
1983         unsigned int cpp = fb->format->cpp[plane];
1984
1985         *tile_width = tile_width_bytes / cpp;
1986         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1987 }
1988
1989 unsigned int
1990 intel_fb_align_height(const struct drm_framebuffer *fb,
1991                       int plane, unsigned int height)
1992 {
1993         unsigned int tile_height = intel_tile_height(fb, plane);
1994
1995         return ALIGN(height, tile_height);
1996 }
1997
1998 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1999 {
2000         unsigned int size = 0;
2001         int i;
2002
2003         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2004                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2005
2006         return size;
2007 }
2008
2009 static void
2010 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2011                         const struct drm_framebuffer *fb,
2012                         unsigned int rotation)
2013 {
2014         view->type = I915_GGTT_VIEW_NORMAL;
2015         if (drm_rotation_90_or_270(rotation)) {
2016                 view->type = I915_GGTT_VIEW_ROTATED;
2017                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2018         }
2019 }
2020
2021 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2022 {
2023         if (IS_I830(dev_priv))
2024                 return 16 * 1024;
2025         else if (IS_I85X(dev_priv))
2026                 return 256;
2027         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2028                 return 32;
2029         else
2030                 return 4 * 1024;
2031 }
2032
2033 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2034 {
2035         if (INTEL_GEN(dev_priv) >= 9)
2036                 return 256 * 1024;
2037         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2038                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2039                 return 128 * 1024;
2040         else if (INTEL_GEN(dev_priv) >= 4)
2041                 return 4 * 1024;
2042         else
2043                 return 0;
2044 }
2045
2046 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2047                                          int plane)
2048 {
2049         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2050
2051         /* AUX_DIST needs only 4K alignment */
2052         if (plane == 1)
2053                 return 4096;
2054
2055         switch (fb->modifier) {
2056         case DRM_FORMAT_MOD_LINEAR:
2057                 return intel_linear_alignment(dev_priv);
2058         case I915_FORMAT_MOD_X_TILED:
2059                 if (INTEL_GEN(dev_priv) >= 9)
2060                         return 256 * 1024;
2061                 return 0;
2062         case I915_FORMAT_MOD_Y_TILED_CCS:
2063         case I915_FORMAT_MOD_Yf_TILED_CCS:
2064         case I915_FORMAT_MOD_Y_TILED:
2065         case I915_FORMAT_MOD_Yf_TILED:
2066                 return 1 * 1024 * 1024;
2067         default:
2068                 MISSING_CASE(fb->modifier);
2069                 return 0;
2070         }
2071 }
2072
2073 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2074 {
2075         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2076         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2077
2078         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2079 }
2080
2081 struct i915_vma *
2082 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2083                            unsigned int rotation,
2084                            bool uses_fence,
2085                            unsigned long *out_flags)
2086 {
2087         struct drm_device *dev = fb->dev;
2088         struct drm_i915_private *dev_priv = to_i915(dev);
2089         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2090         struct i915_ggtt_view view;
2091         struct i915_vma *vma;
2092         unsigned int pinctl;
2093         u32 alignment;
2094
2095         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2096
2097         alignment = intel_surf_alignment(fb, 0);
2098
2099         intel_fill_fb_ggtt_view(&view, fb, rotation);
2100
2101         /* Note that the w/a also requires 64 PTE of padding following the
2102          * bo. We currently fill all unused PTE with the shadow page and so
2103          * we should always have valid PTE following the scanout preventing
2104          * the VT-d warning.
2105          */
2106         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2107                 alignment = 256 * 1024;
2108
2109         /*
2110          * Global gtt pte registers are special registers which actually forward
2111          * writes to a chunk of system memory. Which means that there is no risk
2112          * that the register values disappear as soon as we call
2113          * intel_runtime_pm_put(), so it is correct to wrap only the
2114          * pin/unpin/fence and not more.
2115          */
2116         intel_runtime_pm_get(dev_priv);
2117
2118         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2119
2120         pinctl = 0;
2121
2122         /* Valleyview is definitely limited to scanning out the first
2123          * 512MiB. Lets presume this behaviour was inherited from the
2124          * g4x display engine and that all earlier gen are similarly
2125          * limited. Testing suggests that it is a little more
2126          * complicated than this. For example, Cherryview appears quite
2127          * happy to scanout from anywhere within its global aperture.
2128          */
2129         if (HAS_GMCH_DISPLAY(dev_priv))
2130                 pinctl |= PIN_MAPPABLE;
2131
2132         vma = i915_gem_object_pin_to_display_plane(obj,
2133                                                    alignment, &view, pinctl);
2134         if (IS_ERR(vma))
2135                 goto err;
2136
2137         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2138                 int ret;
2139
2140                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2141                  * fence, whereas 965+ only requires a fence if using
2142                  * framebuffer compression.  For simplicity, we always, when
2143                  * possible, install a fence as the cost is not that onerous.
2144                  *
2145                  * If we fail to fence the tiled scanout, then either the
2146                  * modeset will reject the change (which is highly unlikely as
2147                  * the affected systems, all but one, do not have unmappable
2148                  * space) or we will not be able to enable full powersaving
2149                  * techniques (also likely not to apply due to various limits
2150                  * FBC and the like impose on the size of the buffer, which
2151                  * presumably we violated anyway with this unmappable buffer).
2152                  * Anyway, it is presumably better to stumble onwards with
2153                  * something and try to run the system in a "less than optimal"
2154                  * mode that matches the user configuration.
2155                  */
2156                 ret = i915_vma_pin_fence(vma);
2157                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2158                         i915_gem_object_unpin_from_display_plane(vma);
2159                         vma = ERR_PTR(ret);
2160                         goto err;
2161                 }
2162
2163                 if (ret == 0 && vma->fence)
2164                         *out_flags |= PLANE_HAS_FENCE;
2165         }
2166
2167         i915_vma_get(vma);
2168 err:
2169         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2170
2171         intel_runtime_pm_put(dev_priv);
2172         return vma;
2173 }
2174
2175 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2176 {
2177         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2178
2179         if (flags & PLANE_HAS_FENCE)
2180                 i915_vma_unpin_fence(vma);
2181         i915_gem_object_unpin_from_display_plane(vma);
2182         i915_vma_put(vma);
2183 }
2184
2185 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2186                           unsigned int rotation)
2187 {
2188         if (drm_rotation_90_or_270(rotation))
2189                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2190         else
2191                 return fb->pitches[plane];
2192 }
2193
2194 /*
2195  * Convert the x/y offsets into a linear offset.
2196  * Only valid with 0/180 degree rotation, which is fine since linear
2197  * offset is only used with linear buffers on pre-hsw and tiled buffers
2198  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2199  */
2200 u32 intel_fb_xy_to_linear(int x, int y,
2201                           const struct intel_plane_state *state,
2202                           int plane)
2203 {
2204         const struct drm_framebuffer *fb = state->base.fb;
2205         unsigned int cpp = fb->format->cpp[plane];
2206         unsigned int pitch = fb->pitches[plane];
2207
2208         return y * pitch + x * cpp;
2209 }
2210
2211 /*
2212  * Add the x/y offsets derived from fb->offsets[] to the user
2213  * specified plane src x/y offsets. The resulting x/y offsets
2214  * specify the start of scanout from the beginning of the gtt mapping.
2215  */
2216 void intel_add_fb_offsets(int *x, int *y,
2217                           const struct intel_plane_state *state,
2218                           int plane)
2219
2220 {
2221         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2222         unsigned int rotation = state->base.rotation;
2223
2224         if (drm_rotation_90_or_270(rotation)) {
2225                 *x += intel_fb->rotated[plane].x;
2226                 *y += intel_fb->rotated[plane].y;
2227         } else {
2228                 *x += intel_fb->normal[plane].x;
2229                 *y += intel_fb->normal[plane].y;
2230         }
2231 }
2232
2233 static u32 __intel_adjust_tile_offset(int *x, int *y,
2234                                       unsigned int tile_width,
2235                                       unsigned int tile_height,
2236                                       unsigned int tile_size,
2237                                       unsigned int pitch_tiles,
2238                                       u32 old_offset,
2239                                       u32 new_offset)
2240 {
2241         unsigned int pitch_pixels = pitch_tiles * tile_width;
2242         unsigned int tiles;
2243
2244         WARN_ON(old_offset & (tile_size - 1));
2245         WARN_ON(new_offset & (tile_size - 1));
2246         WARN_ON(new_offset > old_offset);
2247
2248         tiles = (old_offset - new_offset) / tile_size;
2249
2250         *y += tiles / pitch_tiles * tile_height;
2251         *x += tiles % pitch_tiles * tile_width;
2252
2253         /* minimize x in case it got needlessly big */
2254         *y += *x / pitch_pixels * tile_height;
2255         *x %= pitch_pixels;
2256
2257         return new_offset;
2258 }
2259
2260 static u32 _intel_adjust_tile_offset(int *x, int *y,
2261                                      const struct drm_framebuffer *fb, int plane,
2262                                      unsigned int rotation,
2263                                      u32 old_offset, u32 new_offset)
2264 {
2265         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2266         unsigned int cpp = fb->format->cpp[plane];
2267         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2268
2269         WARN_ON(new_offset > old_offset);
2270
2271         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2272                 unsigned int tile_size, tile_width, tile_height;
2273                 unsigned int pitch_tiles;
2274
2275                 tile_size = intel_tile_size(dev_priv);
2276                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2277
2278                 if (drm_rotation_90_or_270(rotation)) {
2279                         pitch_tiles = pitch / tile_height;
2280                         swap(tile_width, tile_height);
2281                 } else {
2282                         pitch_tiles = pitch / (tile_width * cpp);
2283                 }
2284
2285                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2286                                            tile_size, pitch_tiles,
2287                                            old_offset, new_offset);
2288         } else {
2289                 old_offset += *y * pitch + *x * cpp;
2290
2291                 *y = (old_offset - new_offset) / pitch;
2292                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2293         }
2294
2295         return new_offset;
2296 }
2297
2298 /*
2299  * Adjust the tile offset by moving the difference into
2300  * the x/y offsets.
2301  */
2302 static u32 intel_adjust_tile_offset(int *x, int *y,
2303                                     const struct intel_plane_state *state, int plane,
2304                                     u32 old_offset, u32 new_offset)
2305 {
2306         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2307                                          state->base.rotation,
2308                                          old_offset, new_offset);
2309 }
2310
2311 /*
2312  * Computes the linear offset to the base tile and adjusts
2313  * x, y. bytes per pixel is assumed to be a power-of-two.
2314  *
2315  * In the 90/270 rotated case, x and y are assumed
2316  * to be already rotated to match the rotated GTT view, and
2317  * pitch is the tile_height aligned framebuffer height.
2318  *
2319  * This function is used when computing the derived information
2320  * under intel_framebuffer, so using any of that information
2321  * here is not allowed. Anything under drm_framebuffer can be
2322  * used. This is why the user has to pass in the pitch since it
2323  * is specified in the rotated orientation.
2324  */
2325 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2326                                       int *x, int *y,
2327                                       const struct drm_framebuffer *fb, int plane,
2328                                       unsigned int pitch,
2329                                       unsigned int rotation,
2330                                       u32 alignment)
2331 {
2332         uint64_t fb_modifier = fb->modifier;
2333         unsigned int cpp = fb->format->cpp[plane];
2334         u32 offset, offset_aligned;
2335
2336         if (alignment)
2337                 alignment--;
2338
2339         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2340                 unsigned int tile_size, tile_width, tile_height;
2341                 unsigned int tile_rows, tiles, pitch_tiles;
2342
2343                 tile_size = intel_tile_size(dev_priv);
2344                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2345
2346                 if (drm_rotation_90_or_270(rotation)) {
2347                         pitch_tiles = pitch / tile_height;
2348                         swap(tile_width, tile_height);
2349                 } else {
2350                         pitch_tiles = pitch / (tile_width * cpp);
2351                 }
2352
2353                 tile_rows = *y / tile_height;
2354                 *y %= tile_height;
2355
2356                 tiles = *x / tile_width;
2357                 *x %= tile_width;
2358
2359                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2360                 offset_aligned = offset & ~alignment;
2361
2362                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2363                                            tile_size, pitch_tiles,
2364                                            offset, offset_aligned);
2365         } else {
2366                 offset = *y * pitch + *x * cpp;
2367                 offset_aligned = offset & ~alignment;
2368
2369                 *y = (offset & alignment) / pitch;
2370                 *x = ((offset & alignment) - *y * pitch) / cpp;
2371         }
2372
2373         return offset_aligned;
2374 }
2375
2376 u32 intel_compute_tile_offset(int *x, int *y,
2377                               const struct intel_plane_state *state,
2378                               int plane)
2379 {
2380         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2381         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2382         const struct drm_framebuffer *fb = state->base.fb;
2383         unsigned int rotation = state->base.rotation;
2384         int pitch = intel_fb_pitch(fb, plane, rotation);
2385         u32 alignment;
2386
2387         if (intel_plane->id == PLANE_CURSOR)
2388                 alignment = intel_cursor_alignment(dev_priv);
2389         else
2390                 alignment = intel_surf_alignment(fb, plane);
2391
2392         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2393                                           rotation, alignment);
2394 }
2395
2396 /* Convert the fb->offset[] into x/y offsets */
2397 static int intel_fb_offset_to_xy(int *x, int *y,
2398                                  const struct drm_framebuffer *fb, int plane)
2399 {
2400         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2401
2402         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2403             fb->offsets[plane] % intel_tile_size(dev_priv))
2404                 return -EINVAL;
2405
2406         *x = 0;
2407         *y = 0;
2408
2409         _intel_adjust_tile_offset(x, y,
2410                                   fb, plane, DRM_MODE_ROTATE_0,
2411                                   fb->offsets[plane], 0);
2412
2413         return 0;
2414 }
2415
2416 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2417 {
2418         switch (fb_modifier) {
2419         case I915_FORMAT_MOD_X_TILED:
2420                 return I915_TILING_X;
2421         case I915_FORMAT_MOD_Y_TILED:
2422         case I915_FORMAT_MOD_Y_TILED_CCS:
2423                 return I915_TILING_Y;
2424         default:
2425                 return I915_TILING_NONE;
2426         }
2427 }
2428
2429 /*
2430  * From the Sky Lake PRM:
2431  * "The Color Control Surface (CCS) contains the compression status of
2432  *  the cache-line pairs. The compression state of the cache-line pair
2433  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2434  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2435  *  cache-line-pairs. CCS is always Y tiled."
2436  *
2437  * Since cache line pairs refers to horizontally adjacent cache lines,
2438  * each cache line in the CCS corresponds to an area of 32x16 cache
2439  * lines on the main surface. Since each pixel is 4 bytes, this gives
2440  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2441  * main surface.
2442  */
2443 static const struct drm_format_info ccs_formats[] = {
2444         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2445         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2446         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2447         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2448 };
2449
2450 static const struct drm_format_info *
2451 lookup_format_info(const struct drm_format_info formats[],
2452                    int num_formats, u32 format)
2453 {
2454         int i;
2455
2456         for (i = 0; i < num_formats; i++) {
2457                 if (formats[i].format == format)
2458                         return &formats[i];
2459         }
2460
2461         return NULL;
2462 }
2463
2464 static const struct drm_format_info *
2465 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2466 {
2467         switch (cmd->modifier[0]) {
2468         case I915_FORMAT_MOD_Y_TILED_CCS:
2469         case I915_FORMAT_MOD_Yf_TILED_CCS:
2470                 return lookup_format_info(ccs_formats,
2471                                           ARRAY_SIZE(ccs_formats),
2472                                           cmd->pixel_format);
2473         default:
2474                 return NULL;
2475         }
2476 }
2477
2478 bool is_ccs_modifier(u64 modifier)
2479 {
2480         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2481                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2482 }
2483
2484 static int
2485 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2486                    struct drm_framebuffer *fb)
2487 {
2488         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2489         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2490         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2491         u32 gtt_offset_rotated = 0;
2492         unsigned int max_size = 0;
2493         int i, num_planes = fb->format->num_planes;
2494         unsigned int tile_size = intel_tile_size(dev_priv);
2495
2496         for (i = 0; i < num_planes; i++) {
2497                 unsigned int width, height;
2498                 unsigned int cpp, size;
2499                 u32 offset;
2500                 int x, y;
2501                 int ret;
2502
2503                 cpp = fb->format->cpp[i];
2504                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2505                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2506
2507                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2508                 if (ret) {
2509                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2510                                       i, fb->offsets[i]);
2511                         return ret;
2512                 }
2513
2514                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2515                         int hsub = fb->format->hsub;
2516                         int vsub = fb->format->vsub;
2517                         int tile_width, tile_height;
2518                         int main_x, main_y;
2519                         int ccs_x, ccs_y;
2520
2521                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2522                         tile_width *= hsub;
2523                         tile_height *= vsub;
2524
2525                         ccs_x = (x * hsub) % tile_width;
2526                         ccs_y = (y * vsub) % tile_height;
2527                         main_x = intel_fb->normal[0].x % tile_width;
2528                         main_y = intel_fb->normal[0].y % tile_height;
2529
2530                         /*
2531                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2532                          * x/y offsets must match between CCS and the main surface.
2533                          */
2534                         if (main_x != ccs_x || main_y != ccs_y) {
2535                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2536                                               main_x, main_y,
2537                                               ccs_x, ccs_y,
2538                                               intel_fb->normal[0].x,
2539                                               intel_fb->normal[0].y,
2540                                               x, y);
2541                                 return -EINVAL;
2542                         }
2543                 }
2544
2545                 /*
2546                  * The fence (if used) is aligned to the start of the object
2547                  * so having the framebuffer wrap around across the edge of the
2548                  * fenced region doesn't really work. We have no API to configure
2549                  * the fence start offset within the object (nor could we probably
2550                  * on gen2/3). So it's just easier if we just require that the
2551                  * fb layout agrees with the fence layout. We already check that the
2552                  * fb stride matches the fence stride elsewhere.
2553                  */
2554                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2555                     (x + width) * cpp > fb->pitches[i]) {
2556                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2557                                       i, fb->offsets[i]);
2558                         return -EINVAL;
2559                 }
2560
2561                 /*
2562                  * First pixel of the framebuffer from
2563                  * the start of the normal gtt mapping.
2564                  */
2565                 intel_fb->normal[i].x = x;
2566                 intel_fb->normal[i].y = y;
2567
2568                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2569                                                     fb, i, fb->pitches[i],
2570                                                     DRM_MODE_ROTATE_0, tile_size);
2571                 offset /= tile_size;
2572
2573                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2574                         unsigned int tile_width, tile_height;
2575                         unsigned int pitch_tiles;
2576                         struct drm_rect r;
2577
2578                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2579
2580                         rot_info->plane[i].offset = offset;
2581                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2582                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2583                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2584
2585                         intel_fb->rotated[i].pitch =
2586                                 rot_info->plane[i].height * tile_height;
2587
2588                         /* how many tiles does this plane need */
2589                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2590                         /*
2591                          * If the plane isn't horizontally tile aligned,
2592                          * we need one more tile.
2593                          */
2594                         if (x != 0)
2595                                 size++;
2596
2597                         /* rotate the x/y offsets to match the GTT view */
2598                         r.x1 = x;
2599                         r.y1 = y;
2600                         r.x2 = x + width;
2601                         r.y2 = y + height;
2602                         drm_rect_rotate(&r,
2603                                         rot_info->plane[i].width * tile_width,
2604                                         rot_info->plane[i].height * tile_height,
2605                                         DRM_MODE_ROTATE_270);
2606                         x = r.x1;
2607                         y = r.y1;
2608
2609                         /* rotate the tile dimensions to match the GTT view */
2610                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2611                         swap(tile_width, tile_height);
2612
2613                         /*
2614                          * We only keep the x/y offsets, so push all of the
2615                          * gtt offset into the x/y offsets.
2616                          */
2617                         __intel_adjust_tile_offset(&x, &y,
2618                                                    tile_width, tile_height,
2619                                                    tile_size, pitch_tiles,
2620                                                    gtt_offset_rotated * tile_size, 0);
2621
2622                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2623
2624                         /*
2625                          * First pixel of the framebuffer from
2626                          * the start of the rotated gtt mapping.
2627                          */
2628                         intel_fb->rotated[i].x = x;
2629                         intel_fb->rotated[i].y = y;
2630                 } else {
2631                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2632                                             x * cpp, tile_size);
2633                 }
2634
2635                 /* how many tiles in total needed in the bo */
2636                 max_size = max(max_size, offset + size);
2637         }
2638
2639         if (max_size * tile_size > obj->base.size) {
2640                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2641                               max_size * tile_size, obj->base.size);
2642                 return -EINVAL;
2643         }
2644
2645         return 0;
2646 }
2647
2648 static int i9xx_format_to_fourcc(int format)
2649 {
2650         switch (format) {
2651         case DISPPLANE_8BPP:
2652                 return DRM_FORMAT_C8;
2653         case DISPPLANE_BGRX555:
2654                 return DRM_FORMAT_XRGB1555;
2655         case DISPPLANE_BGRX565:
2656                 return DRM_FORMAT_RGB565;
2657         default:
2658         case DISPPLANE_BGRX888:
2659                 return DRM_FORMAT_XRGB8888;
2660         case DISPPLANE_RGBX888:
2661                 return DRM_FORMAT_XBGR8888;
2662         case DISPPLANE_BGRX101010:
2663                 return DRM_FORMAT_XRGB2101010;
2664         case DISPPLANE_RGBX101010:
2665                 return DRM_FORMAT_XBGR2101010;
2666         }
2667 }
2668
2669 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2670 {
2671         switch (format) {
2672         case PLANE_CTL_FORMAT_RGB_565:
2673                 return DRM_FORMAT_RGB565;
2674         case PLANE_CTL_FORMAT_NV12:
2675                 return DRM_FORMAT_NV12;
2676         default:
2677         case PLANE_CTL_FORMAT_XRGB_8888:
2678                 if (rgb_order) {
2679                         if (alpha)
2680                                 return DRM_FORMAT_ABGR8888;
2681                         else
2682                                 return DRM_FORMAT_XBGR8888;
2683                 } else {
2684                         if (alpha)
2685                                 return DRM_FORMAT_ARGB8888;
2686                         else
2687                                 return DRM_FORMAT_XRGB8888;
2688                 }
2689         case PLANE_CTL_FORMAT_XRGB_2101010:
2690                 if (rgb_order)
2691                         return DRM_FORMAT_XBGR2101010;
2692                 else
2693                         return DRM_FORMAT_XRGB2101010;
2694         }
2695 }
2696
2697 static bool
2698 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2699                               struct intel_initial_plane_config *plane_config)
2700 {
2701         struct drm_device *dev = crtc->base.dev;
2702         struct drm_i915_private *dev_priv = to_i915(dev);
2703         struct drm_i915_gem_object *obj = NULL;
2704         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2705         struct drm_framebuffer *fb = &plane_config->fb->base;
2706         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2707         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2708                                     PAGE_SIZE);
2709
2710         size_aligned -= base_aligned;
2711
2712         if (plane_config->size == 0)
2713                 return false;
2714
2715         /* If the FB is too big, just don't use it since fbdev is not very
2716          * important and we should probably use that space with FBC or other
2717          * features. */
2718         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2719                 return false;
2720
2721         mutex_lock(&dev->struct_mutex);
2722         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2723                                                              base_aligned,
2724                                                              base_aligned,
2725                                                              size_aligned);
2726         mutex_unlock(&dev->struct_mutex);
2727         if (!obj)
2728                 return false;
2729
2730         if (plane_config->tiling == I915_TILING_X)
2731                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2732
2733         mode_cmd.pixel_format = fb->format->format;
2734         mode_cmd.width = fb->width;
2735         mode_cmd.height = fb->height;
2736         mode_cmd.pitches[0] = fb->pitches[0];
2737         mode_cmd.modifier[0] = fb->modifier;
2738         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2739
2740         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2741                 DRM_DEBUG_KMS("intel fb init failed\n");
2742                 goto out_unref_obj;
2743         }
2744
2745
2746         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2747         return true;
2748
2749 out_unref_obj:
2750         i915_gem_object_put(obj);
2751         return false;
2752 }
2753
2754 static void
2755 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2756                         struct intel_plane_state *plane_state,
2757                         bool visible)
2758 {
2759         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2760
2761         plane_state->base.visible = visible;
2762
2763         /* FIXME pre-g4x don't work like this */
2764         if (visible) {
2765                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2766                 crtc_state->active_planes |= BIT(plane->id);
2767         } else {
2768                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2769                 crtc_state->active_planes &= ~BIT(plane->id);
2770         }
2771
2772         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2773                       crtc_state->base.crtc->name,
2774                       crtc_state->active_planes);
2775 }
2776
2777 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2778                                          struct intel_plane *plane)
2779 {
2780         struct intel_crtc_state *crtc_state =
2781                 to_intel_crtc_state(crtc->base.state);
2782         struct intel_plane_state *plane_state =
2783                 to_intel_plane_state(plane->base.state);
2784
2785         intel_set_plane_visible(crtc_state, plane_state, false);
2786
2787         if (plane->id == PLANE_PRIMARY)
2788                 intel_pre_disable_primary_noatomic(&crtc->base);
2789
2790         trace_intel_disable_plane(&plane->base, crtc);
2791         plane->disable_plane(plane, crtc);
2792 }
2793
2794 static void
2795 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2796                              struct intel_initial_plane_config *plane_config)
2797 {
2798         struct drm_device *dev = intel_crtc->base.dev;
2799         struct drm_i915_private *dev_priv = to_i915(dev);
2800         struct drm_crtc *c;
2801         struct drm_i915_gem_object *obj;
2802         struct drm_plane *primary = intel_crtc->base.primary;
2803         struct drm_plane_state *plane_state = primary->state;
2804         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2805         struct intel_plane *intel_plane = to_intel_plane(primary);
2806         struct intel_plane_state *intel_state =
2807                 to_intel_plane_state(plane_state);
2808         struct drm_framebuffer *fb;
2809
2810         if (!plane_config->fb)
2811                 return;
2812
2813         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2814                 fb = &plane_config->fb->base;
2815                 goto valid_fb;
2816         }
2817
2818         kfree(plane_config->fb);
2819
2820         /*
2821          * Failed to alloc the obj, check to see if we should share
2822          * an fb with another CRTC instead
2823          */
2824         for_each_crtc(dev, c) {
2825                 struct intel_plane_state *state;
2826
2827                 if (c == &intel_crtc->base)
2828                         continue;
2829
2830                 if (!to_intel_crtc(c)->active)
2831                         continue;
2832
2833                 state = to_intel_plane_state(c->primary->state);
2834                 if (!state->vma)
2835                         continue;
2836
2837                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2838                         fb = state->base.fb;
2839                         drm_framebuffer_get(fb);
2840                         goto valid_fb;
2841                 }
2842         }
2843
2844         /*
2845          * We've failed to reconstruct the BIOS FB.  Current display state
2846          * indicates that the primary plane is visible, but has a NULL FB,
2847          * which will lead to problems later if we don't fix it up.  The
2848          * simplest solution is to just disable the primary plane now and
2849          * pretend the BIOS never had it enabled.
2850          */
2851         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2852
2853         return;
2854
2855 valid_fb:
2856         mutex_lock(&dev->struct_mutex);
2857         intel_state->vma =
2858                 intel_pin_and_fence_fb_obj(fb,
2859                                            primary->state->rotation,
2860                                            intel_plane_uses_fence(intel_state),
2861                                            &intel_state->flags);
2862         mutex_unlock(&dev->struct_mutex);
2863         if (IS_ERR(intel_state->vma)) {
2864                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2865                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2866
2867                 intel_state->vma = NULL;
2868                 drm_framebuffer_put(fb);
2869                 return;
2870         }
2871
2872         obj = intel_fb_obj(fb);
2873         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2874
2875         plane_state->src_x = 0;
2876         plane_state->src_y = 0;
2877         plane_state->src_w = fb->width << 16;
2878         plane_state->src_h = fb->height << 16;
2879
2880         plane_state->crtc_x = 0;
2881         plane_state->crtc_y = 0;
2882         plane_state->crtc_w = fb->width;
2883         plane_state->crtc_h = fb->height;
2884
2885         intel_state->base.src = drm_plane_state_src(plane_state);
2886         intel_state->base.dst = drm_plane_state_dest(plane_state);
2887
2888         if (i915_gem_object_is_tiled(obj))
2889                 dev_priv->preserve_bios_swizzle = true;
2890
2891         plane_state->fb = fb;
2892         plane_state->crtc = &intel_crtc->base;
2893
2894         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2895                                 to_intel_plane_state(plane_state),
2896                                 true);
2897
2898         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2899                   &obj->frontbuffer_bits);
2900 }
2901
2902 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2903                                unsigned int rotation)
2904 {
2905         int cpp = fb->format->cpp[plane];
2906
2907         switch (fb->modifier) {
2908         case DRM_FORMAT_MOD_LINEAR:
2909         case I915_FORMAT_MOD_X_TILED:
2910                 switch (cpp) {
2911                 case 8:
2912                         return 4096;
2913                 case 4:
2914                 case 2:
2915                 case 1:
2916                         return 8192;
2917                 default:
2918                         MISSING_CASE(cpp);
2919                         break;
2920                 }
2921                 break;
2922         case I915_FORMAT_MOD_Y_TILED_CCS:
2923         case I915_FORMAT_MOD_Yf_TILED_CCS:
2924                 /* FIXME AUX plane? */
2925         case I915_FORMAT_MOD_Y_TILED:
2926         case I915_FORMAT_MOD_Yf_TILED:
2927                 switch (cpp) {
2928                 case 8:
2929                         return 2048;
2930                 case 4:
2931                         return 4096;
2932                 case 2:
2933                 case 1:
2934                         return 8192;
2935                 default:
2936                         MISSING_CASE(cpp);
2937                         break;
2938                 }
2939                 break;
2940         default:
2941                 MISSING_CASE(fb->modifier);
2942         }
2943
2944         return 2048;
2945 }
2946
2947 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2948                                            int main_x, int main_y, u32 main_offset)
2949 {
2950         const struct drm_framebuffer *fb = plane_state->base.fb;
2951         int hsub = fb->format->hsub;
2952         int vsub = fb->format->vsub;
2953         int aux_x = plane_state->aux.x;
2954         int aux_y = plane_state->aux.y;
2955         u32 aux_offset = plane_state->aux.offset;
2956         u32 alignment = intel_surf_alignment(fb, 1);
2957
2958         while (aux_offset >= main_offset && aux_y <= main_y) {
2959                 int x, y;
2960
2961                 if (aux_x == main_x && aux_y == main_y)
2962                         break;
2963
2964                 if (aux_offset == 0)
2965                         break;
2966
2967                 x = aux_x / hsub;
2968                 y = aux_y / vsub;
2969                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
2970                                                       aux_offset, aux_offset - alignment);
2971                 aux_x = x * hsub + aux_x % hsub;
2972                 aux_y = y * vsub + aux_y % vsub;
2973         }
2974
2975         if (aux_x != main_x || aux_y != main_y)
2976                 return false;
2977
2978         plane_state->aux.offset = aux_offset;
2979         plane_state->aux.x = aux_x;
2980         plane_state->aux.y = aux_y;
2981
2982         return true;
2983 }
2984
2985 static int skl_check_main_surface(const struct intel_crtc_state *crtc_state,
2986                                   struct intel_plane_state *plane_state)
2987 {
2988         struct drm_i915_private *dev_priv =
2989                 to_i915(plane_state->base.plane->dev);
2990         const struct drm_framebuffer *fb = plane_state->base.fb;
2991         unsigned int rotation = plane_state->base.rotation;
2992         int x = plane_state->base.src.x1 >> 16;
2993         int y = plane_state->base.src.y1 >> 16;
2994         int w = drm_rect_width(&plane_state->base.src) >> 16;
2995         int h = drm_rect_height(&plane_state->base.src) >> 16;
2996         int dst_x = plane_state->base.dst.x1;
2997         int dst_w = drm_rect_width(&plane_state->base.dst);
2998         int pipe_src_w = crtc_state->pipe_src_w;
2999         int max_width = skl_max_plane_width(fb, 0, rotation);
3000         int max_height = 4096;
3001         u32 alignment, offset, aux_offset = plane_state->aux.offset;
3002
3003         if (w > max_width || h > max_height) {
3004                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3005                               w, h, max_width, max_height);
3006                 return -EINVAL;
3007         }
3008
3009         /*
3010          * Display WA #1175: cnl,glk
3011          * Planes other than the cursor may cause FIFO underflow and display
3012          * corruption if starting less than 4 pixels from the right edge of
3013          * the screen.
3014          * Besides the above WA fix the similar problem, where planes other
3015          * than the cursor ending less than 4 pixels from the left edge of the
3016          * screen may cause FIFO underflow and display corruption.
3017          */
3018         if ((IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
3019             (dst_x + dst_w < 4 || dst_x > pipe_src_w - 4)) {
3020                 DRM_DEBUG_KMS("requested plane X %s position %d invalid (valid range %d-%d)\n",
3021                               dst_x + dst_w < 4 ? "end" : "start",
3022                               dst_x + dst_w < 4 ? dst_x + dst_w : dst_x,
3023                               4, pipe_src_w - 4);
3024                 return -ERANGE;
3025         }
3026
3027         intel_add_fb_offsets(&x, &y, plane_state, 0);
3028         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
3029         alignment = intel_surf_alignment(fb, 0);
3030
3031         /*
3032          * AUX surface offset is specified as the distance from the
3033          * main surface offset, and it must be non-negative. Make
3034          * sure that is what we will get.
3035          */
3036         if (offset > aux_offset)
3037                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3038                                                   offset, aux_offset & ~(alignment - 1));
3039
3040         /*
3041          * When using an X-tiled surface, the plane blows up
3042          * if the x offset + width exceed the stride.
3043          *
3044          * TODO: linear and Y-tiled seem fine, Yf untested,
3045          */
3046         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3047                 int cpp = fb->format->cpp[0];
3048
3049                 while ((x + w) * cpp > fb->pitches[0]) {
3050                         if (offset == 0) {
3051                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3052                                 return -EINVAL;
3053                         }
3054
3055                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3056                                                           offset, offset - alignment);
3057                 }
3058         }
3059
3060         /*
3061          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3062          * they match with the main surface x/y offsets.
3063          */
3064         if (is_ccs_modifier(fb->modifier)) {
3065                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3066                         if (offset == 0)
3067                                 break;
3068
3069                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3070                                                           offset, offset - alignment);
3071                 }
3072
3073                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
3074                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3075                         return -EINVAL;
3076                 }
3077         }
3078
3079         plane_state->main.offset = offset;
3080         plane_state->main.x = x;
3081         plane_state->main.y = y;
3082
3083         return 0;
3084 }
3085
3086 static int
3087 skl_check_nv12_surface(const struct intel_crtc_state *crtc_state,
3088                        struct intel_plane_state *plane_state)
3089 {
3090         /* Display WA #1106 */
3091         if (plane_state->base.rotation !=
3092             (DRM_MODE_REFLECT_X | DRM_MODE_ROTATE_90) &&
3093             plane_state->base.rotation != DRM_MODE_ROTATE_270)
3094                 return 0;
3095
3096         /*
3097          * src coordinates are rotated here.
3098          * We check height but report it as width
3099          */
3100         if (((drm_rect_height(&plane_state->base.src) >> 16) % 4) != 0) {
3101                 DRM_DEBUG_KMS("src width must be multiple "
3102                               "of 4 for rotated NV12\n");
3103                 return -EINVAL;
3104         }
3105
3106         return 0;
3107 }
3108
3109 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3110 {
3111         const struct drm_framebuffer *fb = plane_state->base.fb;
3112         unsigned int rotation = plane_state->base.rotation;
3113         int max_width = skl_max_plane_width(fb, 1, rotation);
3114         int max_height = 4096;
3115         int x = plane_state->base.src.x1 >> 17;
3116         int y = plane_state->base.src.y1 >> 17;
3117         int w = drm_rect_width(&plane_state->base.src) >> 17;
3118         int h = drm_rect_height(&plane_state->base.src) >> 17;
3119         u32 offset;
3120
3121         intel_add_fb_offsets(&x, &y, plane_state, 1);
3122         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3123
3124         /* FIXME not quite sure how/if these apply to the chroma plane */
3125         if (w > max_width || h > max_height) {
3126                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3127                               w, h, max_width, max_height);
3128                 return -EINVAL;
3129         }
3130
3131         plane_state->aux.offset = offset;
3132         plane_state->aux.x = x;
3133         plane_state->aux.y = y;
3134
3135         return 0;
3136 }
3137
3138 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3139 {
3140         const struct drm_framebuffer *fb = plane_state->base.fb;
3141         int src_x = plane_state->base.src.x1 >> 16;
3142         int src_y = plane_state->base.src.y1 >> 16;
3143         int hsub = fb->format->hsub;
3144         int vsub = fb->format->vsub;
3145         int x = src_x / hsub;
3146         int y = src_y / vsub;
3147         u32 offset;
3148
3149         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3150                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3151                               plane_state->base.rotation);
3152                 return -EINVAL;
3153         }
3154
3155         intel_add_fb_offsets(&x, &y, plane_state, 1);
3156         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3157
3158         plane_state->aux.offset = offset;
3159         plane_state->aux.x = x * hsub + src_x % hsub;
3160         plane_state->aux.y = y * vsub + src_y % vsub;
3161
3162         return 0;
3163 }
3164
3165 int skl_check_plane_surface(const struct intel_crtc_state *crtc_state,
3166                             struct intel_plane_state *plane_state)
3167 {
3168         const struct drm_framebuffer *fb = plane_state->base.fb;
3169         unsigned int rotation = plane_state->base.rotation;
3170         int ret;
3171
3172         if (rotation & DRM_MODE_REFLECT_X &&
3173             fb->modifier == DRM_FORMAT_MOD_LINEAR) {
3174                 DRM_DEBUG_KMS("horizontal flip is not supported with linear surface formats\n");
3175                 return -EINVAL;
3176         }
3177
3178         if (!plane_state->base.visible)
3179                 return 0;
3180
3181         /* Rotate src coordinates to match rotated GTT view */
3182         if (drm_rotation_90_or_270(rotation))
3183                 drm_rect_rotate(&plane_state->base.src,
3184                                 fb->width << 16, fb->height << 16,
3185                                 DRM_MODE_ROTATE_270);
3186
3187         /*
3188          * Handle the AUX surface first since
3189          * the main surface setup depends on it.
3190          */
3191         if (fb->format->format == DRM_FORMAT_NV12) {
3192                 ret = skl_check_nv12_surface(crtc_state, plane_state);
3193                 if (ret)
3194                         return ret;
3195                 ret = skl_check_nv12_aux_surface(plane_state);
3196                 if (ret)
3197                         return ret;
3198         } else if (is_ccs_modifier(fb->modifier)) {
3199                 ret = skl_check_ccs_aux_surface(plane_state);
3200                 if (ret)
3201                         return ret;
3202         } else {
3203                 plane_state->aux.offset = ~0xfff;
3204                 plane_state->aux.x = 0;
3205                 plane_state->aux.y = 0;
3206         }
3207
3208         ret = skl_check_main_surface(crtc_state, plane_state);
3209         if (ret)
3210                 return ret;
3211
3212         return 0;
3213 }
3214
3215 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3216                           const struct intel_plane_state *plane_state)
3217 {
3218         struct drm_i915_private *dev_priv =
3219                 to_i915(plane_state->base.plane->dev);
3220         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3221         const struct drm_framebuffer *fb = plane_state->base.fb;
3222         unsigned int rotation = plane_state->base.rotation;
3223         u32 dspcntr;
3224
3225         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3226
3227         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3228             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3229                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3230
3231         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3232                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3233
3234         if (INTEL_GEN(dev_priv) < 5)
3235                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3236
3237         switch (fb->format->format) {
3238         case DRM_FORMAT_C8:
3239                 dspcntr |= DISPPLANE_8BPP;
3240                 break;
3241         case DRM_FORMAT_XRGB1555:
3242                 dspcntr |= DISPPLANE_BGRX555;
3243                 break;
3244         case DRM_FORMAT_RGB565:
3245                 dspcntr |= DISPPLANE_BGRX565;
3246                 break;
3247         case DRM_FORMAT_XRGB8888:
3248                 dspcntr |= DISPPLANE_BGRX888;
3249                 break;
3250         case DRM_FORMAT_XBGR8888:
3251                 dspcntr |= DISPPLANE_RGBX888;
3252                 break;
3253         case DRM_FORMAT_XRGB2101010:
3254                 dspcntr |= DISPPLANE_BGRX101010;
3255                 break;
3256         case DRM_FORMAT_XBGR2101010:
3257                 dspcntr |= DISPPLANE_RGBX101010;
3258                 break;
3259         default:
3260                 MISSING_CASE(fb->format->format);
3261                 return 0;
3262         }
3263
3264         if (INTEL_GEN(dev_priv) >= 4 &&
3265             fb->modifier == I915_FORMAT_MOD_X_TILED)
3266                 dspcntr |= DISPPLANE_TILED;
3267
3268         if (rotation & DRM_MODE_ROTATE_180)
3269                 dspcntr |= DISPPLANE_ROTATE_180;
3270
3271         if (rotation & DRM_MODE_REFLECT_X)
3272                 dspcntr |= DISPPLANE_MIRROR;
3273
3274         return dspcntr;
3275 }
3276
3277 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3278 {
3279         struct drm_i915_private *dev_priv =
3280                 to_i915(plane_state->base.plane->dev);
3281         int src_x = plane_state->base.src.x1 >> 16;
3282         int src_y = plane_state->base.src.y1 >> 16;
3283         u32 offset;
3284
3285         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3286
3287         if (INTEL_GEN(dev_priv) >= 4)
3288                 offset = intel_compute_tile_offset(&src_x, &src_y,
3289                                                    plane_state, 0);
3290         else
3291                 offset = 0;
3292
3293         /* HSW/BDW do this automagically in hardware */
3294         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3295                 unsigned int rotation = plane_state->base.rotation;
3296                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3297                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3298
3299                 if (rotation & DRM_MODE_ROTATE_180) {
3300                         src_x += src_w - 1;
3301                         src_y += src_h - 1;
3302                 } else if (rotation & DRM_MODE_REFLECT_X) {
3303                         src_x += src_w - 1;
3304                 }
3305         }
3306
3307         plane_state->main.offset = offset;
3308         plane_state->main.x = src_x;
3309         plane_state->main.y = src_y;
3310
3311         return 0;
3312 }
3313
3314 static void i9xx_update_plane(struct intel_plane *plane,
3315                               const struct intel_crtc_state *crtc_state,
3316                               const struct intel_plane_state *plane_state)
3317 {
3318         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3319         const struct drm_framebuffer *fb = plane_state->base.fb;
3320         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3321         u32 linear_offset;
3322         u32 dspcntr = plane_state->ctl;
3323         i915_reg_t reg = DSPCNTR(i9xx_plane);
3324         int x = plane_state->main.x;
3325         int y = plane_state->main.y;
3326         unsigned long irqflags;
3327         u32 dspaddr_offset;
3328
3329         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3330
3331         if (INTEL_GEN(dev_priv) >= 4)
3332                 dspaddr_offset = plane_state->main.offset;
3333         else
3334                 dspaddr_offset = linear_offset;
3335
3336         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3337
3338         if (INTEL_GEN(dev_priv) < 4) {
3339                 /* pipesrc and dspsize control the size that is scaled from,
3340                  * which should always be the user's requested size.
3341                  */
3342                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3343                               ((crtc_state->pipe_src_h - 1) << 16) |
3344                               (crtc_state->pipe_src_w - 1));
3345                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3346         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3347                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3348                               ((crtc_state->pipe_src_h - 1) << 16) |
3349                               (crtc_state->pipe_src_w - 1));
3350                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3351                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3352         }
3353
3354         I915_WRITE_FW(reg, dspcntr);
3355
3356         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), fb->pitches[0]);
3357         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3358                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3359                               intel_plane_ggtt_offset(plane_state) +
3360                               dspaddr_offset);
3361                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3362         } else if (INTEL_GEN(dev_priv) >= 4) {
3363                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3364                               intel_plane_ggtt_offset(plane_state) +
3365                               dspaddr_offset);
3366                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3367                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3368         } else {
3369                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3370                               intel_plane_ggtt_offset(plane_state) +
3371                               dspaddr_offset);
3372         }
3373         POSTING_READ_FW(reg);
3374
3375         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3376 }
3377
3378 static void i9xx_disable_plane(struct intel_plane *plane,
3379                                struct intel_crtc *crtc)
3380 {
3381         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3382         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3383         unsigned long irqflags;
3384
3385         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3386
3387         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3388         if (INTEL_GEN(dev_priv) >= 4)
3389                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3390         else
3391                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3392         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3393
3394         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3395 }
3396
3397 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3398                                     enum pipe *pipe)
3399 {
3400         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3401         enum intel_display_power_domain power_domain;
3402         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3403         bool ret;
3404         u32 val;
3405
3406         /*
3407          * Not 100% correct for planes that can move between pipes,
3408          * but that's only the case for gen2-4 which don't have any
3409          * display power wells.
3410          */
3411         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3412         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3413                 return false;
3414
3415         val = I915_READ(DSPCNTR(i9xx_plane));
3416
3417         ret = val & DISPLAY_PLANE_ENABLE;
3418
3419         if (INTEL_GEN(dev_priv) >= 5)
3420                 *pipe = plane->pipe;
3421         else
3422                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3423                         DISPPLANE_SEL_PIPE_SHIFT;
3424
3425         intel_display_power_put(dev_priv, power_domain);
3426
3427         return ret;
3428 }
3429
3430 static u32
3431 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3432 {
3433         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3434                 return 64;
3435         else
3436                 return intel_tile_width_bytes(fb, plane);
3437 }
3438
3439 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3440 {
3441         struct drm_device *dev = intel_crtc->base.dev;
3442         struct drm_i915_private *dev_priv = to_i915(dev);
3443
3444         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3445         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3446         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3447 }
3448
3449 /*
3450  * This function detaches (aka. unbinds) unused scalers in hardware
3451  */
3452 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3453 {
3454         struct intel_crtc_scaler_state *scaler_state;
3455         int i;
3456
3457         scaler_state = &intel_crtc->config->scaler_state;
3458
3459         /* loop through and disable scalers that aren't in use */
3460         for (i = 0; i < intel_crtc->num_scalers; i++) {
3461                 if (!scaler_state->scalers[i].in_use)
3462                         skl_detach_scaler(intel_crtc, i);
3463         }
3464 }
3465
3466 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3467                      unsigned int rotation)
3468 {
3469         u32 stride;
3470
3471         if (plane >= fb->format->num_planes)
3472                 return 0;
3473
3474         stride = intel_fb_pitch(fb, plane, rotation);
3475
3476         /*
3477          * The stride is either expressed as a multiple of 64 bytes chunks for
3478          * linear buffers or in number of tiles for tiled buffers.
3479          */
3480         if (drm_rotation_90_or_270(rotation))
3481                 stride /= intel_tile_height(fb, plane);
3482         else
3483                 stride /= intel_fb_stride_alignment(fb, plane);
3484
3485         return stride;
3486 }
3487
3488 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3489 {
3490         switch (pixel_format) {
3491         case DRM_FORMAT_C8:
3492                 return PLANE_CTL_FORMAT_INDEXED;
3493         case DRM_FORMAT_RGB565:
3494                 return PLANE_CTL_FORMAT_RGB_565;
3495         case DRM_FORMAT_XBGR8888:
3496         case DRM_FORMAT_ABGR8888:
3497                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3498         case DRM_FORMAT_XRGB8888:
3499         case DRM_FORMAT_ARGB8888:
3500                 return PLANE_CTL_FORMAT_XRGB_8888;
3501         case DRM_FORMAT_XRGB2101010:
3502                 return PLANE_CTL_FORMAT_XRGB_2101010;
3503         case DRM_FORMAT_XBGR2101010:
3504                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3505         case DRM_FORMAT_YUYV:
3506                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3507         case DRM_FORMAT_YVYU:
3508                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3509         case DRM_FORMAT_UYVY:
3510                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3511         case DRM_FORMAT_VYUY:
3512                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3513         case DRM_FORMAT_NV12:
3514                 return PLANE_CTL_FORMAT_NV12;
3515         default:
3516                 MISSING_CASE(pixel_format);
3517         }
3518
3519         return 0;
3520 }
3521
3522 /*
3523  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3524  * to be already pre-multiplied. We need to add a knob (or a different
3525  * DRM_FORMAT) for user-space to configure that.
3526  */
3527 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3528 {
3529         switch (pixel_format) {
3530         case DRM_FORMAT_ABGR8888:
3531         case DRM_FORMAT_ARGB8888:
3532                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3533         default:
3534                 return PLANE_CTL_ALPHA_DISABLE;
3535         }
3536 }
3537
3538 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3539 {
3540         switch (pixel_format) {
3541         case DRM_FORMAT_ABGR8888:
3542         case DRM_FORMAT_ARGB8888:
3543                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3544         default:
3545                 return PLANE_COLOR_ALPHA_DISABLE;
3546         }
3547 }
3548
3549 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3550 {
3551         switch (fb_modifier) {
3552         case DRM_FORMAT_MOD_LINEAR:
3553                 break;
3554         case I915_FORMAT_MOD_X_TILED:
3555                 return PLANE_CTL_TILED_X;
3556         case I915_FORMAT_MOD_Y_TILED:
3557                 return PLANE_CTL_TILED_Y;
3558         case I915_FORMAT_MOD_Y_TILED_CCS:
3559                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3560         case I915_FORMAT_MOD_Yf_TILED:
3561                 return PLANE_CTL_TILED_YF;
3562         case I915_FORMAT_MOD_Yf_TILED_CCS:
3563                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3564         default:
3565                 MISSING_CASE(fb_modifier);
3566         }
3567
3568         return 0;
3569 }
3570
3571 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3572 {
3573         switch (rotate) {
3574         case DRM_MODE_ROTATE_0:
3575                 break;
3576         /*
3577          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3578          * while i915 HW rotation is clockwise, thats why this swapping.
3579          */
3580         case DRM_MODE_ROTATE_90:
3581                 return PLANE_CTL_ROTATE_270;
3582         case DRM_MODE_ROTATE_180:
3583                 return PLANE_CTL_ROTATE_180;
3584         case DRM_MODE_ROTATE_270:
3585                 return PLANE_CTL_ROTATE_90;
3586         default:
3587                 MISSING_CASE(rotate);
3588         }
3589
3590         return 0;
3591 }
3592
3593 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3594 {
3595         switch (reflect) {
3596         case 0:
3597                 break;
3598         case DRM_MODE_REFLECT_X:
3599                 return PLANE_CTL_FLIP_HORIZONTAL;
3600         case DRM_MODE_REFLECT_Y:
3601         default:
3602                 MISSING_CASE(reflect);
3603         }
3604
3605         return 0;
3606 }
3607
3608 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3609                   const struct intel_plane_state *plane_state)
3610 {
3611         struct drm_i915_private *dev_priv =
3612                 to_i915(plane_state->base.plane->dev);
3613         const struct drm_framebuffer *fb = plane_state->base.fb;
3614         unsigned int rotation = plane_state->base.rotation;
3615         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3616         u32 plane_ctl;
3617
3618         plane_ctl = PLANE_CTL_ENABLE;
3619
3620         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3621                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3622                 plane_ctl |=
3623                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3624                         PLANE_CTL_PIPE_CSC_ENABLE |
3625                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3626
3627                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3628                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3629
3630                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3631                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3632         }
3633
3634         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3635         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3636         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3637
3638         if (INTEL_GEN(dev_priv) >= 10)
3639                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3640                                                 DRM_MODE_REFLECT_MASK);
3641
3642         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3643                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3644         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3645                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3646
3647         return plane_ctl;
3648 }
3649
3650 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3651                         const struct intel_plane_state *plane_state)
3652 {
3653         struct drm_i915_private *dev_priv =
3654                 to_i915(plane_state->base.plane->dev);
3655         const struct drm_framebuffer *fb = plane_state->base.fb;
3656         u32 plane_color_ctl = 0;
3657
3658         if (INTEL_GEN(dev_priv) < 11) {
3659                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3660                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3661         }
3662         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3663         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3664
3665         if (fb->format->is_yuv) {
3666                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3667                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3668                 else
3669                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3670
3671                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3672                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3673         }
3674
3675         return plane_color_ctl;
3676 }
3677
3678 static int
3679 __intel_display_resume(struct drm_device *dev,
3680                        struct drm_atomic_state *state,
3681                        struct drm_modeset_acquire_ctx *ctx)
3682 {
3683         struct drm_crtc_state *crtc_state;
3684         struct drm_crtc *crtc;
3685         int i, ret;
3686
3687         intel_modeset_setup_hw_state(dev, ctx);
3688         i915_redisable_vga(to_i915(dev));
3689
3690         if (!state)
3691                 return 0;
3692
3693         /*
3694          * We've duplicated the state, pointers to the old state are invalid.
3695          *
3696          * Don't attempt to use the old state until we commit the duplicated state.
3697          */
3698         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3699                 /*
3700                  * Force recalculation even if we restore
3701                  * current state. With fast modeset this may not result
3702                  * in a modeset when the state is compatible.
3703                  */
3704                 crtc_state->mode_changed = true;
3705         }
3706
3707         /* ignore any reset values/BIOS leftovers in the WM registers */
3708         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3709                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3710
3711         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3712
3713         WARN_ON(ret == -EDEADLK);
3714         return ret;
3715 }
3716
3717 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3718 {
3719         return intel_has_gpu_reset(dev_priv) &&
3720                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3721 }
3722
3723 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3724 {
3725         struct drm_device *dev = &dev_priv->drm;
3726         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3727         struct drm_atomic_state *state;
3728         int ret;
3729
3730         /* reset doesn't touch the display */
3731         if (!i915_modparams.force_reset_modeset_test &&
3732             !gpu_reset_clobbers_display(dev_priv))
3733                 return;
3734
3735         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3736         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3737         wake_up_all(&dev_priv->gpu_error.wait_queue);
3738
3739         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3740                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3741                 i915_gem_set_wedged(dev_priv);
3742         }
3743
3744         /*
3745          * Need mode_config.mutex so that we don't
3746          * trample ongoing ->detect() and whatnot.
3747          */
3748         mutex_lock(&dev->mode_config.mutex);
3749         drm_modeset_acquire_init(ctx, 0);
3750         while (1) {
3751                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3752                 if (ret != -EDEADLK)
3753                         break;
3754
3755                 drm_modeset_backoff(ctx);
3756         }
3757         /*
3758          * Disabling the crtcs gracefully seems nicer. Also the
3759          * g33 docs say we should at least disable all the planes.
3760          */
3761         state = drm_atomic_helper_duplicate_state(dev, ctx);
3762         if (IS_ERR(state)) {
3763                 ret = PTR_ERR(state);
3764                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3765                 return;
3766         }
3767
3768         ret = drm_atomic_helper_disable_all(dev, ctx);
3769         if (ret) {
3770                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3771                 drm_atomic_state_put(state);
3772                 return;
3773         }
3774
3775         dev_priv->modeset_restore_state = state;
3776         state->acquire_ctx = ctx;
3777 }
3778
3779 void intel_finish_reset(struct drm_i915_private *dev_priv)
3780 {
3781         struct drm_device *dev = &dev_priv->drm;
3782         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3783         struct drm_atomic_state *state;
3784         int ret;
3785
3786         /* reset doesn't touch the display */
3787         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3788                 return;
3789
3790         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3791         if (!state)
3792                 goto unlock;
3793
3794         /* reset doesn't touch the display */
3795         if (!gpu_reset_clobbers_display(dev_priv)) {
3796                 /* for testing only restore the display */
3797                 ret = __intel_display_resume(dev, state, ctx);
3798                 if (ret)
3799                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3800         } else {
3801                 /*
3802                  * The display has been reset as well,
3803                  * so need a full re-initialization.
3804                  */
3805                 intel_runtime_pm_disable_interrupts(dev_priv);
3806                 intel_runtime_pm_enable_interrupts(dev_priv);
3807
3808                 intel_pps_unlock_regs_wa(dev_priv);
3809                 intel_modeset_init_hw(dev);
3810                 intel_init_clock_gating(dev_priv);
3811
3812                 spin_lock_irq(&dev_priv->irq_lock);
3813                 if (dev_priv->display.hpd_irq_setup)
3814                         dev_priv->display.hpd_irq_setup(dev_priv);
3815                 spin_unlock_irq(&dev_priv->irq_lock);
3816
3817                 ret = __intel_display_resume(dev, state, ctx);
3818                 if (ret)
3819                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3820
3821                 intel_hpd_init(dev_priv);
3822         }
3823
3824         drm_atomic_state_put(state);
3825 unlock:
3826         drm_modeset_drop_locks(ctx);
3827         drm_modeset_acquire_fini(ctx);
3828         mutex_unlock(&dev->mode_config.mutex);
3829
3830         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3831 }
3832
3833 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3834                                      const struct intel_crtc_state *new_crtc_state)
3835 {
3836         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3837         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3838
3839         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3840         crtc->base.mode = new_crtc_state->base.mode;
3841
3842         /*
3843          * Update pipe size and adjust fitter if needed: the reason for this is
3844          * that in compute_mode_changes we check the native mode (not the pfit
3845          * mode) to see if we can flip rather than do a full mode set. In the
3846          * fastboot case, we'll flip, but if we don't update the pipesrc and
3847          * pfit state, we'll end up with a big fb scanned out into the wrong
3848          * sized surface.
3849          */
3850
3851         I915_WRITE(PIPESRC(crtc->pipe),
3852                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3853                    (new_crtc_state->pipe_src_h - 1));
3854
3855         /* on skylake this is done by detaching scalers */
3856         if (INTEL_GEN(dev_priv) >= 9) {
3857                 skl_detach_scalers(crtc);
3858
3859                 if (new_crtc_state->pch_pfit.enabled)
3860                         skylake_pfit_enable(crtc);
3861         } else if (HAS_PCH_SPLIT(dev_priv)) {
3862                 if (new_crtc_state->pch_pfit.enabled)
3863                         ironlake_pfit_enable(crtc);
3864                 else if (old_crtc_state->pch_pfit.enabled)
3865                         ironlake_pfit_disable(crtc, true);
3866         }
3867 }
3868
3869 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3870 {
3871         struct drm_device *dev = crtc->base.dev;
3872         struct drm_i915_private *dev_priv = to_i915(dev);
3873         int pipe = crtc->pipe;
3874         i915_reg_t reg;
3875         u32 temp;
3876
3877         /* enable normal train */
3878         reg = FDI_TX_CTL(pipe);
3879         temp = I915_READ(reg);
3880         if (IS_IVYBRIDGE(dev_priv)) {
3881                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3882                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3883         } else {
3884                 temp &= ~FDI_LINK_TRAIN_NONE;
3885                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3886         }
3887         I915_WRITE(reg, temp);
3888
3889         reg = FDI_RX_CTL(pipe);
3890         temp = I915_READ(reg);
3891         if (HAS_PCH_CPT(dev_priv)) {
3892                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3893                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3894         } else {
3895                 temp &= ~FDI_LINK_TRAIN_NONE;
3896                 temp |= FDI_LINK_TRAIN_NONE;
3897         }
3898         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3899
3900         /* wait one idle pattern time */
3901         POSTING_READ(reg);
3902         udelay(1000);
3903
3904         /* IVB wants error correction enabled */
3905         if (IS_IVYBRIDGE(dev_priv))
3906                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3907                            FDI_FE_ERRC_ENABLE);
3908 }
3909
3910 /* The FDI link training functions for ILK/Ibexpeak. */
3911 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3912                                     const struct intel_crtc_state *crtc_state)
3913 {
3914         struct drm_device *dev = crtc->base.dev;
3915         struct drm_i915_private *dev_priv = to_i915(dev);
3916         int pipe = crtc->pipe;
3917         i915_reg_t reg;
3918         u32 temp, tries;
3919
3920         /* FDI needs bits from pipe first */
3921         assert_pipe_enabled(dev_priv, pipe);
3922
3923         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3924            for train result */
3925         reg = FDI_RX_IMR(pipe);
3926         temp = I915_READ(reg);
3927         temp &= ~FDI_RX_SYMBOL_LOCK;
3928         temp &= ~FDI_RX_BIT_LOCK;
3929         I915_WRITE(reg, temp);
3930         I915_READ(reg);
3931         udelay(150);
3932
3933         /* enable CPU FDI TX and PCH FDI RX */
3934         reg = FDI_TX_CTL(pipe);
3935         temp = I915_READ(reg);
3936         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3937         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3938         temp &= ~FDI_LINK_TRAIN_NONE;
3939         temp |= FDI_LINK_TRAIN_PATTERN_1;
3940         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3941
3942         reg = FDI_RX_CTL(pipe);
3943         temp = I915_READ(reg);
3944         temp &= ~FDI_LINK_TRAIN_NONE;
3945         temp |= FDI_LINK_TRAIN_PATTERN_1;
3946         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3947
3948         POSTING_READ(reg);
3949         udelay(150);
3950
3951         /* Ironlake workaround, enable clock pointer after FDI enable*/
3952         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3953         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3954                    FDI_RX_PHASE_SYNC_POINTER_EN);
3955
3956         reg = FDI_RX_IIR(pipe);
3957         for (tries = 0; tries < 5; tries++) {
3958                 temp = I915_READ(reg);
3959                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3960
3961                 if ((temp & FDI_RX_BIT_LOCK)) {
3962                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3963                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3964                         break;
3965                 }
3966         }
3967         if (tries == 5)
3968                 DRM_ERROR("FDI train 1 fail!\n");
3969
3970         /* Train 2 */
3971         reg = FDI_TX_CTL(pipe);
3972         temp = I915_READ(reg);
3973         temp &= ~FDI_LINK_TRAIN_NONE;
3974         temp |= FDI_LINK_TRAIN_PATTERN_2;
3975         I915_WRITE(reg, temp);
3976
3977         reg = FDI_RX_CTL(pipe);
3978         temp = I915_READ(reg);
3979         temp &= ~FDI_LINK_TRAIN_NONE;
3980         temp |= FDI_LINK_TRAIN_PATTERN_2;
3981         I915_WRITE(reg, temp);
3982
3983         POSTING_READ(reg);
3984         udelay(150);
3985
3986         reg = FDI_RX_IIR(pipe);
3987         for (tries = 0; tries < 5; tries++) {
3988                 temp = I915_READ(reg);
3989                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3990
3991                 if (temp & FDI_RX_SYMBOL_LOCK) {
3992                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3993                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3994                         break;
3995                 }
3996         }
3997         if (tries == 5)
3998                 DRM_ERROR("FDI train 2 fail!\n");
3999
4000         DRM_DEBUG_KMS("FDI train done\n");
4001
4002 }
4003
4004 static const int snb_b_fdi_train_param[] = {
4005         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4006         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4007         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4008         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4009 };
4010
4011 /* The FDI link training functions for SNB/Cougarpoint. */
4012 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4013                                 const struct intel_crtc_state *crtc_state)
4014 {
4015         struct drm_device *dev = crtc->base.dev;
4016         struct drm_i915_private *dev_priv = to_i915(dev);
4017         int pipe = crtc->pipe;
4018         i915_reg_t reg;
4019         u32 temp, i, retry;
4020
4021         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4022            for train result */
4023         reg = FDI_RX_IMR(pipe);
4024         temp = I915_READ(reg);
4025         temp &= ~FDI_RX_SYMBOL_LOCK;
4026         temp &= ~FDI_RX_BIT_LOCK;
4027         I915_WRITE(reg, temp);
4028
4029         POSTING_READ(reg);
4030         udelay(150);
4031
4032         /* enable CPU FDI TX and PCH FDI RX */
4033         reg = FDI_TX_CTL(pipe);
4034         temp = I915_READ(reg);
4035         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4036         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4037         temp &= ~FDI_LINK_TRAIN_NONE;
4038         temp |= FDI_LINK_TRAIN_PATTERN_1;
4039         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4040         /* SNB-B */
4041         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4042         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4043
4044         I915_WRITE(FDI_RX_MISC(pipe),
4045                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4046
4047         reg = FDI_RX_CTL(pipe);
4048         temp = I915_READ(reg);
4049         if (HAS_PCH_CPT(dev_priv)) {
4050                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4051                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4052         } else {
4053                 temp &= ~FDI_LINK_TRAIN_NONE;
4054                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4055         }
4056         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4057
4058         POSTING_READ(reg);
4059         udelay(150);
4060
4061         for (i = 0; i < 4; i++) {
4062                 reg = FDI_TX_CTL(pipe);
4063                 temp = I915_READ(reg);
4064                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4065                 temp |= snb_b_fdi_train_param[i];
4066                 I915_WRITE(reg, temp);
4067
4068                 POSTING_READ(reg);
4069                 udelay(500);
4070
4071                 for (retry = 0; retry < 5; retry++) {
4072                         reg = FDI_RX_IIR(pipe);
4073                         temp = I915_READ(reg);
4074                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4075                         if (temp & FDI_RX_BIT_LOCK) {
4076                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4077                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4078                                 break;
4079                         }
4080                         udelay(50);
4081                 }
4082                 if (retry < 5)
4083                         break;
4084         }
4085         if (i == 4)
4086                 DRM_ERROR("FDI train 1 fail!\n");
4087
4088         /* Train 2 */
4089         reg = FDI_TX_CTL(pipe);
4090         temp = I915_READ(reg);
4091         temp &= ~FDI_LINK_TRAIN_NONE;
4092         temp |= FDI_LINK_TRAIN_PATTERN_2;
4093         if (IS_GEN6(dev_priv)) {
4094                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4095                 /* SNB-B */
4096                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4097         }
4098         I915_WRITE(reg, temp);
4099
4100         reg = FDI_RX_CTL(pipe);
4101         temp = I915_READ(reg);
4102         if (HAS_PCH_CPT(dev_priv)) {
4103                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4104                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4105         } else {
4106                 temp &= ~FDI_LINK_TRAIN_NONE;
4107                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4108         }
4109         I915_WRITE(reg, temp);
4110
4111         POSTING_READ(reg);
4112         udelay(150);
4113
4114         for (i = 0; i < 4; i++) {
4115                 reg = FDI_TX_CTL(pipe);
4116                 temp = I915_READ(reg);
4117                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4118                 temp |= snb_b_fdi_train_param[i];
4119                 I915_WRITE(reg, temp);
4120
4121                 POSTING_READ(reg);
4122                 udelay(500);
4123
4124                 for (retry = 0; retry < 5; retry++) {
4125                         reg = FDI_RX_IIR(pipe);
4126                         temp = I915_READ(reg);
4127                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4128                         if (temp & FDI_RX_SYMBOL_LOCK) {
4129                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4130                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4131                                 break;
4132                         }
4133                         udelay(50);
4134                 }
4135                 if (retry < 5)
4136                         break;
4137         }
4138         if (i == 4)
4139                 DRM_ERROR("FDI train 2 fail!\n");
4140
4141         DRM_DEBUG_KMS("FDI train done.\n");
4142 }
4143
4144 /* Manual link training for Ivy Bridge A0 parts */
4145 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4146                                       const struct intel_crtc_state *crtc_state)
4147 {
4148         struct drm_device *dev = crtc->base.dev;
4149         struct drm_i915_private *dev_priv = to_i915(dev);
4150         int pipe = crtc->pipe;
4151         i915_reg_t reg;
4152         u32 temp, i, j;
4153
4154         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4155            for train result */
4156         reg = FDI_RX_IMR(pipe);
4157         temp = I915_READ(reg);
4158         temp &= ~FDI_RX_SYMBOL_LOCK;
4159         temp &= ~FDI_RX_BIT_LOCK;
4160         I915_WRITE(reg, temp);
4161
4162         POSTING_READ(reg);
4163         udelay(150);
4164
4165         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4166                       I915_READ(FDI_RX_IIR(pipe)));
4167
4168         /* Try each vswing and preemphasis setting twice before moving on */
4169         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4170                 /* disable first in case we need to retry */
4171                 reg = FDI_TX_CTL(pipe);
4172                 temp = I915_READ(reg);
4173                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4174                 temp &= ~FDI_TX_ENABLE;
4175                 I915_WRITE(reg, temp);
4176
4177                 reg = FDI_RX_CTL(pipe);
4178                 temp = I915_READ(reg);
4179                 temp &= ~FDI_LINK_TRAIN_AUTO;
4180                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4181                 temp &= ~FDI_RX_ENABLE;
4182                 I915_WRITE(reg, temp);
4183
4184                 /* enable CPU FDI TX and PCH FDI RX */
4185                 reg = FDI_TX_CTL(pipe);
4186                 temp = I915_READ(reg);
4187                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4188                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4189                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4190                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4191                 temp |= snb_b_fdi_train_param[j/2];
4192                 temp |= FDI_COMPOSITE_SYNC;
4193                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4194
4195                 I915_WRITE(FDI_RX_MISC(pipe),
4196                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4197
4198                 reg = FDI_RX_CTL(pipe);
4199                 temp = I915_READ(reg);
4200                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4201                 temp |= FDI_COMPOSITE_SYNC;
4202                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4203
4204                 POSTING_READ(reg);
4205                 udelay(1); /* should be 0.5us */
4206
4207                 for (i = 0; i < 4; i++) {
4208                         reg = FDI_RX_IIR(pipe);
4209                         temp = I915_READ(reg);
4210                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4211
4212                         if (temp & FDI_RX_BIT_LOCK ||
4213                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4214                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4215                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4216                                               i);
4217                                 break;
4218                         }
4219                         udelay(1); /* should be 0.5us */
4220                 }
4221                 if (i == 4) {
4222                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4223                         continue;
4224                 }
4225
4226                 /* Train 2 */
4227                 reg = FDI_TX_CTL(pipe);
4228                 temp = I915_READ(reg);
4229                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4230                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4231                 I915_WRITE(reg, temp);
4232
4233                 reg = FDI_RX_CTL(pipe);
4234                 temp = I915_READ(reg);
4235                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4236                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4237                 I915_WRITE(reg, temp);
4238
4239                 POSTING_READ(reg);
4240                 udelay(2); /* should be 1.5us */
4241
4242                 for (i = 0; i < 4; i++) {
4243                         reg = FDI_RX_IIR(pipe);
4244                         temp = I915_READ(reg);
4245                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4246
4247                         if (temp & FDI_RX_SYMBOL_LOCK ||
4248                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4249                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4250                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4251                                               i);
4252                                 goto train_done;
4253                         }
4254                         udelay(2); /* should be 1.5us */
4255                 }
4256                 if (i == 4)
4257                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4258         }
4259
4260 train_done:
4261         DRM_DEBUG_KMS("FDI train done.\n");
4262 }
4263
4264 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4265 {
4266         struct drm_device *dev = intel_crtc->base.dev;
4267         struct drm_i915_private *dev_priv = to_i915(dev);
4268         int pipe = intel_crtc->pipe;
4269         i915_reg_t reg;
4270         u32 temp;
4271
4272         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4273         reg = FDI_RX_CTL(pipe);
4274         temp = I915_READ(reg);
4275         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4276         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4277         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4278         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4279
4280         POSTING_READ(reg);
4281         udelay(200);
4282
4283         /* Switch from Rawclk to PCDclk */
4284         temp = I915_READ(reg);
4285         I915_WRITE(reg, temp | FDI_PCDCLK);
4286
4287         POSTING_READ(reg);
4288         udelay(200);
4289
4290         /* Enable CPU FDI TX PLL, always on for Ironlake */
4291         reg = FDI_TX_CTL(pipe);
4292         temp = I915_READ(reg);
4293         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4294                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4295
4296                 POSTING_READ(reg);
4297                 udelay(100);
4298         }
4299 }
4300
4301 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4302 {
4303         struct drm_device *dev = intel_crtc->base.dev;
4304         struct drm_i915_private *dev_priv = to_i915(dev);
4305         int pipe = intel_crtc->pipe;
4306         i915_reg_t reg;
4307         u32 temp;
4308
4309         /* Switch from PCDclk to Rawclk */
4310         reg = FDI_RX_CTL(pipe);
4311         temp = I915_READ(reg);
4312         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4313
4314         /* Disable CPU FDI TX PLL */
4315         reg = FDI_TX_CTL(pipe);
4316         temp = I915_READ(reg);
4317         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4318
4319         POSTING_READ(reg);
4320         udelay(100);
4321
4322         reg = FDI_RX_CTL(pipe);
4323         temp = I915_READ(reg);
4324         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4325
4326         /* Wait for the clocks to turn off. */
4327         POSTING_READ(reg);
4328         udelay(100);
4329 }
4330
4331 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4332 {
4333         struct drm_device *dev = crtc->dev;
4334         struct drm_i915_private *dev_priv = to_i915(dev);
4335         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4336         int pipe = intel_crtc->pipe;
4337         i915_reg_t reg;
4338         u32 temp;
4339
4340         /* disable CPU FDI tx and PCH FDI rx */
4341         reg = FDI_TX_CTL(pipe);
4342         temp = I915_READ(reg);
4343         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4344         POSTING_READ(reg);
4345
4346         reg = FDI_RX_CTL(pipe);
4347         temp = I915_READ(reg);
4348         temp &= ~(0x7 << 16);
4349         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4350         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4351
4352         POSTING_READ(reg);
4353         udelay(100);
4354
4355         /* Ironlake workaround, disable clock pointer after downing FDI */
4356         if (HAS_PCH_IBX(dev_priv))
4357                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4358
4359         /* still set train pattern 1 */
4360         reg = FDI_TX_CTL(pipe);
4361         temp = I915_READ(reg);
4362         temp &= ~FDI_LINK_TRAIN_NONE;
4363         temp |= FDI_LINK_TRAIN_PATTERN_1;
4364         I915_WRITE(reg, temp);
4365
4366         reg = FDI_RX_CTL(pipe);
4367         temp = I915_READ(reg);
4368         if (HAS_PCH_CPT(dev_priv)) {
4369                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4370                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4371         } else {
4372                 temp &= ~FDI_LINK_TRAIN_NONE;
4373                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4374         }
4375         /* BPC in FDI rx is consistent with that in PIPECONF */
4376         temp &= ~(0x07 << 16);
4377         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4378         I915_WRITE(reg, temp);
4379
4380         POSTING_READ(reg);
4381         udelay(100);
4382 }
4383
4384 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4385 {
4386         struct drm_crtc *crtc;
4387         bool cleanup_done;
4388
4389         drm_for_each_crtc(crtc, &dev_priv->drm) {
4390                 struct drm_crtc_commit *commit;
4391                 spin_lock(&crtc->commit_lock);
4392                 commit = list_first_entry_or_null(&crtc->commit_list,
4393                                                   struct drm_crtc_commit, commit_entry);
4394                 cleanup_done = commit ?
4395                         try_wait_for_completion(&commit->cleanup_done) : true;
4396                 spin_unlock(&crtc->commit_lock);
4397
4398                 if (cleanup_done)
4399                         continue;
4400
4401                 drm_crtc_wait_one_vblank(crtc);
4402
4403                 return true;
4404         }
4405
4406         return false;
4407 }
4408
4409 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4410 {
4411         u32 temp;
4412
4413         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4414
4415         mutex_lock(&dev_priv->sb_lock);
4416
4417         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4418         temp |= SBI_SSCCTL_DISABLE;
4419         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4420
4421         mutex_unlock(&dev_priv->sb_lock);
4422 }
4423
4424 /* Program iCLKIP clock to the desired frequency */
4425 static void lpt_program_iclkip(struct intel_crtc *crtc)
4426 {
4427         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4428         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4429         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4430         u32 temp;
4431
4432         lpt_disable_iclkip(dev_priv);
4433
4434         /* The iCLK virtual clock root frequency is in MHz,
4435          * but the adjusted_mode->crtc_clock in in KHz. To get the
4436          * divisors, it is necessary to divide one by another, so we
4437          * convert the virtual clock precision to KHz here for higher
4438          * precision.
4439          */
4440         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4441                 u32 iclk_virtual_root_freq = 172800 * 1000;
4442                 u32 iclk_pi_range = 64;
4443                 u32 desired_divisor;
4444
4445                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4446                                                     clock << auxdiv);
4447                 divsel = (desired_divisor / iclk_pi_range) - 2;
4448                 phaseinc = desired_divisor % iclk_pi_range;
4449
4450                 /*
4451                  * Near 20MHz is a corner case which is
4452                  * out of range for the 7-bit divisor
4453                  */
4454                 if (divsel <= 0x7f)
4455                         break;
4456         }
4457
4458         /* This should not happen with any sane values */
4459         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4460                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4461         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4462                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4463
4464         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4465                         clock,
4466                         auxdiv,
4467                         divsel,
4468                         phasedir,
4469                         phaseinc);
4470
4471         mutex_lock(&dev_priv->sb_lock);
4472
4473         /* Program SSCDIVINTPHASE6 */
4474         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4475         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4476         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4477         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4478         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4479         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4480         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4481         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4482
4483         /* Program SSCAUXDIV */
4484         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4485         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4486         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4487         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4488
4489         /* Enable modulator and associated divider */
4490         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4491         temp &= ~SBI_SSCCTL_DISABLE;
4492         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4493
4494         mutex_unlock(&dev_priv->sb_lock);
4495
4496         /* Wait for initialization time */
4497         udelay(24);
4498
4499         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4500 }
4501
4502 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4503 {
4504         u32 divsel, phaseinc, auxdiv;
4505         u32 iclk_virtual_root_freq = 172800 * 1000;
4506         u32 iclk_pi_range = 64;
4507         u32 desired_divisor;
4508         u32 temp;
4509
4510         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4511                 return 0;
4512
4513         mutex_lock(&dev_priv->sb_lock);
4514
4515         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4516         if (temp & SBI_SSCCTL_DISABLE) {
4517                 mutex_unlock(&dev_priv->sb_lock);
4518                 return 0;
4519         }
4520
4521         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4522         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4523                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4524         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4525                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4526
4527         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4528         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4529                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4530
4531         mutex_unlock(&dev_priv->sb_lock);
4532
4533         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4534
4535         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4536                                  desired_divisor << auxdiv);
4537 }
4538
4539 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4540                                                 enum pipe pch_transcoder)
4541 {
4542         struct drm_device *dev = crtc->base.dev;
4543         struct drm_i915_private *dev_priv = to_i915(dev);
4544         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4545
4546         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4547                    I915_READ(HTOTAL(cpu_transcoder)));
4548         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4549                    I915_READ(HBLANK(cpu_transcoder)));
4550         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4551                    I915_READ(HSYNC(cpu_transcoder)));
4552
4553         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4554                    I915_READ(VTOTAL(cpu_transcoder)));
4555         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4556                    I915_READ(VBLANK(cpu_transcoder)));
4557         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4558                    I915_READ(VSYNC(cpu_transcoder)));
4559         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4560                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4561 }
4562
4563 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4564 {
4565         struct drm_i915_private *dev_priv = to_i915(dev);
4566         uint32_t temp;
4567
4568         temp = I915_READ(SOUTH_CHICKEN1);
4569         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4570                 return;
4571
4572         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4573         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4574
4575         temp &= ~FDI_BC_BIFURCATION_SELECT;
4576         if (enable)
4577                 temp |= FDI_BC_BIFURCATION_SELECT;
4578
4579         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4580         I915_WRITE(SOUTH_CHICKEN1, temp);
4581         POSTING_READ(SOUTH_CHICKEN1);
4582 }
4583
4584 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4585 {
4586         struct drm_device *dev = intel_crtc->base.dev;
4587
4588         switch (intel_crtc->pipe) {
4589         case PIPE_A:
4590                 break;
4591         case PIPE_B:
4592                 if (intel_crtc->config->fdi_lanes > 2)
4593                         cpt_set_fdi_bc_bifurcation(dev, false);
4594                 else
4595                         cpt_set_fdi_bc_bifurcation(dev, true);
4596
4597                 break;
4598         case PIPE_C:
4599                 cpt_set_fdi_bc_bifurcation(dev, true);
4600
4601                 break;
4602         default:
4603                 BUG();
4604         }
4605 }
4606
4607 /*
4608  * Finds the encoder associated with the given CRTC. This can only be
4609  * used when we know that the CRTC isn't feeding multiple encoders!
4610  */
4611 static struct intel_encoder *
4612 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4613                            const struct intel_crtc_state *crtc_state)
4614 {
4615         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4616         const struct drm_connector_state *connector_state;
4617         const struct drm_connector *connector;
4618         struct intel_encoder *encoder = NULL;
4619         int num_encoders = 0;
4620         int i;
4621
4622         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4623                 if (connector_state->crtc != &crtc->base)
4624                         continue;
4625
4626                 encoder = to_intel_encoder(connector_state->best_encoder);
4627                 num_encoders++;
4628         }
4629
4630         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4631              num_encoders, pipe_name(crtc->pipe));
4632
4633         return encoder;
4634 }
4635
4636 /*
4637  * Enable PCH resources required for PCH ports:
4638  *   - PCH PLLs
4639  *   - FDI training & RX/TX
4640  *   - update transcoder timings
4641  *   - DP transcoding bits
4642  *   - transcoder
4643  */
4644 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4645                                 const struct intel_crtc_state *crtc_state)
4646 {
4647         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4648         struct drm_device *dev = crtc->base.dev;
4649         struct drm_i915_private *dev_priv = to_i915(dev);
4650         int pipe = crtc->pipe;
4651         u32 temp;
4652
4653         assert_pch_transcoder_disabled(dev_priv, pipe);
4654
4655         if (IS_IVYBRIDGE(dev_priv))
4656                 ivybridge_update_fdi_bc_bifurcation(crtc);
4657
4658         /* Write the TU size bits before fdi link training, so that error
4659          * detection works. */
4660         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4661                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4662
4663         /* For PCH output, training FDI link */
4664         dev_priv->display.fdi_link_train(crtc, crtc_state);
4665
4666         /* We need to program the right clock selection before writing the pixel
4667          * mutliplier into the DPLL. */
4668         if (HAS_PCH_CPT(dev_priv)) {
4669                 u32 sel;
4670
4671                 temp = I915_READ(PCH_DPLL_SEL);
4672                 temp |= TRANS_DPLL_ENABLE(pipe);
4673                 sel = TRANS_DPLLB_SEL(pipe);
4674                 if (crtc_state->shared_dpll ==
4675                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4676                         temp |= sel;
4677                 else
4678                         temp &= ~sel;
4679                 I915_WRITE(PCH_DPLL_SEL, temp);
4680         }
4681
4682         /* XXX: pch pll's can be enabled any time before we enable the PCH
4683          * transcoder, and we actually should do this to not upset any PCH
4684          * transcoder that already use the clock when we share it.
4685          *
4686          * Note that enable_shared_dpll tries to do the right thing, but
4687          * get_shared_dpll unconditionally resets the pll - we need that to have
4688          * the right LVDS enable sequence. */
4689         intel_enable_shared_dpll(crtc);
4690
4691         /* set transcoder timing, panel must allow it */
4692         assert_panel_unlocked(dev_priv, pipe);
4693         ironlake_pch_transcoder_set_timings(crtc, pipe);
4694
4695         intel_fdi_normal_train(crtc);
4696
4697         /* For PCH DP, enable TRANS_DP_CTL */
4698         if (HAS_PCH_CPT(dev_priv) &&
4699             intel_crtc_has_dp_encoder(crtc_state)) {
4700                 const struct drm_display_mode *adjusted_mode =
4701                         &crtc_state->base.adjusted_mode;
4702                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4703                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4704                 enum port port;
4705
4706                 temp = I915_READ(reg);
4707                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4708                           TRANS_DP_SYNC_MASK |
4709                           TRANS_DP_BPC_MASK);
4710                 temp |= TRANS_DP_OUTPUT_ENABLE;
4711                 temp |= bpc << 9; /* same format but at 11:9 */
4712
4713                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4714                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4715                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4716                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4717
4718                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4719                 WARN_ON(port < PORT_B || port > PORT_D);
4720                 temp |= TRANS_DP_PORT_SEL(port);
4721
4722                 I915_WRITE(reg, temp);
4723         }
4724
4725         ironlake_enable_pch_transcoder(dev_priv, pipe);
4726 }
4727
4728 static void lpt_pch_enable(const struct intel_atomic_state *state,
4729                            const struct intel_crtc_state *crtc_state)
4730 {
4731         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4732         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4733         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4734
4735         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4736
4737         lpt_program_iclkip(crtc);
4738
4739         /* Set transcoder timing. */
4740         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4741
4742         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4743 }
4744
4745 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4746 {
4747         struct drm_i915_private *dev_priv = to_i915(dev);
4748         i915_reg_t dslreg = PIPEDSL(pipe);
4749         u32 temp;
4750
4751         temp = I915_READ(dslreg);
4752         udelay(500);
4753         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4754                 if (wait_for(I915_READ(dslreg) != temp, 5))
4755                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4756         }
4757 }
4758
4759 /*
4760  * The hardware phase 0.0 refers to the center of the pixel.
4761  * We want to start from the top/left edge which is phase
4762  * -0.5. That matches how the hardware calculates the scaling
4763  * factors (from top-left of the first pixel to bottom-right
4764  * of the last pixel, as opposed to the pixel centers).
4765  *
4766  * For 4:2:0 subsampled chroma planes we obviously have to
4767  * adjust that so that the chroma sample position lands in
4768  * the right spot.
4769  *
4770  * Note that for packed YCbCr 4:2:2 formats there is no way to
4771  * control chroma siting. The hardware simply replicates the
4772  * chroma samples for both of the luma samples, and thus we don't
4773  * actually get the expected MPEG2 chroma siting convention :(
4774  * The same behaviour is observed on pre-SKL platforms as well.
4775  */
4776 u16 skl_scaler_calc_phase(int sub, bool chroma_cosited)
4777 {
4778         int phase = -0x8000;
4779         u16 trip = 0;
4780
4781         if (chroma_cosited)
4782                 phase += (sub - 1) * 0x8000 / sub;
4783
4784         if (phase < 0)
4785                 phase = 0x10000 + phase;
4786         else
4787                 trip = PS_PHASE_TRIP;
4788
4789         return ((phase >> 2) & PS_PHASE_MASK) | trip;
4790 }
4791
4792 static int
4793 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4794                   unsigned int scaler_user, int *scaler_id,
4795                   int src_w, int src_h, int dst_w, int dst_h,
4796                   bool plane_scaler_check,
4797                   uint32_t pixel_format)
4798 {
4799         struct intel_crtc_scaler_state *scaler_state =
4800                 &crtc_state->scaler_state;
4801         struct intel_crtc *intel_crtc =
4802                 to_intel_crtc(crtc_state->base.crtc);
4803         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4804         const struct drm_display_mode *adjusted_mode =
4805                 &crtc_state->base.adjusted_mode;
4806         int need_scaling;
4807
4808         /*
4809          * Src coordinates are already rotated by 270 degrees for
4810          * the 90/270 degree plane rotation cases (to match the
4811          * GTT mapping), hence no need to account for rotation here.
4812          */
4813         need_scaling = src_w != dst_w || src_h != dst_h;
4814
4815         if (plane_scaler_check)
4816                 if (pixel_format == DRM_FORMAT_NV12)
4817                         need_scaling = true;
4818
4819         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4820                 need_scaling = true;
4821
4822         /*
4823          * Scaling/fitting not supported in IF-ID mode in GEN9+
4824          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4825          * Once NV12 is enabled, handle it here while allocating scaler
4826          * for NV12.
4827          */
4828         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4829             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4830                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4831                 return -EINVAL;
4832         }
4833
4834         /*
4835          * if plane is being disabled or scaler is no more required or force detach
4836          *  - free scaler binded to this plane/crtc
4837          *  - in order to do this, update crtc->scaler_usage
4838          *
4839          * Here scaler state in crtc_state is set free so that
4840          * scaler can be assigned to other user. Actual register
4841          * update to free the scaler is done in plane/panel-fit programming.
4842          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4843          */
4844         if (force_detach || !need_scaling) {
4845                 if (*scaler_id >= 0) {
4846                         scaler_state->scaler_users &= ~(1 << scaler_user);
4847                         scaler_state->scalers[*scaler_id].in_use = 0;
4848
4849                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4850                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4851                                 intel_crtc->pipe, scaler_user, *scaler_id,
4852                                 scaler_state->scaler_users);
4853                         *scaler_id = -1;
4854                 }
4855                 return 0;
4856         }
4857
4858         if (plane_scaler_check && pixel_format == DRM_FORMAT_NV12 &&
4859             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4860                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4861                 return -EINVAL;
4862         }
4863
4864         /* range checks */
4865         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4866             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4867             (IS_GEN11(dev_priv) &&
4868              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4869               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4870             (!IS_GEN11(dev_priv) &&
4871              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4872               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4873                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4874                         "size is out of scaler range\n",
4875                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4876                 return -EINVAL;
4877         }
4878
4879         /* mark this plane as a scaler user in crtc_state */
4880         scaler_state->scaler_users |= (1 << scaler_user);
4881         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4882                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4883                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4884                 scaler_state->scaler_users);
4885
4886         return 0;
4887 }
4888
4889 /**
4890  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4891  *
4892  * @state: crtc's scaler state
4893  *
4894  * Return
4895  *     0 - scaler_usage updated successfully
4896  *    error - requested scaling cannot be supported or other error condition
4897  */
4898 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4899 {
4900         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4901
4902         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4903                                  &state->scaler_state.scaler_id,
4904                                  state->pipe_src_w, state->pipe_src_h,
4905                                  adjusted_mode->crtc_hdisplay,
4906                                  adjusted_mode->crtc_vdisplay, false, 0);
4907 }
4908
4909 /**
4910  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4911  * @crtc_state: crtc's scaler state
4912  * @plane_state: atomic plane state to update
4913  *
4914  * Return
4915  *     0 - scaler_usage updated successfully
4916  *    error - requested scaling cannot be supported or other error condition
4917  */
4918 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4919                                    struct intel_plane_state *plane_state)
4920 {
4921
4922         struct intel_plane *intel_plane =
4923                 to_intel_plane(plane_state->base.plane);
4924         struct drm_framebuffer *fb = plane_state->base.fb;
4925         int ret;
4926
4927         bool force_detach = !fb || !plane_state->base.visible;
4928
4929         ret = skl_update_scaler(crtc_state, force_detach,
4930                                 drm_plane_index(&intel_plane->base),
4931                                 &plane_state->scaler_id,
4932                                 drm_rect_width(&plane_state->base.src) >> 16,
4933                                 drm_rect_height(&plane_state->base.src) >> 16,
4934                                 drm_rect_width(&plane_state->base.dst),
4935                                 drm_rect_height(&plane_state->base.dst),
4936                                 fb ? true : false, fb ? fb->format->format : 0);
4937
4938         if (ret || plane_state->scaler_id < 0)
4939                 return ret;
4940
4941         /* check colorkey */
4942         if (plane_state->ckey.flags) {
4943                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4944                               intel_plane->base.base.id,
4945                               intel_plane->base.name);
4946                 return -EINVAL;
4947         }
4948
4949         /* Check src format */
4950         switch (fb->format->format) {
4951         case DRM_FORMAT_RGB565:
4952         case DRM_FORMAT_XBGR8888:
4953         case DRM_FORMAT_XRGB8888:
4954         case DRM_FORMAT_ABGR8888:
4955         case DRM_FORMAT_ARGB8888:
4956         case DRM_FORMAT_XRGB2101010:
4957         case DRM_FORMAT_XBGR2101010:
4958         case DRM_FORMAT_YUYV:
4959         case DRM_FORMAT_YVYU:
4960         case DRM_FORMAT_UYVY:
4961         case DRM_FORMAT_VYUY:
4962         case DRM_FORMAT_NV12:
4963                 break;
4964         default:
4965                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4966                               intel_plane->base.base.id, intel_plane->base.name,
4967                               fb->base.id, fb->format->format);
4968                 return -EINVAL;
4969         }
4970
4971         return 0;
4972 }
4973
4974 static void skylake_scaler_disable(struct intel_crtc *crtc)
4975 {
4976         int i;
4977
4978         for (i = 0; i < crtc->num_scalers; i++)
4979                 skl_detach_scaler(crtc, i);
4980 }
4981
4982 static void skylake_pfit_enable(struct intel_crtc *crtc)
4983 {
4984         struct drm_device *dev = crtc->base.dev;
4985         struct drm_i915_private *dev_priv = to_i915(dev);
4986         int pipe = crtc->pipe;
4987         struct intel_crtc_scaler_state *scaler_state =
4988                 &crtc->config->scaler_state;
4989
4990         if (crtc->config->pch_pfit.enabled) {
4991                 u16 uv_rgb_hphase, uv_rgb_vphase;
4992                 int id;
4993
4994                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4995                         return;
4996
4997                 uv_rgb_hphase = skl_scaler_calc_phase(1, false);
4998                 uv_rgb_vphase = skl_scaler_calc_phase(1, false);
4999
5000                 id = scaler_state->scaler_id;
5001                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5002                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5003                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5004                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5005                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5006                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5007                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
5008                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
5009         }
5010 }
5011
5012 static void ironlake_pfit_enable(struct intel_crtc *crtc)
5013 {
5014         struct drm_device *dev = crtc->base.dev;
5015         struct drm_i915_private *dev_priv = to_i915(dev);
5016         int pipe = crtc->pipe;
5017
5018         if (crtc->config->pch_pfit.enabled) {
5019                 /* Force use of hard-coded filter coefficients
5020                  * as some pre-programmed values are broken,
5021                  * e.g. x201.
5022                  */
5023                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5024                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5025                                                  PF_PIPE_SEL_IVB(pipe));
5026                 else
5027                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5028                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
5029                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
5030         }
5031 }
5032
5033 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5034 {
5035         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5036         struct drm_device *dev = crtc->base.dev;
5037         struct drm_i915_private *dev_priv = to_i915(dev);
5038
5039         if (!crtc_state->ips_enabled)
5040                 return;
5041
5042         /*
5043          * We can only enable IPS after we enable a plane and wait for a vblank
5044          * This function is called from post_plane_update, which is run after
5045          * a vblank wait.
5046          */
5047         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5048
5049         if (IS_BROADWELL(dev_priv)) {
5050                 mutex_lock(&dev_priv->pcu_lock);
5051                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5052                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5053                 mutex_unlock(&dev_priv->pcu_lock);
5054                 /* Quoting Art Runyan: "its not safe to expect any particular
5055                  * value in IPS_CTL bit 31 after enabling IPS through the
5056                  * mailbox." Moreover, the mailbox may return a bogus state,
5057                  * so we need to just enable it and continue on.
5058                  */
5059         } else {
5060                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5061                 /* The bit only becomes 1 in the next vblank, so this wait here
5062                  * is essentially intel_wait_for_vblank. If we don't have this
5063                  * and don't wait for vblanks until the end of crtc_enable, then
5064                  * the HW state readout code will complain that the expected
5065                  * IPS_CTL value is not the one we read. */
5066                 if (intel_wait_for_register(dev_priv,
5067                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5068                                             50))
5069                         DRM_ERROR("Timed out waiting for IPS enable\n");
5070         }
5071 }
5072
5073 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5074 {
5075         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5076         struct drm_device *dev = crtc->base.dev;
5077         struct drm_i915_private *dev_priv = to_i915(dev);
5078
5079         if (!crtc_state->ips_enabled)
5080                 return;
5081
5082         if (IS_BROADWELL(dev_priv)) {
5083                 mutex_lock(&dev_priv->pcu_lock);
5084                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5085                 mutex_unlock(&dev_priv->pcu_lock);
5086                 /*
5087                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5088                  * 42ms timeout value leads to occasional timeouts so use 100ms
5089                  * instead.
5090                  */
5091                 if (intel_wait_for_register(dev_priv,
5092                                             IPS_CTL, IPS_ENABLE, 0,
5093                                             100))
5094                         DRM_ERROR("Timed out waiting for IPS disable\n");
5095         } else {
5096                 I915_WRITE(IPS_CTL, 0);
5097                 POSTING_READ(IPS_CTL);
5098         }
5099
5100         /* We need to wait for a vblank before we can disable the plane. */
5101         intel_wait_for_vblank(dev_priv, crtc->pipe);
5102 }
5103
5104 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5105 {
5106         if (intel_crtc->overlay) {
5107                 struct drm_device *dev = intel_crtc->base.dev;
5108
5109                 mutex_lock(&dev->struct_mutex);
5110                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5111                 mutex_unlock(&dev->struct_mutex);
5112         }
5113
5114         /* Let userspace switch the overlay on again. In most cases userspace
5115          * has to recompute where to put it anyway.
5116          */
5117 }
5118
5119 /**
5120  * intel_post_enable_primary - Perform operations after enabling primary plane
5121  * @crtc: the CRTC whose primary plane was just enabled
5122  * @new_crtc_state: the enabling state
5123  *
5124  * Performs potentially sleeping operations that must be done after the primary
5125  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5126  * called due to an explicit primary plane update, or due to an implicit
5127  * re-enable that is caused when a sprite plane is updated to no longer
5128  * completely hide the primary plane.
5129  */
5130 static void
5131 intel_post_enable_primary(struct drm_crtc *crtc,
5132                           const struct intel_crtc_state *new_crtc_state)
5133 {
5134         struct drm_device *dev = crtc->dev;
5135         struct drm_i915_private *dev_priv = to_i915(dev);
5136         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5137         int pipe = intel_crtc->pipe;
5138
5139         /*
5140          * Gen2 reports pipe underruns whenever all planes are disabled.
5141          * So don't enable underrun reporting before at least some planes
5142          * are enabled.
5143          * FIXME: Need to fix the logic to work when we turn off all planes
5144          * but leave the pipe running.
5145          */
5146         if (IS_GEN2(dev_priv))
5147                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5148
5149         /* Underruns don't always raise interrupts, so check manually. */
5150         intel_check_cpu_fifo_underruns(dev_priv);
5151         intel_check_pch_fifo_underruns(dev_priv);
5152 }
5153
5154 /* FIXME get rid of this and use pre_plane_update */
5155 static void
5156 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5157 {
5158         struct drm_device *dev = crtc->dev;
5159         struct drm_i915_private *dev_priv = to_i915(dev);
5160         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5161         int pipe = intel_crtc->pipe;
5162
5163         /*
5164          * Gen2 reports pipe underruns whenever all planes are disabled.
5165          * So disable underrun reporting before all the planes get disabled.
5166          */
5167         if (IS_GEN2(dev_priv))
5168                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5169
5170         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5171
5172         /*
5173          * Vblank time updates from the shadow to live plane control register
5174          * are blocked if the memory self-refresh mode is active at that
5175          * moment. So to make sure the plane gets truly disabled, disable
5176          * first the self-refresh mode. The self-refresh enable bit in turn
5177          * will be checked/applied by the HW only at the next frame start
5178          * event which is after the vblank start event, so we need to have a
5179          * wait-for-vblank between disabling the plane and the pipe.
5180          */
5181         if (HAS_GMCH_DISPLAY(dev_priv) &&
5182             intel_set_memory_cxsr(dev_priv, false))
5183                 intel_wait_for_vblank(dev_priv, pipe);
5184 }
5185
5186 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5187                                        const struct intel_crtc_state *new_crtc_state)
5188 {
5189         if (!old_crtc_state->ips_enabled)
5190                 return false;
5191
5192         if (needs_modeset(&new_crtc_state->base))
5193                 return true;
5194
5195         return !new_crtc_state->ips_enabled;
5196 }
5197
5198 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5199                                        const struct intel_crtc_state *new_crtc_state)
5200 {
5201         if (!new_crtc_state->ips_enabled)
5202                 return false;
5203
5204         if (needs_modeset(&new_crtc_state->base))
5205                 return true;
5206
5207         /*
5208          * We can't read out IPS on broadwell, assume the worst and
5209          * forcibly enable IPS on the first fastset.
5210          */
5211         if (new_crtc_state->update_pipe &&
5212             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5213                 return true;
5214
5215         return !old_crtc_state->ips_enabled;
5216 }
5217
5218 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5219                           const struct intel_crtc_state *crtc_state)
5220 {
5221         if (!crtc_state->nv12_planes)
5222                 return false;
5223
5224         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
5225                 return false;
5226
5227         if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5228             IS_CANNONLAKE(dev_priv))
5229                 return true;
5230
5231         return false;
5232 }
5233
5234 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5235 {
5236         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5237         struct drm_device *dev = crtc->base.dev;
5238         struct drm_i915_private *dev_priv = to_i915(dev);
5239         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5240         struct intel_crtc_state *pipe_config =
5241                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5242                                                 crtc);
5243         struct drm_plane *primary = crtc->base.primary;
5244         struct drm_plane_state *old_primary_state =
5245                 drm_atomic_get_old_plane_state(old_state, primary);
5246
5247         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5248
5249         if (pipe_config->update_wm_post && pipe_config->base.active)
5250                 intel_update_watermarks(crtc);
5251
5252         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5253                 hsw_enable_ips(pipe_config);
5254
5255         if (old_primary_state) {
5256                 struct drm_plane_state *new_primary_state =
5257                         drm_atomic_get_new_plane_state(old_state, primary);
5258
5259                 intel_fbc_post_update(crtc);
5260
5261                 if (new_primary_state->visible &&
5262                     (needs_modeset(&pipe_config->base) ||
5263                      !old_primary_state->visible))
5264                         intel_post_enable_primary(&crtc->base, pipe_config);
5265         }
5266
5267         /* Display WA 827 */
5268         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5269             !needs_nv12_wa(dev_priv, pipe_config)) {
5270                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5271                 skl_wa_528(dev_priv, crtc->pipe, false);
5272         }
5273 }
5274
5275 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5276                                    struct intel_crtc_state *pipe_config)
5277 {
5278         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5279         struct drm_device *dev = crtc->base.dev;
5280         struct drm_i915_private *dev_priv = to_i915(dev);
5281         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5282         struct drm_plane *primary = crtc->base.primary;
5283         struct drm_plane_state *old_primary_state =
5284                 drm_atomic_get_old_plane_state(old_state, primary);
5285         bool modeset = needs_modeset(&pipe_config->base);
5286         struct intel_atomic_state *old_intel_state =
5287                 to_intel_atomic_state(old_state);
5288
5289         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5290                 hsw_disable_ips(old_crtc_state);
5291
5292         if (old_primary_state) {
5293                 struct intel_plane_state *new_primary_state =
5294                         intel_atomic_get_new_plane_state(old_intel_state,
5295                                                          to_intel_plane(primary));
5296
5297                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5298                 /*
5299                  * Gen2 reports pipe underruns whenever all planes are disabled.
5300                  * So disable underrun reporting before all the planes get disabled.
5301                  */
5302                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5303                     (modeset || !new_primary_state->base.visible))
5304                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5305         }
5306
5307         /* Display WA 827 */
5308         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5309             needs_nv12_wa(dev_priv, pipe_config)) {
5310                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5311                 skl_wa_528(dev_priv, crtc->pipe, true);
5312         }
5313
5314         /*
5315          * Vblank time updates from the shadow to live plane control register
5316          * are blocked if the memory self-refresh mode is active at that
5317          * moment. So to make sure the plane gets truly disabled, disable
5318          * first the self-refresh mode. The self-refresh enable bit in turn
5319          * will be checked/applied by the HW only at the next frame start
5320          * event which is after the vblank start event, so we need to have a
5321          * wait-for-vblank between disabling the plane and the pipe.
5322          */
5323         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5324             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5325                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5326
5327         /*
5328          * IVB workaround: must disable low power watermarks for at least
5329          * one frame before enabling scaling.  LP watermarks can be re-enabled
5330          * when scaling is disabled.
5331          *
5332          * WaCxSRDisabledForSpriteScaling:ivb
5333          */
5334         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5335                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5336
5337         /*
5338          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5339          * watermark programming here.
5340          */
5341         if (needs_modeset(&pipe_config->base))
5342                 return;
5343
5344         /*
5345          * For platforms that support atomic watermarks, program the
5346          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5347          * will be the intermediate values that are safe for both pre- and
5348          * post- vblank; when vblank happens, the 'active' values will be set
5349          * to the final 'target' values and we'll do this again to get the
5350          * optimal watermarks.  For gen9+ platforms, the values we program here
5351          * will be the final target values which will get automatically latched
5352          * at vblank time; no further programming will be necessary.
5353          *
5354          * If a platform hasn't been transitioned to atomic watermarks yet,
5355          * we'll continue to update watermarks the old way, if flags tell
5356          * us to.
5357          */
5358         if (dev_priv->display.initial_watermarks != NULL)
5359                 dev_priv->display.initial_watermarks(old_intel_state,
5360                                                      pipe_config);
5361         else if (pipe_config->update_wm_pre)
5362                 intel_update_watermarks(crtc);
5363 }
5364
5365 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5366 {
5367         struct drm_device *dev = crtc->dev;
5368         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5369         struct drm_plane *p;
5370         int pipe = intel_crtc->pipe;
5371
5372         intel_crtc_dpms_overlay_disable(intel_crtc);
5373
5374         drm_for_each_plane_mask(p, dev, plane_mask)
5375                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5376
5377         /*
5378          * FIXME: Once we grow proper nuclear flip support out of this we need
5379          * to compute the mask of flip planes precisely. For the time being
5380          * consider this a flip to a NULL plane.
5381          */
5382         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5383 }
5384
5385 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5386                                           struct intel_crtc_state *crtc_state,
5387                                           struct drm_atomic_state *old_state)
5388 {
5389         struct drm_connector_state *conn_state;
5390         struct drm_connector *conn;
5391         int i;
5392
5393         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5394                 struct intel_encoder *encoder =
5395                         to_intel_encoder(conn_state->best_encoder);
5396
5397                 if (conn_state->crtc != crtc)
5398                         continue;
5399
5400                 if (encoder->pre_pll_enable)
5401                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5402         }
5403 }
5404
5405 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5406                                       struct intel_crtc_state *crtc_state,
5407                                       struct drm_atomic_state *old_state)
5408 {
5409         struct drm_connector_state *conn_state;
5410         struct drm_connector *conn;
5411         int i;
5412
5413         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5414                 struct intel_encoder *encoder =
5415                         to_intel_encoder(conn_state->best_encoder);
5416
5417                 if (conn_state->crtc != crtc)
5418                         continue;
5419
5420                 if (encoder->pre_enable)
5421                         encoder->pre_enable(encoder, crtc_state, conn_state);
5422         }
5423 }
5424
5425 static void intel_encoders_enable(struct drm_crtc *crtc,
5426                                   struct intel_crtc_state *crtc_state,
5427                                   struct drm_atomic_state *old_state)
5428 {
5429         struct drm_connector_state *conn_state;
5430         struct drm_connector *conn;
5431         int i;
5432
5433         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5434                 struct intel_encoder *encoder =
5435                         to_intel_encoder(conn_state->best_encoder);
5436
5437                 if (conn_state->crtc != crtc)
5438                         continue;
5439
5440                 encoder->enable(encoder, crtc_state, conn_state);
5441                 intel_opregion_notify_encoder(encoder, true);
5442         }
5443 }
5444
5445 static void intel_encoders_disable(struct drm_crtc *crtc,
5446                                    struct intel_crtc_state *old_crtc_state,
5447                                    struct drm_atomic_state *old_state)
5448 {
5449         struct drm_connector_state *old_conn_state;
5450         struct drm_connector *conn;
5451         int i;
5452
5453         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5454                 struct intel_encoder *encoder =
5455                         to_intel_encoder(old_conn_state->best_encoder);
5456
5457                 if (old_conn_state->crtc != crtc)
5458                         continue;
5459
5460                 intel_opregion_notify_encoder(encoder, false);
5461                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5462         }
5463 }
5464
5465 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5466                                         struct intel_crtc_state *old_crtc_state,
5467                                         struct drm_atomic_state *old_state)
5468 {
5469         struct drm_connector_state *old_conn_state;
5470         struct drm_connector *conn;
5471         int i;
5472
5473         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5474                 struct intel_encoder *encoder =
5475                         to_intel_encoder(old_conn_state->best_encoder);
5476
5477                 if (old_conn_state->crtc != crtc)
5478                         continue;
5479
5480                 if (encoder->post_disable)
5481                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5482         }
5483 }
5484
5485 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5486                                             struct intel_crtc_state *old_crtc_state,
5487                                             struct drm_atomic_state *old_state)
5488 {
5489         struct drm_connector_state *old_conn_state;
5490         struct drm_connector *conn;
5491         int i;
5492
5493         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5494                 struct intel_encoder *encoder =
5495                         to_intel_encoder(old_conn_state->best_encoder);
5496
5497                 if (old_conn_state->crtc != crtc)
5498                         continue;
5499
5500                 if (encoder->post_pll_disable)
5501                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5502         }
5503 }
5504
5505 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5506                                  struct drm_atomic_state *old_state)
5507 {
5508         struct drm_crtc *crtc = pipe_config->base.crtc;
5509         struct drm_device *dev = crtc->dev;
5510         struct drm_i915_private *dev_priv = to_i915(dev);
5511         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5512         int pipe = intel_crtc->pipe;
5513         struct intel_atomic_state *old_intel_state =
5514                 to_intel_atomic_state(old_state);
5515
5516         if (WARN_ON(intel_crtc->active))
5517                 return;
5518
5519         /*
5520          * Sometimes spurious CPU pipe underruns happen during FDI
5521          * training, at least with VGA+HDMI cloning. Suppress them.
5522          *
5523          * On ILK we get an occasional spurious CPU pipe underruns
5524          * between eDP port A enable and vdd enable. Also PCH port
5525          * enable seems to result in the occasional CPU pipe underrun.
5526          *
5527          * Spurious PCH underruns also occur during PCH enabling.
5528          */
5529         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5530         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5531
5532         if (intel_crtc->config->has_pch_encoder)
5533                 intel_prepare_shared_dpll(intel_crtc);
5534
5535         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5536                 intel_dp_set_m_n(intel_crtc, M1_N1);
5537
5538         intel_set_pipe_timings(intel_crtc);
5539         intel_set_pipe_src_size(intel_crtc);
5540
5541         if (intel_crtc->config->has_pch_encoder) {
5542                 intel_cpu_transcoder_set_m_n(intel_crtc,
5543                                      &intel_crtc->config->fdi_m_n, NULL);
5544         }
5545
5546         ironlake_set_pipeconf(crtc);
5547
5548         intel_crtc->active = true;
5549
5550         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5551
5552         if (intel_crtc->config->has_pch_encoder) {
5553                 /* Note: FDI PLL enabling _must_ be done before we enable the
5554                  * cpu pipes, hence this is separate from all the other fdi/pch
5555                  * enabling. */
5556                 ironlake_fdi_pll_enable(intel_crtc);
5557         } else {
5558                 assert_fdi_tx_disabled(dev_priv, pipe);
5559                 assert_fdi_rx_disabled(dev_priv, pipe);
5560         }
5561
5562         ironlake_pfit_enable(intel_crtc);
5563
5564         /*
5565          * On ILK+ LUT must be loaded before the pipe is running but with
5566          * clocks enabled
5567          */
5568         intel_color_load_luts(&pipe_config->base);
5569
5570         if (dev_priv->display.initial_watermarks != NULL)
5571                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5572         intel_enable_pipe(pipe_config);
5573
5574         if (intel_crtc->config->has_pch_encoder)
5575                 ironlake_pch_enable(old_intel_state, pipe_config);
5576
5577         assert_vblank_disabled(crtc);
5578         drm_crtc_vblank_on(crtc);
5579
5580         intel_encoders_enable(crtc, pipe_config, old_state);
5581
5582         if (HAS_PCH_CPT(dev_priv))
5583                 cpt_verify_modeset(dev, intel_crtc->pipe);
5584
5585         /*
5586          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5587          * And a second vblank wait is needed at least on ILK with
5588          * some interlaced HDMI modes. Let's do the double wait always
5589          * in case there are more corner cases we don't know about.
5590          */
5591         if (intel_crtc->config->has_pch_encoder) {
5592                 intel_wait_for_vblank(dev_priv, pipe);
5593                 intel_wait_for_vblank(dev_priv, pipe);
5594         }
5595         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5596         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5597 }
5598
5599 /* IPS only exists on ULT machines and is tied to pipe A. */
5600 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5601 {
5602         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5603 }
5604
5605 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5606                                             enum pipe pipe, bool apply)
5607 {
5608         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5609         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5610
5611         if (apply)
5612                 val |= mask;
5613         else
5614                 val &= ~mask;
5615
5616         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5617 }
5618
5619 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5620 {
5621         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5622         enum pipe pipe = crtc->pipe;
5623         uint32_t val;
5624
5625         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5626
5627         /* Program B credit equally to all pipes */
5628         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5629
5630         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5631 }
5632
5633 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5634                                 struct drm_atomic_state *old_state)
5635 {
5636         struct drm_crtc *crtc = pipe_config->base.crtc;
5637         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5638         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5639         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5640         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5641         struct intel_atomic_state *old_intel_state =
5642                 to_intel_atomic_state(old_state);
5643         bool psl_clkgate_wa;
5644         u32 pipe_chicken;
5645
5646         if (WARN_ON(intel_crtc->active))
5647                 return;
5648
5649         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5650
5651         if (intel_crtc->config->shared_dpll)
5652                 intel_enable_shared_dpll(intel_crtc);
5653
5654         if (INTEL_GEN(dev_priv) >= 11)
5655                 icl_map_plls_to_ports(crtc, pipe_config, old_state);
5656
5657         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5658
5659         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5660                 intel_dp_set_m_n(intel_crtc, M1_N1);
5661
5662         if (!transcoder_is_dsi(cpu_transcoder))
5663                 intel_set_pipe_timings(intel_crtc);
5664
5665         intel_set_pipe_src_size(intel_crtc);
5666
5667         if (cpu_transcoder != TRANSCODER_EDP &&
5668             !transcoder_is_dsi(cpu_transcoder)) {
5669                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5670                            intel_crtc->config->pixel_multiplier - 1);
5671         }
5672
5673         if (intel_crtc->config->has_pch_encoder) {
5674                 intel_cpu_transcoder_set_m_n(intel_crtc,
5675                                      &intel_crtc->config->fdi_m_n, NULL);
5676         }
5677
5678         if (!transcoder_is_dsi(cpu_transcoder))
5679                 haswell_set_pipeconf(crtc);
5680
5681         haswell_set_pipemisc(crtc);
5682
5683         intel_color_set_csc(&pipe_config->base);
5684
5685         intel_crtc->active = true;
5686
5687         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5688         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5689                          intel_crtc->config->pch_pfit.enabled;
5690         if (psl_clkgate_wa)
5691                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5692
5693         if (INTEL_GEN(dev_priv) >= 9)
5694                 skylake_pfit_enable(intel_crtc);
5695         else
5696                 ironlake_pfit_enable(intel_crtc);
5697
5698         /*
5699          * On ILK+ LUT must be loaded before the pipe is running but with
5700          * clocks enabled
5701          */
5702         intel_color_load_luts(&pipe_config->base);
5703
5704         /*
5705          * Display WA #1153: enable hardware to bypass the alpha math
5706          * and rounding for per-pixel values 00 and 0xff
5707          */
5708         if (INTEL_GEN(dev_priv) >= 11) {
5709                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5710                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5711                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5712                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5713         }
5714
5715         intel_ddi_set_pipe_settings(pipe_config);
5716         if (!transcoder_is_dsi(cpu_transcoder))
5717                 intel_ddi_enable_transcoder_func(pipe_config);
5718
5719         if (dev_priv->display.initial_watermarks != NULL)
5720                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5721
5722         if (INTEL_GEN(dev_priv) >= 11)
5723                 icl_pipe_mbus_enable(intel_crtc);
5724
5725         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5726         if (!transcoder_is_dsi(cpu_transcoder))
5727                 intel_enable_pipe(pipe_config);
5728
5729         if (intel_crtc->config->has_pch_encoder)
5730                 lpt_pch_enable(old_intel_state, pipe_config);
5731
5732         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5733                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5734
5735         assert_vblank_disabled(crtc);
5736         drm_crtc_vblank_on(crtc);
5737
5738         intel_encoders_enable(crtc, pipe_config, old_state);
5739
5740         if (psl_clkgate_wa) {
5741                 intel_wait_for_vblank(dev_priv, pipe);
5742                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5743         }
5744
5745         /* If we change the relative order between pipe/planes enabling, we need
5746          * to change the workaround. */
5747         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5748         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5749                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5750                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5751         }
5752 }
5753
5754 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5755 {
5756         struct drm_device *dev = crtc->base.dev;
5757         struct drm_i915_private *dev_priv = to_i915(dev);
5758         int pipe = crtc->pipe;
5759
5760         /* To avoid upsetting the power well on haswell only disable the pfit if
5761          * it's in use. The hw state code will make sure we get this right. */
5762         if (force || crtc->config->pch_pfit.enabled) {
5763                 I915_WRITE(PF_CTL(pipe), 0);
5764                 I915_WRITE(PF_WIN_POS(pipe), 0);
5765                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5766         }
5767 }
5768
5769 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5770                                   struct drm_atomic_state *old_state)
5771 {
5772         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5773         struct drm_device *dev = crtc->dev;
5774         struct drm_i915_private *dev_priv = to_i915(dev);
5775         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5776         int pipe = intel_crtc->pipe;
5777
5778         /*
5779          * Sometimes spurious CPU pipe underruns happen when the
5780          * pipe is already disabled, but FDI RX/TX is still enabled.
5781          * Happens at least with VGA+HDMI cloning. Suppress them.
5782          */
5783         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5784         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5785
5786         intel_encoders_disable(crtc, old_crtc_state, old_state);
5787
5788         drm_crtc_vblank_off(crtc);
5789         assert_vblank_disabled(crtc);
5790
5791         intel_disable_pipe(old_crtc_state);
5792
5793         ironlake_pfit_disable(intel_crtc, false);
5794
5795         if (intel_crtc->config->has_pch_encoder)
5796                 ironlake_fdi_disable(crtc);
5797
5798         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5799
5800         if (intel_crtc->config->has_pch_encoder) {
5801                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5802
5803                 if (HAS_PCH_CPT(dev_priv)) {
5804                         i915_reg_t reg;
5805                         u32 temp;
5806
5807                         /* disable TRANS_DP_CTL */
5808                         reg = TRANS_DP_CTL(pipe);
5809                         temp = I915_READ(reg);
5810                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5811                                   TRANS_DP_PORT_SEL_MASK);
5812                         temp |= TRANS_DP_PORT_SEL_NONE;
5813                         I915_WRITE(reg, temp);
5814
5815                         /* disable DPLL_SEL */
5816                         temp = I915_READ(PCH_DPLL_SEL);
5817                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5818                         I915_WRITE(PCH_DPLL_SEL, temp);
5819                 }
5820
5821                 ironlake_fdi_pll_disable(intel_crtc);
5822         }
5823
5824         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5825         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5826 }
5827
5828 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5829                                  struct drm_atomic_state *old_state)
5830 {
5831         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5832         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5833         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5834         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5835
5836         intel_encoders_disable(crtc, old_crtc_state, old_state);
5837
5838         drm_crtc_vblank_off(crtc);
5839         assert_vblank_disabled(crtc);
5840
5841         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5842         if (!transcoder_is_dsi(cpu_transcoder))
5843                 intel_disable_pipe(old_crtc_state);
5844
5845         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5846                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5847
5848         if (!transcoder_is_dsi(cpu_transcoder))
5849                 intel_ddi_disable_transcoder_func(old_crtc_state);
5850
5851         if (INTEL_GEN(dev_priv) >= 9)
5852                 skylake_scaler_disable(intel_crtc);
5853         else
5854                 ironlake_pfit_disable(intel_crtc, false);
5855
5856         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5857
5858         if (INTEL_GEN(dev_priv) >= 11)
5859                 icl_unmap_plls_to_ports(crtc, old_crtc_state, old_state);
5860 }
5861
5862 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5863 {
5864         struct drm_device *dev = crtc->base.dev;
5865         struct drm_i915_private *dev_priv = to_i915(dev);
5866         struct intel_crtc_state *pipe_config = crtc->config;
5867
5868         if (!pipe_config->gmch_pfit.control)
5869                 return;
5870
5871         /*
5872          * The panel fitter should only be adjusted whilst the pipe is disabled,
5873          * according to register description and PRM.
5874          */
5875         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5876         assert_pipe_disabled(dev_priv, crtc->pipe);
5877
5878         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5879         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5880
5881         /* Border color in case we don't scale up to the full screen. Black by
5882          * default, change to something else for debugging. */
5883         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5884 }
5885
5886 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
5887 {
5888         if (IS_ICELAKE(dev_priv))
5889                 return port >= PORT_C && port <= PORT_F;
5890
5891         return false;
5892 }
5893
5894 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
5895 {
5896         if (!intel_port_is_tc(dev_priv, port))
5897                 return PORT_TC_NONE;
5898
5899         return port - PORT_C;
5900 }
5901
5902 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5903 {
5904         switch (port) {
5905         case PORT_A:
5906                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5907         case PORT_B:
5908                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5909         case PORT_C:
5910                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5911         case PORT_D:
5912                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5913         case PORT_E:
5914                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5915         case PORT_F:
5916                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5917         default:
5918                 MISSING_CASE(port);
5919                 return POWER_DOMAIN_PORT_OTHER;
5920         }
5921 }
5922
5923 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5924                                   struct intel_crtc_state *crtc_state)
5925 {
5926         struct drm_device *dev = crtc->dev;
5927         struct drm_i915_private *dev_priv = to_i915(dev);
5928         struct drm_encoder *encoder;
5929         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5930         enum pipe pipe = intel_crtc->pipe;
5931         u64 mask;
5932         enum transcoder transcoder = crtc_state->cpu_transcoder;
5933
5934         if (!crtc_state->base.active)
5935                 return 0;
5936
5937         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5938         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5939         if (crtc_state->pch_pfit.enabled ||
5940             crtc_state->pch_pfit.force_thru)
5941                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5942
5943         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5944                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5945
5946                 mask |= BIT_ULL(intel_encoder->power_domain);
5947         }
5948
5949         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5950                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5951
5952         if (crtc_state->shared_dpll)
5953                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5954
5955         return mask;
5956 }
5957
5958 static u64
5959 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5960                                struct intel_crtc_state *crtc_state)
5961 {
5962         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5963         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5964         enum intel_display_power_domain domain;
5965         u64 domains, new_domains, old_domains;
5966
5967         old_domains = intel_crtc->enabled_power_domains;
5968         intel_crtc->enabled_power_domains = new_domains =
5969                 get_crtc_power_domains(crtc, crtc_state);
5970
5971         domains = new_domains & ~old_domains;
5972
5973         for_each_power_domain(domain, domains)
5974                 intel_display_power_get(dev_priv, domain);
5975
5976         return old_domains & ~new_domains;
5977 }
5978
5979 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5980                                       u64 domains)
5981 {
5982         enum intel_display_power_domain domain;
5983
5984         for_each_power_domain(domain, domains)
5985                 intel_display_power_put(dev_priv, domain);
5986 }
5987
5988 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5989                                    struct drm_atomic_state *old_state)
5990 {
5991         struct intel_atomic_state *old_intel_state =
5992                 to_intel_atomic_state(old_state);
5993         struct drm_crtc *crtc = pipe_config->base.crtc;
5994         struct drm_device *dev = crtc->dev;
5995         struct drm_i915_private *dev_priv = to_i915(dev);
5996         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5997         int pipe = intel_crtc->pipe;
5998
5999         if (WARN_ON(intel_crtc->active))
6000                 return;
6001
6002         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6003                 intel_dp_set_m_n(intel_crtc, M1_N1);
6004
6005         intel_set_pipe_timings(intel_crtc);
6006         intel_set_pipe_src_size(intel_crtc);
6007
6008         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6009                 struct drm_i915_private *dev_priv = to_i915(dev);
6010
6011                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6012                 I915_WRITE(CHV_CANVAS(pipe), 0);
6013         }
6014
6015         i9xx_set_pipeconf(intel_crtc);
6016
6017         intel_crtc->active = true;
6018
6019         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6020
6021         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6022
6023         if (IS_CHERRYVIEW(dev_priv)) {
6024                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6025                 chv_enable_pll(intel_crtc, intel_crtc->config);
6026         } else {
6027                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6028                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6029         }
6030
6031         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6032
6033         i9xx_pfit_enable(intel_crtc);
6034
6035         intel_color_load_luts(&pipe_config->base);
6036
6037         dev_priv->display.initial_watermarks(old_intel_state,
6038                                              pipe_config);
6039         intel_enable_pipe(pipe_config);
6040
6041         assert_vblank_disabled(crtc);
6042         drm_crtc_vblank_on(crtc);
6043
6044         intel_encoders_enable(crtc, pipe_config, old_state);
6045 }
6046
6047 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6048 {
6049         struct drm_device *dev = crtc->base.dev;
6050         struct drm_i915_private *dev_priv = to_i915(dev);
6051
6052         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6053         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6054 }
6055
6056 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6057                              struct drm_atomic_state *old_state)
6058 {
6059         struct intel_atomic_state *old_intel_state =
6060                 to_intel_atomic_state(old_state);
6061         struct drm_crtc *crtc = pipe_config->base.crtc;
6062         struct drm_device *dev = crtc->dev;
6063         struct drm_i915_private *dev_priv = to_i915(dev);
6064         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6065         enum pipe pipe = intel_crtc->pipe;
6066
6067         if (WARN_ON(intel_crtc->active))
6068                 return;
6069
6070         i9xx_set_pll_dividers(intel_crtc);
6071
6072         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6073                 intel_dp_set_m_n(intel_crtc, M1_N1);
6074
6075         intel_set_pipe_timings(intel_crtc);
6076         intel_set_pipe_src_size(intel_crtc);
6077
6078         i9xx_set_pipeconf(intel_crtc);
6079
6080         intel_crtc->active = true;
6081
6082         if (!IS_GEN2(dev_priv))
6083                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6084
6085         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6086
6087         i9xx_enable_pll(intel_crtc, pipe_config);
6088
6089         i9xx_pfit_enable(intel_crtc);
6090
6091         intel_color_load_luts(&pipe_config->base);
6092
6093         if (dev_priv->display.initial_watermarks != NULL)
6094                 dev_priv->display.initial_watermarks(old_intel_state,
6095                                                      intel_crtc->config);
6096         else
6097                 intel_update_watermarks(intel_crtc);
6098         intel_enable_pipe(pipe_config);
6099
6100         assert_vblank_disabled(crtc);
6101         drm_crtc_vblank_on(crtc);
6102
6103         intel_encoders_enable(crtc, pipe_config, old_state);
6104 }
6105
6106 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6107 {
6108         struct drm_device *dev = crtc->base.dev;
6109         struct drm_i915_private *dev_priv = to_i915(dev);
6110
6111         if (!crtc->config->gmch_pfit.control)
6112                 return;
6113
6114         assert_pipe_disabled(dev_priv, crtc->pipe);
6115
6116         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6117                          I915_READ(PFIT_CONTROL));
6118         I915_WRITE(PFIT_CONTROL, 0);
6119 }
6120
6121 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6122                               struct drm_atomic_state *old_state)
6123 {
6124         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6125         struct drm_device *dev = crtc->dev;
6126         struct drm_i915_private *dev_priv = to_i915(dev);
6127         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6128         int pipe = intel_crtc->pipe;
6129
6130         /*
6131          * On gen2 planes are double buffered but the pipe isn't, so we must
6132          * wait for planes to fully turn off before disabling the pipe.
6133          */
6134         if (IS_GEN2(dev_priv))
6135                 intel_wait_for_vblank(dev_priv, pipe);
6136
6137         intel_encoders_disable(crtc, old_crtc_state, old_state);
6138
6139         drm_crtc_vblank_off(crtc);
6140         assert_vblank_disabled(crtc);
6141
6142         intel_disable_pipe(old_crtc_state);
6143
6144         i9xx_pfit_disable(intel_crtc);
6145
6146         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6147
6148         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6149                 if (IS_CHERRYVIEW(dev_priv))
6150                         chv_disable_pll(dev_priv, pipe);
6151                 else if (IS_VALLEYVIEW(dev_priv))
6152                         vlv_disable_pll(dev_priv, pipe);
6153                 else
6154                         i9xx_disable_pll(intel_crtc);
6155         }
6156
6157         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6158
6159         if (!IS_GEN2(dev_priv))
6160                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6161
6162         if (!dev_priv->display.initial_watermarks)
6163                 intel_update_watermarks(intel_crtc);
6164
6165         /* clock the pipe down to 640x480@60 to potentially save power */
6166         if (IS_I830(dev_priv))
6167                 i830_enable_pipe(dev_priv, pipe);
6168 }
6169
6170 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6171                                         struct drm_modeset_acquire_ctx *ctx)
6172 {
6173         struct intel_encoder *encoder;
6174         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6175         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6176         enum intel_display_power_domain domain;
6177         struct intel_plane *plane;
6178         u64 domains;
6179         struct drm_atomic_state *state;
6180         struct intel_crtc_state *crtc_state;
6181         int ret;
6182
6183         if (!intel_crtc->active)
6184                 return;
6185
6186         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6187                 const struct intel_plane_state *plane_state =
6188                         to_intel_plane_state(plane->base.state);
6189
6190                 if (plane_state->base.visible)
6191                         intel_plane_disable_noatomic(intel_crtc, plane);
6192         }
6193
6194         state = drm_atomic_state_alloc(crtc->dev);
6195         if (!state) {
6196                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6197                               crtc->base.id, crtc->name);
6198                 return;
6199         }
6200
6201         state->acquire_ctx = ctx;
6202
6203         /* Everything's already locked, -EDEADLK can't happen. */
6204         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6205         ret = drm_atomic_add_affected_connectors(state, crtc);
6206
6207         WARN_ON(IS_ERR(crtc_state) || ret);
6208
6209         dev_priv->display.crtc_disable(crtc_state, state);
6210
6211         drm_atomic_state_put(state);
6212
6213         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6214                       crtc->base.id, crtc->name);
6215
6216         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6217         crtc->state->active = false;
6218         intel_crtc->active = false;
6219         crtc->enabled = false;
6220         crtc->state->connector_mask = 0;
6221         crtc->state->encoder_mask = 0;
6222
6223         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6224                 encoder->base.crtc = NULL;
6225
6226         intel_fbc_disable(intel_crtc);
6227         intel_update_watermarks(intel_crtc);
6228         intel_disable_shared_dpll(intel_crtc);
6229
6230         domains = intel_crtc->enabled_power_domains;
6231         for_each_power_domain(domain, domains)
6232                 intel_display_power_put(dev_priv, domain);
6233         intel_crtc->enabled_power_domains = 0;
6234
6235         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6236         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6237         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6238 }
6239
6240 /*
6241  * turn all crtc's off, but do not adjust state
6242  * This has to be paired with a call to intel_modeset_setup_hw_state.
6243  */
6244 int intel_display_suspend(struct drm_device *dev)
6245 {
6246         struct drm_i915_private *dev_priv = to_i915(dev);
6247         struct drm_atomic_state *state;
6248         int ret;
6249
6250         state = drm_atomic_helper_suspend(dev);
6251         ret = PTR_ERR_OR_ZERO(state);
6252         if (ret)
6253                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6254         else
6255                 dev_priv->modeset_restore_state = state;
6256         return ret;
6257 }
6258
6259 void intel_encoder_destroy(struct drm_encoder *encoder)
6260 {
6261         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6262
6263         drm_encoder_cleanup(encoder);
6264         kfree(intel_encoder);
6265 }
6266
6267 /* Cross check the actual hw state with our own modeset state tracking (and it's
6268  * internal consistency). */
6269 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6270                                          struct drm_connector_state *conn_state)
6271 {
6272         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6273
6274         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6275                       connector->base.base.id,
6276                       connector->base.name);
6277
6278         if (connector->get_hw_state(connector)) {
6279                 struct intel_encoder *encoder = connector->encoder;
6280
6281                 I915_STATE_WARN(!crtc_state,
6282                          "connector enabled without attached crtc\n");
6283
6284                 if (!crtc_state)
6285                         return;
6286
6287                 I915_STATE_WARN(!crtc_state->active,
6288                       "connector is active, but attached crtc isn't\n");
6289
6290                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6291                         return;
6292
6293                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6294                         "atomic encoder doesn't match attached encoder\n");
6295
6296                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6297                         "attached encoder crtc differs from connector crtc\n");
6298         } else {
6299                 I915_STATE_WARN(crtc_state && crtc_state->active,
6300                         "attached crtc is active, but connector isn't\n");
6301                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6302                         "best encoder set without crtc!\n");
6303         }
6304 }
6305
6306 int intel_connector_init(struct intel_connector *connector)
6307 {
6308         struct intel_digital_connector_state *conn_state;
6309
6310         /*
6311          * Allocate enough memory to hold intel_digital_connector_state,
6312          * This might be a few bytes too many, but for connectors that don't
6313          * need it we'll free the state and allocate a smaller one on the first
6314          * succesful commit anyway.
6315          */
6316         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6317         if (!conn_state)
6318                 return -ENOMEM;
6319
6320         __drm_atomic_helper_connector_reset(&connector->base,
6321                                             &conn_state->base);
6322
6323         return 0;
6324 }
6325
6326 struct intel_connector *intel_connector_alloc(void)
6327 {
6328         struct intel_connector *connector;
6329
6330         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6331         if (!connector)
6332                 return NULL;
6333
6334         if (intel_connector_init(connector) < 0) {
6335                 kfree(connector);
6336                 return NULL;
6337         }
6338
6339         return connector;
6340 }
6341
6342 /*
6343  * Free the bits allocated by intel_connector_alloc.
6344  * This should only be used after intel_connector_alloc has returned
6345  * successfully, and before drm_connector_init returns successfully.
6346  * Otherwise the destroy callbacks for the connector and the state should
6347  * take care of proper cleanup/free
6348  */
6349 void intel_connector_free(struct intel_connector *connector)
6350 {
6351         kfree(to_intel_digital_connector_state(connector->base.state));
6352         kfree(connector);
6353 }
6354
6355 /* Simple connector->get_hw_state implementation for encoders that support only
6356  * one connector and no cloning and hence the encoder state determines the state
6357  * of the connector. */
6358 bool intel_connector_get_hw_state(struct intel_connector *connector)
6359 {
6360         enum pipe pipe = 0;
6361         struct intel_encoder *encoder = connector->encoder;
6362
6363         return encoder->get_hw_state(encoder, &pipe);
6364 }
6365
6366 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6367 {
6368         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6369                 return crtc_state->fdi_lanes;
6370
6371         return 0;
6372 }
6373
6374 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6375                                      struct intel_crtc_state *pipe_config)
6376 {
6377         struct drm_i915_private *dev_priv = to_i915(dev);
6378         struct drm_atomic_state *state = pipe_config->base.state;
6379         struct intel_crtc *other_crtc;
6380         struct intel_crtc_state *other_crtc_state;
6381
6382         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6383                       pipe_name(pipe), pipe_config->fdi_lanes);
6384         if (pipe_config->fdi_lanes > 4) {
6385                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6386                               pipe_name(pipe), pipe_config->fdi_lanes);
6387                 return -EINVAL;
6388         }
6389
6390         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6391                 if (pipe_config->fdi_lanes > 2) {
6392                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6393                                       pipe_config->fdi_lanes);
6394                         return -EINVAL;
6395                 } else {
6396                         return 0;
6397                 }
6398         }
6399
6400         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6401                 return 0;
6402
6403         /* Ivybridge 3 pipe is really complicated */
6404         switch (pipe) {
6405         case PIPE_A:
6406                 return 0;
6407         case PIPE_B:
6408                 if (pipe_config->fdi_lanes <= 2)
6409                         return 0;
6410
6411                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6412                 other_crtc_state =
6413                         intel_atomic_get_crtc_state(state, other_crtc);
6414                 if (IS_ERR(other_crtc_state))
6415                         return PTR_ERR(other_crtc_state);
6416
6417                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6418                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6419                                       pipe_name(pipe), pipe_config->fdi_lanes);
6420                         return -EINVAL;
6421                 }
6422                 return 0;
6423         case PIPE_C:
6424                 if (pipe_config->fdi_lanes > 2) {
6425                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6426                                       pipe_name(pipe), pipe_config->fdi_lanes);
6427                         return -EINVAL;
6428                 }
6429
6430                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6431                 other_crtc_state =
6432                         intel_atomic_get_crtc_state(state, other_crtc);
6433                 if (IS_ERR(other_crtc_state))
6434                         return PTR_ERR(other_crtc_state);
6435
6436                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6437                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6438                         return -EINVAL;
6439                 }
6440                 return 0;
6441         default:
6442                 BUG();
6443         }
6444 }
6445
6446 #define RETRY 1
6447 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6448                                        struct intel_crtc_state *pipe_config)
6449 {
6450         struct drm_device *dev = intel_crtc->base.dev;
6451         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6452         int lane, link_bw, fdi_dotclock, ret;
6453         bool needs_recompute = false;
6454
6455 retry:
6456         /* FDI is a binary signal running at ~2.7GHz, encoding
6457          * each output octet as 10 bits. The actual frequency
6458          * is stored as a divider into a 100MHz clock, and the
6459          * mode pixel clock is stored in units of 1KHz.
6460          * Hence the bw of each lane in terms of the mode signal
6461          * is:
6462          */
6463         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6464
6465         fdi_dotclock = adjusted_mode->crtc_clock;
6466
6467         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6468                                            pipe_config->pipe_bpp);
6469
6470         pipe_config->fdi_lanes = lane;
6471
6472         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6473                                link_bw, &pipe_config->fdi_m_n, false);
6474
6475         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6476         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6477                 pipe_config->pipe_bpp -= 2*3;
6478                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6479                               pipe_config->pipe_bpp);
6480                 needs_recompute = true;
6481                 pipe_config->bw_constrained = true;
6482
6483                 goto retry;
6484         }
6485
6486         if (needs_recompute)
6487                 return RETRY;
6488
6489         return ret;
6490 }
6491
6492 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6493 {
6494         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6495         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6496
6497         /* IPS only exists on ULT machines and is tied to pipe A. */
6498         if (!hsw_crtc_supports_ips(crtc))
6499                 return false;
6500
6501         if (!i915_modparams.enable_ips)
6502                 return false;
6503
6504         if (crtc_state->pipe_bpp > 24)
6505                 return false;
6506
6507         /*
6508          * We compare against max which means we must take
6509          * the increased cdclk requirement into account when
6510          * calculating the new cdclk.
6511          *
6512          * Should measure whether using a lower cdclk w/o IPS
6513          */
6514         if (IS_BROADWELL(dev_priv) &&
6515             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6516                 return false;
6517
6518         return true;
6519 }
6520
6521 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6522 {
6523         struct drm_i915_private *dev_priv =
6524                 to_i915(crtc_state->base.crtc->dev);
6525         struct intel_atomic_state *intel_state =
6526                 to_intel_atomic_state(crtc_state->base.state);
6527
6528         if (!hsw_crtc_state_ips_capable(crtc_state))
6529                 return false;
6530
6531         if (crtc_state->ips_force_disable)
6532                 return false;
6533
6534         /* IPS should be fine as long as at least one plane is enabled. */
6535         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6536                 return false;
6537
6538         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6539         if (IS_BROADWELL(dev_priv) &&
6540             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6541                 return false;
6542
6543         return true;
6544 }
6545
6546 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6547 {
6548         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6549
6550         /* GDG double wide on either pipe, otherwise pipe A only */
6551         return INTEL_GEN(dev_priv) < 4 &&
6552                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6553 }
6554
6555 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6556 {
6557         uint32_t pixel_rate;
6558
6559         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6560
6561         /*
6562          * We only use IF-ID interlacing. If we ever use
6563          * PF-ID we'll need to adjust the pixel_rate here.
6564          */
6565
6566         if (pipe_config->pch_pfit.enabled) {
6567                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6568                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6569
6570                 pipe_w = pipe_config->pipe_src_w;
6571                 pipe_h = pipe_config->pipe_src_h;
6572
6573                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6574                 pfit_h = pfit_size & 0xFFFF;
6575                 if (pipe_w < pfit_w)
6576                         pipe_w = pfit_w;
6577                 if (pipe_h < pfit_h)
6578                         pipe_h = pfit_h;
6579
6580                 if (WARN_ON(!pfit_w || !pfit_h))
6581                         return pixel_rate;
6582
6583                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6584                                      pfit_w * pfit_h);
6585         }
6586
6587         return pixel_rate;
6588 }
6589
6590 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6591 {
6592         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6593
6594         if (HAS_GMCH_DISPLAY(dev_priv))
6595                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6596                 crtc_state->pixel_rate =
6597                         crtc_state->base.adjusted_mode.crtc_clock;
6598         else
6599                 crtc_state->pixel_rate =
6600                         ilk_pipe_pixel_rate(crtc_state);
6601 }
6602
6603 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6604                                      struct intel_crtc_state *pipe_config)
6605 {
6606         struct drm_device *dev = crtc->base.dev;
6607         struct drm_i915_private *dev_priv = to_i915(dev);
6608         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6609         int clock_limit = dev_priv->max_dotclk_freq;
6610
6611         if (INTEL_GEN(dev_priv) < 4) {
6612                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6613
6614                 /*
6615                  * Enable double wide mode when the dot clock
6616                  * is > 90% of the (display) core speed.
6617                  */
6618                 if (intel_crtc_supports_double_wide(crtc) &&
6619                     adjusted_mode->crtc_clock > clock_limit) {
6620                         clock_limit = dev_priv->max_dotclk_freq;
6621                         pipe_config->double_wide = true;
6622                 }
6623         }
6624
6625         if (adjusted_mode->crtc_clock > clock_limit) {
6626                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6627                               adjusted_mode->crtc_clock, clock_limit,
6628                               yesno(pipe_config->double_wide));
6629                 return -EINVAL;
6630         }
6631
6632         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6633                 /*
6634                  * There is only one pipe CSC unit per pipe, and we need that
6635                  * for output conversion from RGB->YCBCR. So if CTM is already
6636                  * applied we can't support YCBCR420 output.
6637                  */
6638                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6639                 return -EINVAL;
6640         }
6641
6642         /*
6643          * Pipe horizontal size must be even in:
6644          * - DVO ganged mode
6645          * - LVDS dual channel mode
6646          * - Double wide pipe
6647          */
6648         if (pipe_config->pipe_src_w & 1) {
6649                 if (pipe_config->double_wide) {
6650                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6651                         return -EINVAL;
6652                 }
6653
6654                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6655                     intel_is_dual_link_lvds(dev)) {
6656                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6657                         return -EINVAL;
6658                 }
6659         }
6660
6661         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6662          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6663          */
6664         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6665                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6666                 return -EINVAL;
6667
6668         intel_crtc_compute_pixel_rate(pipe_config);
6669
6670         if (pipe_config->has_pch_encoder)
6671                 return ironlake_fdi_compute_config(crtc, pipe_config);
6672
6673         return 0;
6674 }
6675
6676 static void
6677 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6678 {
6679         while (*num > DATA_LINK_M_N_MASK ||
6680                *den > DATA_LINK_M_N_MASK) {
6681                 *num >>= 1;
6682                 *den >>= 1;
6683         }
6684 }
6685
6686 static void compute_m_n(unsigned int m, unsigned int n,
6687                         uint32_t *ret_m, uint32_t *ret_n,
6688                         bool constant_n)
6689 {
6690         /*
6691          * Several DP dongles in particular seem to be fussy about
6692          * too large link M/N values. Give N value as 0x8000 that
6693          * should be acceptable by specific devices. 0x8000 is the
6694          * specified fixed N value for asynchronous clock mode,
6695          * which the devices expect also in synchronous clock mode.
6696          */
6697         if (constant_n)
6698                 *ret_n = 0x8000;
6699         else
6700                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6701
6702         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6703         intel_reduce_m_n_ratio(ret_m, ret_n);
6704 }
6705
6706 void
6707 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6708                        int pixel_clock, int link_clock,
6709                        struct intel_link_m_n *m_n,
6710                        bool constant_n)
6711 {
6712         m_n->tu = 64;
6713
6714         compute_m_n(bits_per_pixel * pixel_clock,
6715                     link_clock * nlanes * 8,
6716                     &m_n->gmch_m, &m_n->gmch_n,
6717                     constant_n);
6718
6719         compute_m_n(pixel_clock, link_clock,
6720                     &m_n->link_m, &m_n->link_n,
6721                     constant_n);
6722 }
6723
6724 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6725 {
6726         if (i915_modparams.panel_use_ssc >= 0)
6727                 return i915_modparams.panel_use_ssc != 0;
6728         return dev_priv->vbt.lvds_use_ssc
6729                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6730 }
6731
6732 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6733 {
6734         return (1 << dpll->n) << 16 | dpll->m2;
6735 }
6736
6737 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6738 {
6739         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6740 }
6741
6742 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6743                                      struct intel_crtc_state *crtc_state,
6744                                      struct dpll *reduced_clock)
6745 {
6746         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6747         u32 fp, fp2 = 0;
6748
6749         if (IS_PINEVIEW(dev_priv)) {
6750                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6751                 if (reduced_clock)
6752                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6753         } else {
6754                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6755                 if (reduced_clock)
6756                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6757         }
6758
6759         crtc_state->dpll_hw_state.fp0 = fp;
6760
6761         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6762             reduced_clock) {
6763                 crtc_state->dpll_hw_state.fp1 = fp2;
6764         } else {
6765                 crtc_state->dpll_hw_state.fp1 = fp;
6766         }
6767 }
6768
6769 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6770                 pipe)
6771 {
6772         u32 reg_val;
6773
6774         /*
6775          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6776          * and set it to a reasonable value instead.
6777          */
6778         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6779         reg_val &= 0xffffff00;
6780         reg_val |= 0x00000030;
6781         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6782
6783         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6784         reg_val &= 0x00ffffff;
6785         reg_val |= 0x8c000000;
6786         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6787
6788         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6789         reg_val &= 0xffffff00;
6790         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6791
6792         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6793         reg_val &= 0x00ffffff;
6794         reg_val |= 0xb0000000;
6795         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6796 }
6797
6798 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6799                                          struct intel_link_m_n *m_n)
6800 {
6801         struct drm_device *dev = crtc->base.dev;
6802         struct drm_i915_private *dev_priv = to_i915(dev);
6803         int pipe = crtc->pipe;
6804
6805         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6806         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6807         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6808         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6809 }
6810
6811 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6812                                          struct intel_link_m_n *m_n,
6813                                          struct intel_link_m_n *m2_n2)
6814 {
6815         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6816         int pipe = crtc->pipe;
6817         enum transcoder transcoder = crtc->config->cpu_transcoder;
6818
6819         if (INTEL_GEN(dev_priv) >= 5) {
6820                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6821                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6822                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6823                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6824                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6825                  * for gen < 8) and if DRRS is supported (to make sure the
6826                  * registers are not unnecessarily accessed).
6827                  */
6828                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6829                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6830                         I915_WRITE(PIPE_DATA_M2(transcoder),
6831                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6832                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6833                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6834                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6835                 }
6836         } else {
6837                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6838                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6839                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6840                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6841         }
6842 }
6843
6844 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6845 {
6846         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6847
6848         if (m_n == M1_N1) {
6849                 dp_m_n = &crtc->config->dp_m_n;
6850                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6851         } else if (m_n == M2_N2) {
6852
6853                 /*
6854                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6855                  * needs to be programmed into M1_N1.
6856                  */
6857                 dp_m_n = &crtc->config->dp_m2_n2;
6858         } else {
6859                 DRM_ERROR("Unsupported divider value\n");
6860                 return;
6861         }
6862
6863         if (crtc->config->has_pch_encoder)
6864                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6865         else
6866                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6867 }
6868
6869 static void vlv_compute_dpll(struct intel_crtc *crtc,
6870                              struct intel_crtc_state *pipe_config)
6871 {
6872         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6873                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6874         if (crtc->pipe != PIPE_A)
6875                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6876
6877         /* DPLL not used with DSI, but still need the rest set up */
6878         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6879                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6880                         DPLL_EXT_BUFFER_ENABLE_VLV;
6881
6882         pipe_config->dpll_hw_state.dpll_md =
6883                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6884 }
6885
6886 static void chv_compute_dpll(struct intel_crtc *crtc,
6887                              struct intel_crtc_state *pipe_config)
6888 {
6889         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6890                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6891         if (crtc->pipe != PIPE_A)
6892                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6893
6894         /* DPLL not used with DSI, but still need the rest set up */
6895         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6896                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6897
6898         pipe_config->dpll_hw_state.dpll_md =
6899                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6900 }
6901
6902 static void vlv_prepare_pll(struct intel_crtc *crtc,
6903                             const struct intel_crtc_state *pipe_config)
6904 {
6905         struct drm_device *dev = crtc->base.dev;
6906         struct drm_i915_private *dev_priv = to_i915(dev);
6907         enum pipe pipe = crtc->pipe;
6908         u32 mdiv;
6909         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6910         u32 coreclk, reg_val;
6911
6912         /* Enable Refclk */
6913         I915_WRITE(DPLL(pipe),
6914                    pipe_config->dpll_hw_state.dpll &
6915                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6916
6917         /* No need to actually set up the DPLL with DSI */
6918         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6919                 return;
6920
6921         mutex_lock(&dev_priv->sb_lock);
6922
6923         bestn = pipe_config->dpll.n;
6924         bestm1 = pipe_config->dpll.m1;
6925         bestm2 = pipe_config->dpll.m2;
6926         bestp1 = pipe_config->dpll.p1;
6927         bestp2 = pipe_config->dpll.p2;
6928
6929         /* See eDP HDMI DPIO driver vbios notes doc */
6930
6931         /* PLL B needs special handling */
6932         if (pipe == PIPE_B)
6933                 vlv_pllb_recal_opamp(dev_priv, pipe);
6934
6935         /* Set up Tx target for periodic Rcomp update */
6936         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6937
6938         /* Disable target IRef on PLL */
6939         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6940         reg_val &= 0x00ffffff;
6941         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6942
6943         /* Disable fast lock */
6944         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6945
6946         /* Set idtafcrecal before PLL is enabled */
6947         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6948         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6949         mdiv |= ((bestn << DPIO_N_SHIFT));
6950         mdiv |= (1 << DPIO_K_SHIFT);
6951
6952         /*
6953          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6954          * but we don't support that).
6955          * Note: don't use the DAC post divider as it seems unstable.
6956          */
6957         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6958         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6959
6960         mdiv |= DPIO_ENABLE_CALIBRATION;
6961         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6962
6963         /* Set HBR and RBR LPF coefficients */
6964         if (pipe_config->port_clock == 162000 ||
6965             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6966             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6967                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6968                                  0x009f0003);
6969         else
6970                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6971                                  0x00d0000f);
6972
6973         if (intel_crtc_has_dp_encoder(pipe_config)) {
6974                 /* Use SSC source */
6975                 if (pipe == PIPE_A)
6976                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6977                                          0x0df40000);
6978                 else
6979                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6980                                          0x0df70000);
6981         } else { /* HDMI or VGA */
6982                 /* Use bend source */
6983                 if (pipe == PIPE_A)
6984                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6985                                          0x0df70000);
6986                 else
6987                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6988                                          0x0df40000);
6989         }
6990
6991         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6992         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6993         if (intel_crtc_has_dp_encoder(crtc->config))
6994                 coreclk |= 0x01000000;
6995         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6996
6997         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6998         mutex_unlock(&dev_priv->sb_lock);
6999 }
7000
7001 static void chv_prepare_pll(struct intel_crtc *crtc,
7002                             const struct intel_crtc_state *pipe_config)
7003 {
7004         struct drm_device *dev = crtc->base.dev;
7005         struct drm_i915_private *dev_priv = to_i915(dev);
7006         enum pipe pipe = crtc->pipe;
7007         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7008         u32 loopfilter, tribuf_calcntr;
7009         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7010         u32 dpio_val;
7011         int vco;
7012
7013         /* Enable Refclk and SSC */
7014         I915_WRITE(DPLL(pipe),
7015                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7016
7017         /* No need to actually set up the DPLL with DSI */
7018         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7019                 return;
7020
7021         bestn = pipe_config->dpll.n;
7022         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7023         bestm1 = pipe_config->dpll.m1;
7024         bestm2 = pipe_config->dpll.m2 >> 22;
7025         bestp1 = pipe_config->dpll.p1;
7026         bestp2 = pipe_config->dpll.p2;
7027         vco = pipe_config->dpll.vco;
7028         dpio_val = 0;
7029         loopfilter = 0;
7030
7031         mutex_lock(&dev_priv->sb_lock);
7032
7033         /* p1 and p2 divider */
7034         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7035                         5 << DPIO_CHV_S1_DIV_SHIFT |
7036                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7037                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7038                         1 << DPIO_CHV_K_DIV_SHIFT);
7039
7040         /* Feedback post-divider - m2 */
7041         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7042
7043         /* Feedback refclk divider - n and m1 */
7044         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7045                         DPIO_CHV_M1_DIV_BY_2 |
7046                         1 << DPIO_CHV_N_DIV_SHIFT);
7047
7048         /* M2 fraction division */
7049         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7050
7051         /* M2 fraction division enable */
7052         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7053         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7054         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7055         if (bestm2_frac)
7056                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7057         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7058
7059         /* Program digital lock detect threshold */
7060         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7061         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7062                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7063         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7064         if (!bestm2_frac)
7065                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7066         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7067
7068         /* Loop filter */
7069         if (vco == 5400000) {
7070                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7071                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7072                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7073                 tribuf_calcntr = 0x9;
7074         } else if (vco <= 6200000) {
7075                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7076                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7077                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7078                 tribuf_calcntr = 0x9;
7079         } else if (vco <= 6480000) {
7080                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7081                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7082                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7083                 tribuf_calcntr = 0x8;
7084         } else {
7085                 /* Not supported. Apply the same limits as in the max case */
7086                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7087                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7088                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7089                 tribuf_calcntr = 0;
7090         }
7091         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7092
7093         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7094         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7095         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7096         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7097
7098         /* AFC Recal */
7099         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7100                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7101                         DPIO_AFC_RECAL);
7102
7103         mutex_unlock(&dev_priv->sb_lock);
7104 }
7105
7106 /**
7107  * vlv_force_pll_on - forcibly enable just the PLL
7108  * @dev_priv: i915 private structure
7109  * @pipe: pipe PLL to enable
7110  * @dpll: PLL configuration
7111  *
7112  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7113  * in cases where we need the PLL enabled even when @pipe is not going to
7114  * be enabled.
7115  */
7116 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7117                      const struct dpll *dpll)
7118 {
7119         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7120         struct intel_crtc_state *pipe_config;
7121
7122         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7123         if (!pipe_config)
7124                 return -ENOMEM;
7125
7126         pipe_config->base.crtc = &crtc->base;
7127         pipe_config->pixel_multiplier = 1;
7128         pipe_config->dpll = *dpll;
7129
7130         if (IS_CHERRYVIEW(dev_priv)) {
7131                 chv_compute_dpll(crtc, pipe_config);
7132                 chv_prepare_pll(crtc, pipe_config);
7133                 chv_enable_pll(crtc, pipe_config);
7134         } else {
7135                 vlv_compute_dpll(crtc, pipe_config);
7136                 vlv_prepare_pll(crtc, pipe_config);
7137                 vlv_enable_pll(crtc, pipe_config);
7138         }
7139
7140         kfree(pipe_config);
7141
7142         return 0;
7143 }
7144
7145 /**
7146  * vlv_force_pll_off - forcibly disable just the PLL
7147  * @dev_priv: i915 private structure
7148  * @pipe: pipe PLL to disable
7149  *
7150  * Disable the PLL for @pipe. To be used in cases where we need
7151  * the PLL enabled even when @pipe is not going to be enabled.
7152  */
7153 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7154 {
7155         if (IS_CHERRYVIEW(dev_priv))
7156                 chv_disable_pll(dev_priv, pipe);
7157         else
7158                 vlv_disable_pll(dev_priv, pipe);
7159 }
7160
7161 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7162                               struct intel_crtc_state *crtc_state,
7163                               struct dpll *reduced_clock)
7164 {
7165         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7166         u32 dpll;
7167         struct dpll *clock = &crtc_state->dpll;
7168
7169         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7170
7171         dpll = DPLL_VGA_MODE_DIS;
7172
7173         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7174                 dpll |= DPLLB_MODE_LVDS;
7175         else
7176                 dpll |= DPLLB_MODE_DAC_SERIAL;
7177
7178         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7179             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7180                 dpll |= (crtc_state->pixel_multiplier - 1)
7181                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7182         }
7183
7184         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7185             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7186                 dpll |= DPLL_SDVO_HIGH_SPEED;
7187
7188         if (intel_crtc_has_dp_encoder(crtc_state))
7189                 dpll |= DPLL_SDVO_HIGH_SPEED;
7190
7191         /* compute bitmask from p1 value */
7192         if (IS_PINEVIEW(dev_priv))
7193                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7194         else {
7195                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7196                 if (IS_G4X(dev_priv) && reduced_clock)
7197                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7198         }
7199         switch (clock->p2) {
7200         case 5:
7201                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7202                 break;
7203         case 7:
7204                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7205                 break;
7206         case 10:
7207                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7208                 break;
7209         case 14:
7210                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7211                 break;
7212         }
7213         if (INTEL_GEN(dev_priv) >= 4)
7214                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7215
7216         if (crtc_state->sdvo_tv_clock)
7217                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7218         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7219                  intel_panel_use_ssc(dev_priv))
7220                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7221         else
7222                 dpll |= PLL_REF_INPUT_DREFCLK;
7223
7224         dpll |= DPLL_VCO_ENABLE;
7225         crtc_state->dpll_hw_state.dpll = dpll;
7226
7227         if (INTEL_GEN(dev_priv) >= 4) {
7228                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7229                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7230                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7231         }
7232 }
7233
7234 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7235                               struct intel_crtc_state *crtc_state,
7236                               struct dpll *reduced_clock)
7237 {
7238         struct drm_device *dev = crtc->base.dev;
7239         struct drm_i915_private *dev_priv = to_i915(dev);
7240         u32 dpll;
7241         struct dpll *clock = &crtc_state->dpll;
7242
7243         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7244
7245         dpll = DPLL_VGA_MODE_DIS;
7246
7247         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7248                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7249         } else {
7250                 if (clock->p1 == 2)
7251                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7252                 else
7253                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7254                 if (clock->p2 == 4)
7255                         dpll |= PLL_P2_DIVIDE_BY_4;
7256         }
7257
7258         if (!IS_I830(dev_priv) &&
7259             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7260                 dpll |= DPLL_DVO_2X_MODE;
7261
7262         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7263             intel_panel_use_ssc(dev_priv))
7264                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7265         else
7266                 dpll |= PLL_REF_INPUT_DREFCLK;
7267
7268         dpll |= DPLL_VCO_ENABLE;
7269         crtc_state->dpll_hw_state.dpll = dpll;
7270 }
7271
7272 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7273 {
7274         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7275         enum pipe pipe = intel_crtc->pipe;
7276         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7277         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7278         uint32_t crtc_vtotal, crtc_vblank_end;
7279         int vsyncshift = 0;
7280
7281         /* We need to be careful not to changed the adjusted mode, for otherwise
7282          * the hw state checker will get angry at the mismatch. */
7283         crtc_vtotal = adjusted_mode->crtc_vtotal;
7284         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7285
7286         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7287                 /* the chip adds 2 halflines automatically */
7288                 crtc_vtotal -= 1;
7289                 crtc_vblank_end -= 1;
7290
7291                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7292                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7293                 else
7294                         vsyncshift = adjusted_mode->crtc_hsync_start -
7295                                 adjusted_mode->crtc_htotal / 2;
7296                 if (vsyncshift < 0)
7297                         vsyncshift += adjusted_mode->crtc_htotal;
7298         }
7299
7300         if (INTEL_GEN(dev_priv) > 3)
7301                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7302
7303         I915_WRITE(HTOTAL(cpu_transcoder),
7304                    (adjusted_mode->crtc_hdisplay - 1) |
7305                    ((adjusted_mode->crtc_htotal - 1) << 16));
7306         I915_WRITE(HBLANK(cpu_transcoder),
7307                    (adjusted_mode->crtc_hblank_start - 1) |
7308                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7309         I915_WRITE(HSYNC(cpu_transcoder),
7310                    (adjusted_mode->crtc_hsync_start - 1) |
7311                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7312
7313         I915_WRITE(VTOTAL(cpu_transcoder),
7314                    (adjusted_mode->crtc_vdisplay - 1) |
7315                    ((crtc_vtotal - 1) << 16));
7316         I915_WRITE(VBLANK(cpu_transcoder),
7317                    (adjusted_mode->crtc_vblank_start - 1) |
7318                    ((crtc_vblank_end - 1) << 16));
7319         I915_WRITE(VSYNC(cpu_transcoder),
7320                    (adjusted_mode->crtc_vsync_start - 1) |
7321                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7322
7323         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7324          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7325          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7326          * bits. */
7327         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7328             (pipe == PIPE_B || pipe == PIPE_C))
7329                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7330
7331 }
7332
7333 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7334 {
7335         struct drm_device *dev = intel_crtc->base.dev;
7336         struct drm_i915_private *dev_priv = to_i915(dev);
7337         enum pipe pipe = intel_crtc->pipe;
7338
7339         /* pipesrc controls the size that is scaled from, which should
7340          * always be the user's requested size.
7341          */
7342         I915_WRITE(PIPESRC(pipe),
7343                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7344                    (intel_crtc->config->pipe_src_h - 1));
7345 }
7346
7347 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7348                                    struct intel_crtc_state *pipe_config)
7349 {
7350         struct drm_device *dev = crtc->base.dev;
7351         struct drm_i915_private *dev_priv = to_i915(dev);
7352         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7353         uint32_t tmp;
7354
7355         tmp = I915_READ(HTOTAL(cpu_transcoder));
7356         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7357         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7358         tmp = I915_READ(HBLANK(cpu_transcoder));
7359         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7360         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7361         tmp = I915_READ(HSYNC(cpu_transcoder));
7362         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7363         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7364
7365         tmp = I915_READ(VTOTAL(cpu_transcoder));
7366         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7367         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7368         tmp = I915_READ(VBLANK(cpu_transcoder));
7369         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7370         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7371         tmp = I915_READ(VSYNC(cpu_transcoder));
7372         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7373         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7374
7375         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7376                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7377                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7378                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7379         }
7380 }
7381
7382 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7383                                     struct intel_crtc_state *pipe_config)
7384 {
7385         struct drm_device *dev = crtc->base.dev;
7386         struct drm_i915_private *dev_priv = to_i915(dev);
7387         u32 tmp;
7388
7389         tmp = I915_READ(PIPESRC(crtc->pipe));
7390         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7391         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7392
7393         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7394         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7395 }
7396
7397 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7398                                  struct intel_crtc_state *pipe_config)
7399 {
7400         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7401         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7402         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7403         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7404
7405         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7406         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7407         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7408         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7409
7410         mode->flags = pipe_config->base.adjusted_mode.flags;
7411         mode->type = DRM_MODE_TYPE_DRIVER;
7412
7413         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7414
7415         mode->hsync = drm_mode_hsync(mode);
7416         mode->vrefresh = drm_mode_vrefresh(mode);
7417         drm_mode_set_name(mode);
7418 }
7419
7420 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7421 {
7422         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7423         uint32_t pipeconf;
7424
7425         pipeconf = 0;
7426
7427         /* we keep both pipes enabled on 830 */
7428         if (IS_I830(dev_priv))
7429                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7430
7431         if (intel_crtc->config->double_wide)
7432                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7433
7434         /* only g4x and later have fancy bpc/dither controls */
7435         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7436             IS_CHERRYVIEW(dev_priv)) {
7437                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7438                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7439                         pipeconf |= PIPECONF_DITHER_EN |
7440                                     PIPECONF_DITHER_TYPE_SP;
7441
7442                 switch (intel_crtc->config->pipe_bpp) {
7443                 case 18:
7444                         pipeconf |= PIPECONF_6BPC;
7445                         break;
7446                 case 24:
7447                         pipeconf |= PIPECONF_8BPC;
7448                         break;
7449                 case 30:
7450                         pipeconf |= PIPECONF_10BPC;
7451                         break;
7452                 default:
7453                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7454                         BUG();
7455                 }
7456         }
7457
7458         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7459                 if (INTEL_GEN(dev_priv) < 4 ||
7460                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7461                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7462                 else
7463                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7464         } else
7465                 pipeconf |= PIPECONF_PROGRESSIVE;
7466
7467         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7468              intel_crtc->config->limited_color_range)
7469                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7470
7471         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7472         POSTING_READ(PIPECONF(intel_crtc->pipe));
7473 }
7474
7475 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7476                                    struct intel_crtc_state *crtc_state)
7477 {
7478         struct drm_device *dev = crtc->base.dev;
7479         struct drm_i915_private *dev_priv = to_i915(dev);
7480         const struct intel_limit *limit;
7481         int refclk = 48000;
7482
7483         memset(&crtc_state->dpll_hw_state, 0,
7484                sizeof(crtc_state->dpll_hw_state));
7485
7486         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7487                 if (intel_panel_use_ssc(dev_priv)) {
7488                         refclk = dev_priv->vbt.lvds_ssc_freq;
7489                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7490                 }
7491
7492                 limit = &intel_limits_i8xx_lvds;
7493         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7494                 limit = &intel_limits_i8xx_dvo;
7495         } else {
7496                 limit = &intel_limits_i8xx_dac;
7497         }
7498
7499         if (!crtc_state->clock_set &&
7500             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7501                                  refclk, NULL, &crtc_state->dpll)) {
7502                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7503                 return -EINVAL;
7504         }
7505
7506         i8xx_compute_dpll(crtc, crtc_state, NULL);
7507
7508         return 0;
7509 }
7510
7511 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7512                                   struct intel_crtc_state *crtc_state)
7513 {
7514         struct drm_device *dev = crtc->base.dev;
7515         struct drm_i915_private *dev_priv = to_i915(dev);
7516         const struct intel_limit *limit;
7517         int refclk = 96000;
7518
7519         memset(&crtc_state->dpll_hw_state, 0,
7520                sizeof(crtc_state->dpll_hw_state));
7521
7522         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7523                 if (intel_panel_use_ssc(dev_priv)) {
7524                         refclk = dev_priv->vbt.lvds_ssc_freq;
7525                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7526                 }
7527
7528                 if (intel_is_dual_link_lvds(dev))
7529                         limit = &intel_limits_g4x_dual_channel_lvds;
7530                 else
7531                         limit = &intel_limits_g4x_single_channel_lvds;
7532         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7533                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7534                 limit = &intel_limits_g4x_hdmi;
7535         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7536                 limit = &intel_limits_g4x_sdvo;
7537         } else {
7538                 /* The option is for other outputs */
7539                 limit = &intel_limits_i9xx_sdvo;
7540         }
7541
7542         if (!crtc_state->clock_set &&
7543             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7544                                 refclk, NULL, &crtc_state->dpll)) {
7545                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7546                 return -EINVAL;
7547         }
7548
7549         i9xx_compute_dpll(crtc, crtc_state, NULL);
7550
7551         return 0;
7552 }
7553
7554 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7555                                   struct intel_crtc_state *crtc_state)
7556 {
7557         struct drm_device *dev = crtc->base.dev;
7558         struct drm_i915_private *dev_priv = to_i915(dev);
7559         const struct intel_limit *limit;
7560         int refclk = 96000;
7561
7562         memset(&crtc_state->dpll_hw_state, 0,
7563                sizeof(crtc_state->dpll_hw_state));
7564
7565         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7566                 if (intel_panel_use_ssc(dev_priv)) {
7567                         refclk = dev_priv->vbt.lvds_ssc_freq;
7568                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7569                 }
7570
7571                 limit = &intel_limits_pineview_lvds;
7572         } else {
7573                 limit = &intel_limits_pineview_sdvo;
7574         }
7575
7576         if (!crtc_state->clock_set &&
7577             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7578                                 refclk, NULL, &crtc_state->dpll)) {
7579                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7580                 return -EINVAL;
7581         }
7582
7583         i9xx_compute_dpll(crtc, crtc_state, NULL);
7584
7585         return 0;
7586 }
7587
7588 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7589                                    struct intel_crtc_state *crtc_state)
7590 {
7591         struct drm_device *dev = crtc->base.dev;
7592         struct drm_i915_private *dev_priv = to_i915(dev);
7593         const struct intel_limit *limit;
7594         int refclk = 96000;
7595
7596         memset(&crtc_state->dpll_hw_state, 0,
7597                sizeof(crtc_state->dpll_hw_state));
7598
7599         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7600                 if (intel_panel_use_ssc(dev_priv)) {
7601                         refclk = dev_priv->vbt.lvds_ssc_freq;
7602                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7603                 }
7604
7605                 limit = &intel_limits_i9xx_lvds;
7606         } else {
7607                 limit = &intel_limits_i9xx_sdvo;
7608         }
7609
7610         if (!crtc_state->clock_set &&
7611             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7612                                  refclk, NULL, &crtc_state->dpll)) {
7613                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7614                 return -EINVAL;
7615         }
7616
7617         i9xx_compute_dpll(crtc, crtc_state, NULL);
7618
7619         return 0;
7620 }
7621
7622 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7623                                   struct intel_crtc_state *crtc_state)
7624 {
7625         int refclk = 100000;
7626         const struct intel_limit *limit = &intel_limits_chv;
7627
7628         memset(&crtc_state->dpll_hw_state, 0,
7629                sizeof(crtc_state->dpll_hw_state));
7630
7631         if (!crtc_state->clock_set &&
7632             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7633                                 refclk, NULL, &crtc_state->dpll)) {
7634                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7635                 return -EINVAL;
7636         }
7637
7638         chv_compute_dpll(crtc, crtc_state);
7639
7640         return 0;
7641 }
7642
7643 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7644                                   struct intel_crtc_state *crtc_state)
7645 {
7646         int refclk = 100000;
7647         const struct intel_limit *limit = &intel_limits_vlv;
7648
7649         memset(&crtc_state->dpll_hw_state, 0,
7650                sizeof(crtc_state->dpll_hw_state));
7651
7652         if (!crtc_state->clock_set &&
7653             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7654                                 refclk, NULL, &crtc_state->dpll)) {
7655                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7656                 return -EINVAL;
7657         }
7658
7659         vlv_compute_dpll(crtc, crtc_state);
7660
7661         return 0;
7662 }
7663
7664 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7665                                  struct intel_crtc_state *pipe_config)
7666 {
7667         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7668         uint32_t tmp;
7669
7670         if (INTEL_GEN(dev_priv) <= 3 &&
7671             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7672                 return;
7673
7674         tmp = I915_READ(PFIT_CONTROL);
7675         if (!(tmp & PFIT_ENABLE))
7676                 return;
7677
7678         /* Check whether the pfit is attached to our pipe. */
7679         if (INTEL_GEN(dev_priv) < 4) {
7680                 if (crtc->pipe != PIPE_B)
7681                         return;
7682         } else {
7683                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7684                         return;
7685         }
7686
7687         pipe_config->gmch_pfit.control = tmp;
7688         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7689 }
7690
7691 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7692                                struct intel_crtc_state *pipe_config)
7693 {
7694         struct drm_device *dev = crtc->base.dev;
7695         struct drm_i915_private *dev_priv = to_i915(dev);
7696         int pipe = pipe_config->cpu_transcoder;
7697         struct dpll clock;
7698         u32 mdiv;
7699         int refclk = 100000;
7700
7701         /* In case of DSI, DPLL will not be used */
7702         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7703                 return;
7704
7705         mutex_lock(&dev_priv->sb_lock);
7706         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7707         mutex_unlock(&dev_priv->sb_lock);
7708
7709         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7710         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7711         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7712         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7713         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7714
7715         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7716 }
7717
7718 static void
7719 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7720                               struct intel_initial_plane_config *plane_config)
7721 {
7722         struct drm_device *dev = crtc->base.dev;
7723         struct drm_i915_private *dev_priv = to_i915(dev);
7724         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7725         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7726         enum pipe pipe;
7727         u32 val, base, offset;
7728         int fourcc, pixel_format;
7729         unsigned int aligned_height;
7730         struct drm_framebuffer *fb;
7731         struct intel_framebuffer *intel_fb;
7732
7733         if (!plane->get_hw_state(plane, &pipe))
7734                 return;
7735
7736         WARN_ON(pipe != crtc->pipe);
7737
7738         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7739         if (!intel_fb) {
7740                 DRM_DEBUG_KMS("failed to alloc fb\n");
7741                 return;
7742         }
7743
7744         fb = &intel_fb->base;
7745
7746         fb->dev = dev;
7747
7748         val = I915_READ(DSPCNTR(i9xx_plane));
7749
7750         if (INTEL_GEN(dev_priv) >= 4) {
7751                 if (val & DISPPLANE_TILED) {
7752                         plane_config->tiling = I915_TILING_X;
7753                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7754                 }
7755         }
7756
7757         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7758         fourcc = i9xx_format_to_fourcc(pixel_format);
7759         fb->format = drm_format_info(fourcc);
7760
7761         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7762                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7763                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7764         } else if (INTEL_GEN(dev_priv) >= 4) {
7765                 if (plane_config->tiling)
7766                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7767                 else
7768                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7769                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7770         } else {
7771                 base = I915_READ(DSPADDR(i9xx_plane));
7772         }
7773         plane_config->base = base;
7774
7775         val = I915_READ(PIPESRC(pipe));
7776         fb->width = ((val >> 16) & 0xfff) + 1;
7777         fb->height = ((val >> 0) & 0xfff) + 1;
7778
7779         val = I915_READ(DSPSTRIDE(i9xx_plane));
7780         fb->pitches[0] = val & 0xffffffc0;
7781
7782         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7783
7784         plane_config->size = fb->pitches[0] * aligned_height;
7785
7786         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7787                       crtc->base.name, plane->base.name, fb->width, fb->height,
7788                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7789                       plane_config->size);
7790
7791         plane_config->fb = intel_fb;
7792 }
7793
7794 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7795                                struct intel_crtc_state *pipe_config)
7796 {
7797         struct drm_device *dev = crtc->base.dev;
7798         struct drm_i915_private *dev_priv = to_i915(dev);
7799         int pipe = pipe_config->cpu_transcoder;
7800         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7801         struct dpll clock;
7802         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7803         int refclk = 100000;
7804
7805         /* In case of DSI, DPLL will not be used */
7806         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7807                 return;
7808
7809         mutex_lock(&dev_priv->sb_lock);
7810         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7811         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7812         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7813         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7814         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7815         mutex_unlock(&dev_priv->sb_lock);
7816
7817         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7818         clock.m2 = (pll_dw0 & 0xff) << 22;
7819         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7820                 clock.m2 |= pll_dw2 & 0x3fffff;
7821         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7822         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7823         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7824
7825         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7826 }
7827
7828 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7829                                  struct intel_crtc_state *pipe_config)
7830 {
7831         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7832         enum intel_display_power_domain power_domain;
7833         uint32_t tmp;
7834         bool ret;
7835
7836         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7837         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7838                 return false;
7839
7840         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7841         pipe_config->shared_dpll = NULL;
7842
7843         ret = false;
7844
7845         tmp = I915_READ(PIPECONF(crtc->pipe));
7846         if (!(tmp & PIPECONF_ENABLE))
7847                 goto out;
7848
7849         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7850             IS_CHERRYVIEW(dev_priv)) {
7851                 switch (tmp & PIPECONF_BPC_MASK) {
7852                 case PIPECONF_6BPC:
7853                         pipe_config->pipe_bpp = 18;
7854                         break;
7855                 case PIPECONF_8BPC:
7856                         pipe_config->pipe_bpp = 24;
7857                         break;
7858                 case PIPECONF_10BPC:
7859                         pipe_config->pipe_bpp = 30;
7860                         break;
7861                 default:
7862                         break;
7863                 }
7864         }
7865
7866         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7867             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7868                 pipe_config->limited_color_range = true;
7869
7870         if (INTEL_GEN(dev_priv) < 4)
7871                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7872
7873         intel_get_pipe_timings(crtc, pipe_config);
7874         intel_get_pipe_src_size(crtc, pipe_config);
7875
7876         i9xx_get_pfit_config(crtc, pipe_config);
7877
7878         if (INTEL_GEN(dev_priv) >= 4) {
7879                 /* No way to read it out on pipes B and C */
7880                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7881                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7882                 else
7883                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7884                 pipe_config->pixel_multiplier =
7885                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7886                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7887                 pipe_config->dpll_hw_state.dpll_md = tmp;
7888         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7889                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7890                 tmp = I915_READ(DPLL(crtc->pipe));
7891                 pipe_config->pixel_multiplier =
7892                         ((tmp & SDVO_MULTIPLIER_MASK)
7893                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7894         } else {
7895                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7896                  * port and will be fixed up in the encoder->get_config
7897                  * function. */
7898                 pipe_config->pixel_multiplier = 1;
7899         }
7900         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7901         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7902                 /*
7903                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7904                  * on 830. Filter it out here so that we don't
7905                  * report errors due to that.
7906                  */
7907                 if (IS_I830(dev_priv))
7908                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7909
7910                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7911                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7912         } else {
7913                 /* Mask out read-only status bits. */
7914                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7915                                                      DPLL_PORTC_READY_MASK |
7916                                                      DPLL_PORTB_READY_MASK);
7917         }
7918
7919         if (IS_CHERRYVIEW(dev_priv))
7920                 chv_crtc_clock_get(crtc, pipe_config);
7921         else if (IS_VALLEYVIEW(dev_priv))
7922                 vlv_crtc_clock_get(crtc, pipe_config);
7923         else
7924                 i9xx_crtc_clock_get(crtc, pipe_config);
7925
7926         /*
7927          * Normally the dotclock is filled in by the encoder .get_config()
7928          * but in case the pipe is enabled w/o any ports we need a sane
7929          * default.
7930          */
7931         pipe_config->base.adjusted_mode.crtc_clock =
7932                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7933
7934         ret = true;
7935
7936 out:
7937         intel_display_power_put(dev_priv, power_domain);
7938
7939         return ret;
7940 }
7941
7942 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7943 {
7944         struct intel_encoder *encoder;
7945         int i;
7946         u32 val, final;
7947         bool has_lvds = false;
7948         bool has_cpu_edp = false;
7949         bool has_panel = false;
7950         bool has_ck505 = false;
7951         bool can_ssc = false;
7952         bool using_ssc_source = false;
7953
7954         /* We need to take the global config into account */
7955         for_each_intel_encoder(&dev_priv->drm, encoder) {
7956                 switch (encoder->type) {
7957                 case INTEL_OUTPUT_LVDS:
7958                         has_panel = true;
7959                         has_lvds = true;
7960                         break;
7961                 case INTEL_OUTPUT_EDP:
7962                         has_panel = true;
7963                         if (encoder->port == PORT_A)
7964                                 has_cpu_edp = true;
7965                         break;
7966                 default:
7967                         break;
7968                 }
7969         }
7970
7971         if (HAS_PCH_IBX(dev_priv)) {
7972                 has_ck505 = dev_priv->vbt.display_clock_mode;
7973                 can_ssc = has_ck505;
7974         } else {
7975                 has_ck505 = false;
7976                 can_ssc = true;
7977         }
7978
7979         /* Check if any DPLLs are using the SSC source */
7980         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7981                 u32 temp = I915_READ(PCH_DPLL(i));
7982
7983                 if (!(temp & DPLL_VCO_ENABLE))
7984                         continue;
7985
7986                 if ((temp & PLL_REF_INPUT_MASK) ==
7987                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7988                         using_ssc_source = true;
7989                         break;
7990                 }
7991         }
7992
7993         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7994                       has_panel, has_lvds, has_ck505, using_ssc_source);
7995
7996         /* Ironlake: try to setup display ref clock before DPLL
7997          * enabling. This is only under driver's control after
7998          * PCH B stepping, previous chipset stepping should be
7999          * ignoring this setting.
8000          */
8001         val = I915_READ(PCH_DREF_CONTROL);
8002
8003         /* As we must carefully and slowly disable/enable each source in turn,
8004          * compute the final state we want first and check if we need to
8005          * make any changes at all.
8006          */
8007         final = val;
8008         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8009         if (has_ck505)
8010                 final |= DREF_NONSPREAD_CK505_ENABLE;
8011         else
8012                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8013
8014         final &= ~DREF_SSC_SOURCE_MASK;
8015         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8016         final &= ~DREF_SSC1_ENABLE;
8017
8018         if (has_panel) {
8019                 final |= DREF_SSC_SOURCE_ENABLE;
8020
8021                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8022                         final |= DREF_SSC1_ENABLE;
8023
8024                 if (has_cpu_edp) {
8025                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8026                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8027                         else
8028                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8029                 } else
8030                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8031         } else if (using_ssc_source) {
8032                 final |= DREF_SSC_SOURCE_ENABLE;
8033                 final |= DREF_SSC1_ENABLE;
8034         }
8035
8036         if (final == val)
8037                 return;
8038
8039         /* Always enable nonspread source */
8040         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8041
8042         if (has_ck505)
8043                 val |= DREF_NONSPREAD_CK505_ENABLE;
8044         else
8045                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8046
8047         if (has_panel) {
8048                 val &= ~DREF_SSC_SOURCE_MASK;
8049                 val |= DREF_SSC_SOURCE_ENABLE;
8050
8051                 /* SSC must be turned on before enabling the CPU output  */
8052                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8053                         DRM_DEBUG_KMS("Using SSC on panel\n");
8054                         val |= DREF_SSC1_ENABLE;
8055                 } else
8056                         val &= ~DREF_SSC1_ENABLE;
8057
8058                 /* Get SSC going before enabling the outputs */
8059                 I915_WRITE(PCH_DREF_CONTROL, val);
8060                 POSTING_READ(PCH_DREF_CONTROL);
8061                 udelay(200);
8062
8063                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8064
8065                 /* Enable CPU source on CPU attached eDP */
8066                 if (has_cpu_edp) {
8067                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8068                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8069                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8070                         } else
8071                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8072                 } else
8073                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8074
8075                 I915_WRITE(PCH_DREF_CONTROL, val);
8076                 POSTING_READ(PCH_DREF_CONTROL);
8077                 udelay(200);
8078         } else {
8079                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8080
8081                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8082
8083                 /* Turn off CPU output */
8084                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8085
8086                 I915_WRITE(PCH_DREF_CONTROL, val);
8087                 POSTING_READ(PCH_DREF_CONTROL);
8088                 udelay(200);
8089
8090                 if (!using_ssc_source) {
8091                         DRM_DEBUG_KMS("Disabling SSC source\n");
8092
8093                         /* Turn off the SSC source */
8094                         val &= ~DREF_SSC_SOURCE_MASK;
8095                         val |= DREF_SSC_SOURCE_DISABLE;
8096
8097                         /* Turn off SSC1 */
8098                         val &= ~DREF_SSC1_ENABLE;
8099
8100                         I915_WRITE(PCH_DREF_CONTROL, val);
8101                         POSTING_READ(PCH_DREF_CONTROL);
8102                         udelay(200);
8103                 }
8104         }
8105
8106         BUG_ON(val != final);
8107 }
8108
8109 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8110 {
8111         uint32_t tmp;
8112
8113         tmp = I915_READ(SOUTH_CHICKEN2);
8114         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8115         I915_WRITE(SOUTH_CHICKEN2, tmp);
8116
8117         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8118                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8119                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8120
8121         tmp = I915_READ(SOUTH_CHICKEN2);
8122         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8123         I915_WRITE(SOUTH_CHICKEN2, tmp);
8124
8125         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8126                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8127                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8128 }
8129
8130 /* WaMPhyProgramming:hsw */
8131 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8132 {
8133         uint32_t tmp;
8134
8135         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8136         tmp &= ~(0xFF << 24);
8137         tmp |= (0x12 << 24);
8138         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8139
8140         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8141         tmp |= (1 << 11);
8142         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8143
8144         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8145         tmp |= (1 << 11);
8146         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8147
8148         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8149         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8150         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8151
8152         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8153         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8154         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8155
8156         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8157         tmp &= ~(7 << 13);
8158         tmp |= (5 << 13);
8159         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8160
8161         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8162         tmp &= ~(7 << 13);
8163         tmp |= (5 << 13);
8164         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8165
8166         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8167         tmp &= ~0xFF;
8168         tmp |= 0x1C;
8169         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8170
8171         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8172         tmp &= ~0xFF;
8173         tmp |= 0x1C;
8174         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8175
8176         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8177         tmp &= ~(0xFF << 16);
8178         tmp |= (0x1C << 16);
8179         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8180
8181         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8182         tmp &= ~(0xFF << 16);
8183         tmp |= (0x1C << 16);
8184         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8185
8186         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8187         tmp |= (1 << 27);
8188         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8189
8190         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8191         tmp |= (1 << 27);
8192         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8193
8194         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8195         tmp &= ~(0xF << 28);
8196         tmp |= (4 << 28);
8197         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8198
8199         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8200         tmp &= ~(0xF << 28);
8201         tmp |= (4 << 28);
8202         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8203 }
8204
8205 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8206  * Programming" based on the parameters passed:
8207  * - Sequence to enable CLKOUT_DP
8208  * - Sequence to enable CLKOUT_DP without spread
8209  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8210  */
8211 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8212                                  bool with_spread, bool with_fdi)
8213 {
8214         uint32_t reg, tmp;
8215
8216         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8217                 with_spread = true;
8218         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8219             with_fdi, "LP PCH doesn't have FDI\n"))
8220                 with_fdi = false;
8221
8222         mutex_lock(&dev_priv->sb_lock);
8223
8224         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8225         tmp &= ~SBI_SSCCTL_DISABLE;
8226         tmp |= SBI_SSCCTL_PATHALT;
8227         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8228
8229         udelay(24);
8230
8231         if (with_spread) {
8232                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8233                 tmp &= ~SBI_SSCCTL_PATHALT;
8234                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8235
8236                 if (with_fdi) {
8237                         lpt_reset_fdi_mphy(dev_priv);
8238                         lpt_program_fdi_mphy(dev_priv);
8239                 }
8240         }
8241
8242         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8243         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8244         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8245         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8246
8247         mutex_unlock(&dev_priv->sb_lock);
8248 }
8249
8250 /* Sequence to disable CLKOUT_DP */
8251 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8252 {
8253         uint32_t reg, tmp;
8254
8255         mutex_lock(&dev_priv->sb_lock);
8256
8257         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8258         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8259         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8260         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8261
8262         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8263         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8264                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8265                         tmp |= SBI_SSCCTL_PATHALT;
8266                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8267                         udelay(32);
8268                 }
8269                 tmp |= SBI_SSCCTL_DISABLE;
8270                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8271         }
8272
8273         mutex_unlock(&dev_priv->sb_lock);
8274 }
8275
8276 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8277
8278 static const uint16_t sscdivintphase[] = {
8279         [BEND_IDX( 50)] = 0x3B23,
8280         [BEND_IDX( 45)] = 0x3B23,
8281         [BEND_IDX( 40)] = 0x3C23,
8282         [BEND_IDX( 35)] = 0x3C23,
8283         [BEND_IDX( 30)] = 0x3D23,
8284         [BEND_IDX( 25)] = 0x3D23,
8285         [BEND_IDX( 20)] = 0x3E23,
8286         [BEND_IDX( 15)] = 0x3E23,
8287         [BEND_IDX( 10)] = 0x3F23,
8288         [BEND_IDX(  5)] = 0x3F23,
8289         [BEND_IDX(  0)] = 0x0025,
8290         [BEND_IDX( -5)] = 0x0025,
8291         [BEND_IDX(-10)] = 0x0125,
8292         [BEND_IDX(-15)] = 0x0125,
8293         [BEND_IDX(-20)] = 0x0225,
8294         [BEND_IDX(-25)] = 0x0225,
8295         [BEND_IDX(-30)] = 0x0325,
8296         [BEND_IDX(-35)] = 0x0325,
8297         [BEND_IDX(-40)] = 0x0425,
8298         [BEND_IDX(-45)] = 0x0425,
8299         [BEND_IDX(-50)] = 0x0525,
8300 };
8301
8302 /*
8303  * Bend CLKOUT_DP
8304  * steps -50 to 50 inclusive, in steps of 5
8305  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8306  * change in clock period = -(steps / 10) * 5.787 ps
8307  */
8308 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8309 {
8310         uint32_t tmp;
8311         int idx = BEND_IDX(steps);
8312
8313         if (WARN_ON(steps % 5 != 0))
8314                 return;
8315
8316         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8317                 return;
8318
8319         mutex_lock(&dev_priv->sb_lock);
8320
8321         if (steps % 10 != 0)
8322                 tmp = 0xAAAAAAAB;
8323         else
8324                 tmp = 0x00000000;
8325         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8326
8327         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8328         tmp &= 0xffff0000;
8329         tmp |= sscdivintphase[idx];
8330         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8331
8332         mutex_unlock(&dev_priv->sb_lock);
8333 }
8334
8335 #undef BEND_IDX
8336
8337 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8338 {
8339         struct intel_encoder *encoder;
8340         bool has_vga = false;
8341
8342         for_each_intel_encoder(&dev_priv->drm, encoder) {
8343                 switch (encoder->type) {
8344                 case INTEL_OUTPUT_ANALOG:
8345                         has_vga = true;
8346                         break;
8347                 default:
8348                         break;
8349                 }
8350         }
8351
8352         if (has_vga) {
8353                 lpt_bend_clkout_dp(dev_priv, 0);
8354                 lpt_enable_clkout_dp(dev_priv, true, true);
8355         } else {
8356                 lpt_disable_clkout_dp(dev_priv);
8357         }
8358 }
8359
8360 /*
8361  * Initialize reference clocks when the driver loads
8362  */
8363 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8364 {
8365         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8366                 ironlake_init_pch_refclk(dev_priv);
8367         else if (HAS_PCH_LPT(dev_priv))
8368                 lpt_init_pch_refclk(dev_priv);
8369 }
8370
8371 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8372 {
8373         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8374         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8375         int pipe = intel_crtc->pipe;
8376         uint32_t val;
8377
8378         val = 0;
8379
8380         switch (intel_crtc->config->pipe_bpp) {
8381         case 18:
8382                 val |= PIPECONF_6BPC;
8383                 break;
8384         case 24:
8385                 val |= PIPECONF_8BPC;
8386                 break;
8387         case 30:
8388                 val |= PIPECONF_10BPC;
8389                 break;
8390         case 36:
8391                 val |= PIPECONF_12BPC;
8392                 break;
8393         default:
8394                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8395                 BUG();
8396         }
8397
8398         if (intel_crtc->config->dither)
8399                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8400
8401         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8402                 val |= PIPECONF_INTERLACED_ILK;
8403         else
8404                 val |= PIPECONF_PROGRESSIVE;
8405
8406         if (intel_crtc->config->limited_color_range)
8407                 val |= PIPECONF_COLOR_RANGE_SELECT;
8408
8409         I915_WRITE(PIPECONF(pipe), val);
8410         POSTING_READ(PIPECONF(pipe));
8411 }
8412
8413 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8414 {
8415         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8416         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8417         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8418         u32 val = 0;
8419
8420         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8421                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8422
8423         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8424                 val |= PIPECONF_INTERLACED_ILK;
8425         else
8426                 val |= PIPECONF_PROGRESSIVE;
8427
8428         I915_WRITE(PIPECONF(cpu_transcoder), val);
8429         POSTING_READ(PIPECONF(cpu_transcoder));
8430 }
8431
8432 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8433 {
8434         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8435         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8436         struct intel_crtc_state *config = intel_crtc->config;
8437
8438         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8439                 u32 val = 0;
8440
8441                 switch (intel_crtc->config->pipe_bpp) {
8442                 case 18:
8443                         val |= PIPEMISC_DITHER_6_BPC;
8444                         break;
8445                 case 24:
8446                         val |= PIPEMISC_DITHER_8_BPC;
8447                         break;
8448                 case 30:
8449                         val |= PIPEMISC_DITHER_10_BPC;
8450                         break;
8451                 case 36:
8452                         val |= PIPEMISC_DITHER_12_BPC;
8453                         break;
8454                 default:
8455                         /* Case prevented by pipe_config_set_bpp. */
8456                         BUG();
8457                 }
8458
8459                 if (intel_crtc->config->dither)
8460                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8461
8462                 if (config->ycbcr420) {
8463                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8464                                 PIPEMISC_YUV420_ENABLE |
8465                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8466                 }
8467
8468                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8469         }
8470 }
8471
8472 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8473 {
8474         /*
8475          * Account for spread spectrum to avoid
8476          * oversubscribing the link. Max center spread
8477          * is 2.5%; use 5% for safety's sake.
8478          */
8479         u32 bps = target_clock * bpp * 21 / 20;
8480         return DIV_ROUND_UP(bps, link_bw * 8);
8481 }
8482
8483 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8484 {
8485         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8486 }
8487
8488 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8489                                   struct intel_crtc_state *crtc_state,
8490                                   struct dpll *reduced_clock)
8491 {
8492         struct drm_crtc *crtc = &intel_crtc->base;
8493         struct drm_device *dev = crtc->dev;
8494         struct drm_i915_private *dev_priv = to_i915(dev);
8495         u32 dpll, fp, fp2;
8496         int factor;
8497
8498         /* Enable autotuning of the PLL clock (if permissible) */
8499         factor = 21;
8500         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8501                 if ((intel_panel_use_ssc(dev_priv) &&
8502                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8503                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8504                         factor = 25;
8505         } else if (crtc_state->sdvo_tv_clock)
8506                 factor = 20;
8507
8508         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8509
8510         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8511                 fp |= FP_CB_TUNE;
8512
8513         if (reduced_clock) {
8514                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8515
8516                 if (reduced_clock->m < factor * reduced_clock->n)
8517                         fp2 |= FP_CB_TUNE;
8518         } else {
8519                 fp2 = fp;
8520         }
8521
8522         dpll = 0;
8523
8524         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8525                 dpll |= DPLLB_MODE_LVDS;
8526         else
8527                 dpll |= DPLLB_MODE_DAC_SERIAL;
8528
8529         dpll |= (crtc_state->pixel_multiplier - 1)
8530                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8531
8532         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8533             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8534                 dpll |= DPLL_SDVO_HIGH_SPEED;
8535
8536         if (intel_crtc_has_dp_encoder(crtc_state))
8537                 dpll |= DPLL_SDVO_HIGH_SPEED;
8538
8539         /*
8540          * The high speed IO clock is only really required for
8541          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8542          * possible to share the DPLL between CRT and HDMI. Enabling
8543          * the clock needlessly does no real harm, except use up a
8544          * bit of power potentially.
8545          *
8546          * We'll limit this to IVB with 3 pipes, since it has only two
8547          * DPLLs and so DPLL sharing is the only way to get three pipes
8548          * driving PCH ports at the same time. On SNB we could do this,
8549          * and potentially avoid enabling the second DPLL, but it's not
8550          * clear if it''s a win or loss power wise. No point in doing
8551          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8552          */
8553         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8554             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8555                 dpll |= DPLL_SDVO_HIGH_SPEED;
8556
8557         /* compute bitmask from p1 value */
8558         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8559         /* also FPA1 */
8560         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8561
8562         switch (crtc_state->dpll.p2) {
8563         case 5:
8564                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8565                 break;
8566         case 7:
8567                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8568                 break;
8569         case 10:
8570                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8571                 break;
8572         case 14:
8573                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8574                 break;
8575         }
8576
8577         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8578             intel_panel_use_ssc(dev_priv))
8579                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8580         else
8581                 dpll |= PLL_REF_INPUT_DREFCLK;
8582
8583         dpll |= DPLL_VCO_ENABLE;
8584
8585         crtc_state->dpll_hw_state.dpll = dpll;
8586         crtc_state->dpll_hw_state.fp0 = fp;
8587         crtc_state->dpll_hw_state.fp1 = fp2;
8588 }
8589
8590 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8591                                        struct intel_crtc_state *crtc_state)
8592 {
8593         struct drm_device *dev = crtc->base.dev;
8594         struct drm_i915_private *dev_priv = to_i915(dev);
8595         const struct intel_limit *limit;
8596         int refclk = 120000;
8597
8598         memset(&crtc_state->dpll_hw_state, 0,
8599                sizeof(crtc_state->dpll_hw_state));
8600
8601         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8602         if (!crtc_state->has_pch_encoder)
8603                 return 0;
8604
8605         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8606                 if (intel_panel_use_ssc(dev_priv)) {
8607                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8608                                       dev_priv->vbt.lvds_ssc_freq);
8609                         refclk = dev_priv->vbt.lvds_ssc_freq;
8610                 }
8611
8612                 if (intel_is_dual_link_lvds(dev)) {
8613                         if (refclk == 100000)
8614                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8615                         else
8616                                 limit = &intel_limits_ironlake_dual_lvds;
8617                 } else {
8618                         if (refclk == 100000)
8619                                 limit = &intel_limits_ironlake_single_lvds_100m;
8620                         else
8621                                 limit = &intel_limits_ironlake_single_lvds;
8622                 }
8623         } else {
8624                 limit = &intel_limits_ironlake_dac;
8625         }
8626
8627         if (!crtc_state->clock_set &&
8628             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8629                                 refclk, NULL, &crtc_state->dpll)) {
8630                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8631                 return -EINVAL;
8632         }
8633
8634         ironlake_compute_dpll(crtc, crtc_state, NULL);
8635
8636         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8637                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8638                                  pipe_name(crtc->pipe));
8639                 return -EINVAL;
8640         }
8641
8642         return 0;
8643 }
8644
8645 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8646                                          struct intel_link_m_n *m_n)
8647 {
8648         struct drm_device *dev = crtc->base.dev;
8649         struct drm_i915_private *dev_priv = to_i915(dev);
8650         enum pipe pipe = crtc->pipe;
8651
8652         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8653         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8654         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8655                 & ~TU_SIZE_MASK;
8656         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8657         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8658                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8659 }
8660
8661 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8662                                          enum transcoder transcoder,
8663                                          struct intel_link_m_n *m_n,
8664                                          struct intel_link_m_n *m2_n2)
8665 {
8666         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8667         enum pipe pipe = crtc->pipe;
8668
8669         if (INTEL_GEN(dev_priv) >= 5) {
8670                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8671                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8672                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8673                         & ~TU_SIZE_MASK;
8674                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8675                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8676                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8677                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8678                  * gen < 8) and if DRRS is supported (to make sure the
8679                  * registers are not unnecessarily read).
8680                  */
8681                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8682                         crtc->config->has_drrs) {
8683                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8684                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8685                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8686                                         & ~TU_SIZE_MASK;
8687                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8688                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8689                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8690                 }
8691         } else {
8692                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8693                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8694                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8695                         & ~TU_SIZE_MASK;
8696                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8697                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8698                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8699         }
8700 }
8701
8702 void intel_dp_get_m_n(struct intel_crtc *crtc,
8703                       struct intel_crtc_state *pipe_config)
8704 {
8705         if (pipe_config->has_pch_encoder)
8706                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8707         else
8708                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8709                                              &pipe_config->dp_m_n,
8710                                              &pipe_config->dp_m2_n2);
8711 }
8712
8713 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8714                                         struct intel_crtc_state *pipe_config)
8715 {
8716         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8717                                      &pipe_config->fdi_m_n, NULL);
8718 }
8719
8720 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8721                                     struct intel_crtc_state *pipe_config)
8722 {
8723         struct drm_device *dev = crtc->base.dev;
8724         struct drm_i915_private *dev_priv = to_i915(dev);
8725         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8726         uint32_t ps_ctrl = 0;
8727         int id = -1;
8728         int i;
8729
8730         /* find scaler attached to this pipe */
8731         for (i = 0; i < crtc->num_scalers; i++) {
8732                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8733                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8734                         id = i;
8735                         pipe_config->pch_pfit.enabled = true;
8736                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8737                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8738                         break;
8739                 }
8740         }
8741
8742         scaler_state->scaler_id = id;
8743         if (id >= 0) {
8744                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8745         } else {
8746                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8747         }
8748 }
8749
8750 static void
8751 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8752                                  struct intel_initial_plane_config *plane_config)
8753 {
8754         struct drm_device *dev = crtc->base.dev;
8755         struct drm_i915_private *dev_priv = to_i915(dev);
8756         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8757         enum plane_id plane_id = plane->id;
8758         enum pipe pipe;
8759         u32 val, base, offset, stride_mult, tiling, alpha;
8760         int fourcc, pixel_format;
8761         unsigned int aligned_height;
8762         struct drm_framebuffer *fb;
8763         struct intel_framebuffer *intel_fb;
8764
8765         if (!plane->get_hw_state(plane, &pipe))
8766                 return;
8767
8768         WARN_ON(pipe != crtc->pipe);
8769
8770         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8771         if (!intel_fb) {
8772                 DRM_DEBUG_KMS("failed to alloc fb\n");
8773                 return;
8774         }
8775
8776         fb = &intel_fb->base;
8777
8778         fb->dev = dev;
8779
8780         val = I915_READ(PLANE_CTL(pipe, plane_id));
8781
8782         if (INTEL_GEN(dev_priv) >= 11)
8783                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8784         else
8785                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8786
8787         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8788                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8789                 alpha &= PLANE_COLOR_ALPHA_MASK;
8790         } else {
8791                 alpha = val & PLANE_CTL_ALPHA_MASK;
8792         }
8793
8794         fourcc = skl_format_to_fourcc(pixel_format,
8795                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8796         fb->format = drm_format_info(fourcc);
8797
8798         tiling = val & PLANE_CTL_TILED_MASK;
8799         switch (tiling) {
8800         case PLANE_CTL_TILED_LINEAR:
8801                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8802                 break;
8803         case PLANE_CTL_TILED_X:
8804                 plane_config->tiling = I915_TILING_X;
8805                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8806                 break;
8807         case PLANE_CTL_TILED_Y:
8808                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8809                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8810                 else
8811                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8812                 break;
8813         case PLANE_CTL_TILED_YF:
8814                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8815                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8816                 else
8817                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8818                 break;
8819         default:
8820                 MISSING_CASE(tiling);
8821                 goto error;
8822         }
8823
8824         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8825         plane_config->base = base;
8826
8827         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8828
8829         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8830         fb->height = ((val >> 16) & 0xfff) + 1;
8831         fb->width = ((val >> 0) & 0x1fff) + 1;
8832
8833         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8834         stride_mult = intel_fb_stride_alignment(fb, 0);
8835         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8836
8837         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8838
8839         plane_config->size = fb->pitches[0] * aligned_height;
8840
8841         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8842                       crtc->base.name, plane->base.name, fb->width, fb->height,
8843                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8844                       plane_config->size);
8845
8846         plane_config->fb = intel_fb;
8847         return;
8848
8849 error:
8850         kfree(intel_fb);
8851 }
8852
8853 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8854                                      struct intel_crtc_state *pipe_config)
8855 {
8856         struct drm_device *dev = crtc->base.dev;
8857         struct drm_i915_private *dev_priv = to_i915(dev);
8858         uint32_t tmp;
8859
8860         tmp = I915_READ(PF_CTL(crtc->pipe));
8861
8862         if (tmp & PF_ENABLE) {
8863                 pipe_config->pch_pfit.enabled = true;
8864                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8865                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8866
8867                 /* We currently do not free assignements of panel fitters on
8868                  * ivb/hsw (since we don't use the higher upscaling modes which
8869                  * differentiates them) so just WARN about this case for now. */
8870                 if (IS_GEN7(dev_priv)) {
8871                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8872                                 PF_PIPE_SEL_IVB(crtc->pipe));
8873                 }
8874         }
8875 }
8876
8877 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8878                                      struct intel_crtc_state *pipe_config)
8879 {
8880         struct drm_device *dev = crtc->base.dev;
8881         struct drm_i915_private *dev_priv = to_i915(dev);
8882         enum intel_display_power_domain power_domain;
8883         uint32_t tmp;
8884         bool ret;
8885
8886         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8887         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8888                 return false;
8889
8890         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8891         pipe_config->shared_dpll = NULL;
8892
8893         ret = false;
8894         tmp = I915_READ(PIPECONF(crtc->pipe));
8895         if (!(tmp & PIPECONF_ENABLE))
8896                 goto out;
8897
8898         switch (tmp & PIPECONF_BPC_MASK) {
8899         case PIPECONF_6BPC:
8900                 pipe_config->pipe_bpp = 18;
8901                 break;
8902         case PIPECONF_8BPC:
8903                 pipe_config->pipe_bpp = 24;
8904                 break;
8905         case PIPECONF_10BPC:
8906                 pipe_config->pipe_bpp = 30;
8907                 break;
8908         case PIPECONF_12BPC:
8909                 pipe_config->pipe_bpp = 36;
8910                 break;
8911         default:
8912                 break;
8913         }
8914
8915         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8916                 pipe_config->limited_color_range = true;
8917
8918         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8919                 struct intel_shared_dpll *pll;
8920                 enum intel_dpll_id pll_id;
8921
8922                 pipe_config->has_pch_encoder = true;
8923
8924                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8925                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8926                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8927
8928                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8929
8930                 if (HAS_PCH_IBX(dev_priv)) {
8931                         /*
8932                          * The pipe->pch transcoder and pch transcoder->pll
8933                          * mapping is fixed.
8934                          */
8935                         pll_id = (enum intel_dpll_id) crtc->pipe;
8936                 } else {
8937                         tmp = I915_READ(PCH_DPLL_SEL);
8938                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8939                                 pll_id = DPLL_ID_PCH_PLL_B;
8940                         else
8941                                 pll_id= DPLL_ID_PCH_PLL_A;
8942                 }
8943
8944                 pipe_config->shared_dpll =
8945                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8946                 pll = pipe_config->shared_dpll;
8947
8948                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
8949                                                 &pipe_config->dpll_hw_state));
8950
8951                 tmp = pipe_config->dpll_hw_state.dpll;
8952                 pipe_config->pixel_multiplier =
8953                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8954                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8955
8956                 ironlake_pch_clock_get(crtc, pipe_config);
8957         } else {
8958                 pipe_config->pixel_multiplier = 1;
8959         }
8960
8961         intel_get_pipe_timings(crtc, pipe_config);
8962         intel_get_pipe_src_size(crtc, pipe_config);
8963
8964         ironlake_get_pfit_config(crtc, pipe_config);
8965
8966         ret = true;
8967
8968 out:
8969         intel_display_power_put(dev_priv, power_domain);
8970
8971         return ret;
8972 }
8973
8974 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8975 {
8976         struct drm_device *dev = &dev_priv->drm;
8977         struct intel_crtc *crtc;
8978
8979         for_each_intel_crtc(dev, crtc)
8980                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8981                      pipe_name(crtc->pipe));
8982
8983         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
8984                         "Display power well on\n");
8985         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8986         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8987         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8988         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8989         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8990              "CPU PWM1 enabled\n");
8991         if (IS_HASWELL(dev_priv))
8992                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8993                      "CPU PWM2 enabled\n");
8994         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8995              "PCH PWM1 enabled\n");
8996         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8997              "Utility pin enabled\n");
8998         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8999
9000         /*
9001          * In theory we can still leave IRQs enabled, as long as only the HPD
9002          * interrupts remain enabled. We used to check for that, but since it's
9003          * gen-specific and since we only disable LCPLL after we fully disable
9004          * the interrupts, the check below should be enough.
9005          */
9006         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9007 }
9008
9009 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9010 {
9011         if (IS_HASWELL(dev_priv))
9012                 return I915_READ(D_COMP_HSW);
9013         else
9014                 return I915_READ(D_COMP_BDW);
9015 }
9016
9017 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9018 {
9019         if (IS_HASWELL(dev_priv)) {
9020                 mutex_lock(&dev_priv->pcu_lock);
9021                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9022                                             val))
9023                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9024                 mutex_unlock(&dev_priv->pcu_lock);
9025         } else {
9026                 I915_WRITE(D_COMP_BDW, val);
9027                 POSTING_READ(D_COMP_BDW);
9028         }
9029 }
9030
9031 /*
9032  * This function implements pieces of two sequences from BSpec:
9033  * - Sequence for display software to disable LCPLL
9034  * - Sequence for display software to allow package C8+
9035  * The steps implemented here are just the steps that actually touch the LCPLL
9036  * register. Callers should take care of disabling all the display engine
9037  * functions, doing the mode unset, fixing interrupts, etc.
9038  */
9039 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9040                               bool switch_to_fclk, bool allow_power_down)
9041 {
9042         uint32_t val;
9043
9044         assert_can_disable_lcpll(dev_priv);
9045
9046         val = I915_READ(LCPLL_CTL);
9047
9048         if (switch_to_fclk) {
9049                 val |= LCPLL_CD_SOURCE_FCLK;
9050                 I915_WRITE(LCPLL_CTL, val);
9051
9052                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9053                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9054                         DRM_ERROR("Switching to FCLK failed\n");
9055
9056                 val = I915_READ(LCPLL_CTL);
9057         }
9058
9059         val |= LCPLL_PLL_DISABLE;
9060         I915_WRITE(LCPLL_CTL, val);
9061         POSTING_READ(LCPLL_CTL);
9062
9063         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9064                 DRM_ERROR("LCPLL still locked\n");
9065
9066         val = hsw_read_dcomp(dev_priv);
9067         val |= D_COMP_COMP_DISABLE;
9068         hsw_write_dcomp(dev_priv, val);
9069         ndelay(100);
9070
9071         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9072                      1))
9073                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9074
9075         if (allow_power_down) {
9076                 val = I915_READ(LCPLL_CTL);
9077                 val |= LCPLL_POWER_DOWN_ALLOW;
9078                 I915_WRITE(LCPLL_CTL, val);
9079                 POSTING_READ(LCPLL_CTL);
9080         }
9081 }
9082
9083 /*
9084  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9085  * source.
9086  */
9087 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9088 {
9089         uint32_t val;
9090
9091         val = I915_READ(LCPLL_CTL);
9092
9093         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9094                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9095                 return;
9096
9097         /*
9098          * Make sure we're not on PC8 state before disabling PC8, otherwise
9099          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9100          */
9101         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9102
9103         if (val & LCPLL_POWER_DOWN_ALLOW) {
9104                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9105                 I915_WRITE(LCPLL_CTL, val);
9106                 POSTING_READ(LCPLL_CTL);
9107         }
9108
9109         val = hsw_read_dcomp(dev_priv);
9110         val |= D_COMP_COMP_FORCE;
9111         val &= ~D_COMP_COMP_DISABLE;
9112         hsw_write_dcomp(dev_priv, val);
9113
9114         val = I915_READ(LCPLL_CTL);
9115         val &= ~LCPLL_PLL_DISABLE;
9116         I915_WRITE(LCPLL_CTL, val);
9117
9118         if (intel_wait_for_register(dev_priv,
9119                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9120                                     5))
9121                 DRM_ERROR("LCPLL not locked yet\n");
9122
9123         if (val & LCPLL_CD_SOURCE_FCLK) {
9124                 val = I915_READ(LCPLL_CTL);
9125                 val &= ~LCPLL_CD_SOURCE_FCLK;
9126                 I915_WRITE(LCPLL_CTL, val);
9127
9128                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9129                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9130                         DRM_ERROR("Switching back to LCPLL failed\n");
9131         }
9132
9133         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9134
9135         intel_update_cdclk(dev_priv);
9136         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9137 }
9138
9139 /*
9140  * Package states C8 and deeper are really deep PC states that can only be
9141  * reached when all the devices on the system allow it, so even if the graphics
9142  * device allows PC8+, it doesn't mean the system will actually get to these
9143  * states. Our driver only allows PC8+ when going into runtime PM.
9144  *
9145  * The requirements for PC8+ are that all the outputs are disabled, the power
9146  * well is disabled and most interrupts are disabled, and these are also
9147  * requirements for runtime PM. When these conditions are met, we manually do
9148  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9149  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9150  * hang the machine.
9151  *
9152  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9153  * the state of some registers, so when we come back from PC8+ we need to
9154  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9155  * need to take care of the registers kept by RC6. Notice that this happens even
9156  * if we don't put the device in PCI D3 state (which is what currently happens
9157  * because of the runtime PM support).
9158  *
9159  * For more, read "Display Sequences for Package C8" on the hardware
9160  * documentation.
9161  */
9162 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9163 {
9164         uint32_t val;
9165
9166         DRM_DEBUG_KMS("Enabling package C8+\n");
9167
9168         if (HAS_PCH_LPT_LP(dev_priv)) {
9169                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9170                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9171                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9172         }
9173
9174         lpt_disable_clkout_dp(dev_priv);
9175         hsw_disable_lcpll(dev_priv, true, true);
9176 }
9177
9178 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9179 {
9180         uint32_t val;
9181
9182         DRM_DEBUG_KMS("Disabling package C8+\n");
9183
9184         hsw_restore_lcpll(dev_priv);
9185         lpt_init_pch_refclk(dev_priv);
9186
9187         if (HAS_PCH_LPT_LP(dev_priv)) {
9188                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9189                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9190                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9191         }
9192 }
9193
9194 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9195                                       struct intel_crtc_state *crtc_state)
9196 {
9197         struct intel_atomic_state *state =
9198                 to_intel_atomic_state(crtc_state->base.state);
9199
9200         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9201                 struct intel_encoder *encoder =
9202                         intel_get_crtc_new_encoder(state, crtc_state);
9203
9204                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9205                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9206                                          pipe_name(crtc->pipe));
9207                         return -EINVAL;
9208                 }
9209         }
9210
9211         return 0;
9212 }
9213
9214 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9215                                    enum port port,
9216                                    struct intel_crtc_state *pipe_config)
9217 {
9218         enum intel_dpll_id id;
9219         u32 temp;
9220
9221         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9222         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9223
9224         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9225                 return;
9226
9227         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9228 }
9229
9230 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9231                                 enum port port,
9232                                 struct intel_crtc_state *pipe_config)
9233 {
9234         enum intel_dpll_id id;
9235         u32 temp;
9236
9237         /* TODO: TBT pll not implemented. */
9238         switch (port) {
9239         case PORT_A:
9240         case PORT_B:
9241                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9242                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9243                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9244
9245                 if (WARN_ON(id != DPLL_ID_ICL_DPLL0 && id != DPLL_ID_ICL_DPLL1))
9246                         return;
9247                 break;
9248         case PORT_C:
9249                 id = DPLL_ID_ICL_MGPLL1;
9250                 break;
9251         case PORT_D:
9252                 id = DPLL_ID_ICL_MGPLL2;
9253                 break;
9254         case PORT_E:
9255                 id = DPLL_ID_ICL_MGPLL3;
9256                 break;
9257         case PORT_F:
9258                 id = DPLL_ID_ICL_MGPLL4;
9259                 break;
9260         default:
9261                 MISSING_CASE(port);
9262                 return;
9263         }
9264
9265         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9266 }
9267
9268 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9269                                 enum port port,
9270                                 struct intel_crtc_state *pipe_config)
9271 {
9272         enum intel_dpll_id id;
9273
9274         switch (port) {
9275         case PORT_A:
9276                 id = DPLL_ID_SKL_DPLL0;
9277                 break;
9278         case PORT_B:
9279                 id = DPLL_ID_SKL_DPLL1;
9280                 break;
9281         case PORT_C:
9282                 id = DPLL_ID_SKL_DPLL2;
9283                 break;
9284         default:
9285                 DRM_ERROR("Incorrect port type\n");
9286                 return;
9287         }
9288
9289         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9290 }
9291
9292 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9293                                 enum port port,
9294                                 struct intel_crtc_state *pipe_config)
9295 {
9296         enum intel_dpll_id id;
9297         u32 temp;
9298
9299         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9300         id = temp >> (port * 3 + 1);
9301
9302         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9303                 return;
9304
9305         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9306 }
9307
9308 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9309                                 enum port port,
9310                                 struct intel_crtc_state *pipe_config)
9311 {
9312         enum intel_dpll_id id;
9313         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9314
9315         switch (ddi_pll_sel) {
9316         case PORT_CLK_SEL_WRPLL1:
9317                 id = DPLL_ID_WRPLL1;
9318                 break;
9319         case PORT_CLK_SEL_WRPLL2:
9320                 id = DPLL_ID_WRPLL2;
9321                 break;
9322         case PORT_CLK_SEL_SPLL:
9323                 id = DPLL_ID_SPLL;
9324                 break;
9325         case PORT_CLK_SEL_LCPLL_810:
9326                 id = DPLL_ID_LCPLL_810;
9327                 break;
9328         case PORT_CLK_SEL_LCPLL_1350:
9329                 id = DPLL_ID_LCPLL_1350;
9330                 break;
9331         case PORT_CLK_SEL_LCPLL_2700:
9332                 id = DPLL_ID_LCPLL_2700;
9333                 break;
9334         default:
9335                 MISSING_CASE(ddi_pll_sel);
9336                 /* fall through */
9337         case PORT_CLK_SEL_NONE:
9338                 return;
9339         }
9340
9341         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9342 }
9343
9344 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9345                                      struct intel_crtc_state *pipe_config,
9346                                      u64 *power_domain_mask)
9347 {
9348         struct drm_device *dev = crtc->base.dev;
9349         struct drm_i915_private *dev_priv = to_i915(dev);
9350         enum intel_display_power_domain power_domain;
9351         u32 tmp;
9352
9353         /*
9354          * The pipe->transcoder mapping is fixed with the exception of the eDP
9355          * transcoder handled below.
9356          */
9357         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9358
9359         /*
9360          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9361          * consistency and less surprising code; it's in always on power).
9362          */
9363         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9364         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9365                 enum pipe trans_edp_pipe;
9366                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9367                 default:
9368                         WARN(1, "unknown pipe linked to edp transcoder\n");
9369                         /* fall through */
9370                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9371                 case TRANS_DDI_EDP_INPUT_A_ON:
9372                         trans_edp_pipe = PIPE_A;
9373                         break;
9374                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9375                         trans_edp_pipe = PIPE_B;
9376                         break;
9377                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9378                         trans_edp_pipe = PIPE_C;
9379                         break;
9380                 }
9381
9382                 if (trans_edp_pipe == crtc->pipe)
9383                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9384         }
9385
9386         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9387         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9388                 return false;
9389         *power_domain_mask |= BIT_ULL(power_domain);
9390
9391         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9392
9393         return tmp & PIPECONF_ENABLE;
9394 }
9395
9396 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9397                                          struct intel_crtc_state *pipe_config,
9398                                          u64 *power_domain_mask)
9399 {
9400         struct drm_device *dev = crtc->base.dev;
9401         struct drm_i915_private *dev_priv = to_i915(dev);
9402         enum intel_display_power_domain power_domain;
9403         enum port port;
9404         enum transcoder cpu_transcoder;
9405         u32 tmp;
9406
9407         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9408                 if (port == PORT_A)
9409                         cpu_transcoder = TRANSCODER_DSI_A;
9410                 else
9411                         cpu_transcoder = TRANSCODER_DSI_C;
9412
9413                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9414                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9415                         continue;
9416                 *power_domain_mask |= BIT_ULL(power_domain);
9417
9418                 /*
9419                  * The PLL needs to be enabled with a valid divider
9420                  * configuration, otherwise accessing DSI registers will hang
9421                  * the machine. See BSpec North Display Engine
9422                  * registers/MIPI[BXT]. We can break out here early, since we
9423                  * need the same DSI PLL to be enabled for both DSI ports.
9424                  */
9425                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9426                         break;
9427
9428                 /* XXX: this works for video mode only */
9429                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9430                 if (!(tmp & DPI_ENABLE))
9431                         continue;
9432
9433                 tmp = I915_READ(MIPI_CTRL(port));
9434                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9435                         continue;
9436
9437                 pipe_config->cpu_transcoder = cpu_transcoder;
9438                 break;
9439         }
9440
9441         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9442 }
9443
9444 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9445                                        struct intel_crtc_state *pipe_config)
9446 {
9447         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9448         struct intel_shared_dpll *pll;
9449         enum port port;
9450         uint32_t tmp;
9451
9452         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9453
9454         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9455
9456         if (IS_ICELAKE(dev_priv))
9457                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9458         else if (IS_CANNONLAKE(dev_priv))
9459                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9460         else if (IS_GEN9_BC(dev_priv))
9461                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9462         else if (IS_GEN9_LP(dev_priv))
9463                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9464         else
9465                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9466
9467         pll = pipe_config->shared_dpll;
9468         if (pll) {
9469                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9470                                                 &pipe_config->dpll_hw_state));
9471         }
9472
9473         /*
9474          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9475          * DDI E. So just check whether this pipe is wired to DDI E and whether
9476          * the PCH transcoder is on.
9477          */
9478         if (INTEL_GEN(dev_priv) < 9 &&
9479             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9480                 pipe_config->has_pch_encoder = true;
9481
9482                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9483                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9484                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9485
9486                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9487         }
9488 }
9489
9490 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9491                                     struct intel_crtc_state *pipe_config)
9492 {
9493         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9494         enum intel_display_power_domain power_domain;
9495         u64 power_domain_mask;
9496         bool active;
9497
9498         intel_crtc_init_scalers(crtc, pipe_config);
9499
9500         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9501         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9502                 return false;
9503         power_domain_mask = BIT_ULL(power_domain);
9504
9505         pipe_config->shared_dpll = NULL;
9506
9507         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9508
9509         if (IS_GEN9_LP(dev_priv) &&
9510             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9511                 WARN_ON(active);
9512                 active = true;
9513         }
9514
9515         if (!active)
9516                 goto out;
9517
9518         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9519                 haswell_get_ddi_port_state(crtc, pipe_config);
9520                 intel_get_pipe_timings(crtc, pipe_config);
9521         }
9522
9523         intel_get_pipe_src_size(crtc, pipe_config);
9524
9525         pipe_config->gamma_mode =
9526                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9527
9528         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9529                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9530                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9531
9532                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9533                         bool blend_mode_420 = tmp &
9534                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9535
9536                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9537                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9538                             pipe_config->ycbcr420 != blend_mode_420)
9539                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9540                 } else if (clrspace_yuv) {
9541                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9542                 }
9543         }
9544
9545         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9546         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9547                 power_domain_mask |= BIT_ULL(power_domain);
9548                 if (INTEL_GEN(dev_priv) >= 9)
9549                         skylake_get_pfit_config(crtc, pipe_config);
9550                 else
9551                         ironlake_get_pfit_config(crtc, pipe_config);
9552         }
9553
9554         if (hsw_crtc_supports_ips(crtc)) {
9555                 if (IS_HASWELL(dev_priv))
9556                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9557                 else {
9558                         /*
9559                          * We cannot readout IPS state on broadwell, set to
9560                          * true so we can set it to a defined state on first
9561                          * commit.
9562                          */
9563                         pipe_config->ips_enabled = true;
9564                 }
9565         }
9566
9567         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9568             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9569                 pipe_config->pixel_multiplier =
9570                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9571         } else {
9572                 pipe_config->pixel_multiplier = 1;
9573         }
9574
9575 out:
9576         for_each_power_domain(power_domain, power_domain_mask)
9577                 intel_display_power_put(dev_priv, power_domain);
9578
9579         return active;
9580 }
9581
9582 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9583 {
9584         struct drm_i915_private *dev_priv =
9585                 to_i915(plane_state->base.plane->dev);
9586         const struct drm_framebuffer *fb = plane_state->base.fb;
9587         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9588         u32 base;
9589
9590         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9591                 base = obj->phys_handle->busaddr;
9592         else
9593                 base = intel_plane_ggtt_offset(plane_state);
9594
9595         base += plane_state->main.offset;
9596
9597         /* ILK+ do this automagically */
9598         if (HAS_GMCH_DISPLAY(dev_priv) &&
9599             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9600                 base += (plane_state->base.crtc_h *
9601                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9602
9603         return base;
9604 }
9605
9606 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9607 {
9608         int x = plane_state->base.crtc_x;
9609         int y = plane_state->base.crtc_y;
9610         u32 pos = 0;
9611
9612         if (x < 0) {
9613                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9614                 x = -x;
9615         }
9616         pos |= x << CURSOR_X_SHIFT;
9617
9618         if (y < 0) {
9619                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9620                 y = -y;
9621         }
9622         pos |= y << CURSOR_Y_SHIFT;
9623
9624         return pos;
9625 }
9626
9627 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9628 {
9629         const struct drm_mode_config *config =
9630                 &plane_state->base.plane->dev->mode_config;
9631         int width = plane_state->base.crtc_w;
9632         int height = plane_state->base.crtc_h;
9633
9634         return width > 0 && width <= config->cursor_width &&
9635                 height > 0 && height <= config->cursor_height;
9636 }
9637
9638 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9639                               struct intel_plane_state *plane_state)
9640 {
9641         const struct drm_framebuffer *fb = plane_state->base.fb;
9642         int src_x, src_y;
9643         u32 offset;
9644         int ret;
9645
9646         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9647                                                   &crtc_state->base,
9648                                                   DRM_PLANE_HELPER_NO_SCALING,
9649                                                   DRM_PLANE_HELPER_NO_SCALING,
9650                                                   true, true);
9651         if (ret)
9652                 return ret;
9653
9654         if (!fb)
9655                 return 0;
9656
9657         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9658                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9659                 return -EINVAL;
9660         }
9661
9662         src_x = plane_state->base.src_x >> 16;
9663         src_y = plane_state->base.src_y >> 16;
9664
9665         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9666         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9667
9668         if (src_x != 0 || src_y != 0) {
9669                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9670                 return -EINVAL;
9671         }
9672
9673         plane_state->main.offset = offset;
9674
9675         return 0;
9676 }
9677
9678 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9679                            const struct intel_plane_state *plane_state)
9680 {
9681         const struct drm_framebuffer *fb = plane_state->base.fb;
9682
9683         return CURSOR_ENABLE |
9684                 CURSOR_GAMMA_ENABLE |
9685                 CURSOR_FORMAT_ARGB |
9686                 CURSOR_STRIDE(fb->pitches[0]);
9687 }
9688
9689 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9690 {
9691         int width = plane_state->base.crtc_w;
9692
9693         /*
9694          * 845g/865g are only limited by the width of their cursors,
9695          * the height is arbitrary up to the precision of the register.
9696          */
9697         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9698 }
9699
9700 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
9701                              struct intel_plane_state *plane_state)
9702 {
9703         const struct drm_framebuffer *fb = plane_state->base.fb;
9704         int ret;
9705
9706         ret = intel_check_cursor(crtc_state, plane_state);
9707         if (ret)
9708                 return ret;
9709
9710         /* if we want to turn off the cursor ignore width and height */
9711         if (!fb)
9712                 return 0;
9713
9714         /* Check for which cursor types we support */
9715         if (!i845_cursor_size_ok(plane_state)) {
9716                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9717                           plane_state->base.crtc_w,
9718                           plane_state->base.crtc_h);
9719                 return -EINVAL;
9720         }
9721
9722         switch (fb->pitches[0]) {
9723         case 256:
9724         case 512:
9725         case 1024:
9726         case 2048:
9727                 break;
9728         default:
9729                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9730                               fb->pitches[0]);
9731                 return -EINVAL;
9732         }
9733
9734         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9735
9736         return 0;
9737 }
9738
9739 static void i845_update_cursor(struct intel_plane *plane,
9740                                const struct intel_crtc_state *crtc_state,
9741                                const struct intel_plane_state *plane_state)
9742 {
9743         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9744         u32 cntl = 0, base = 0, pos = 0, size = 0;
9745         unsigned long irqflags;
9746
9747         if (plane_state && plane_state->base.visible) {
9748                 unsigned int width = plane_state->base.crtc_w;
9749                 unsigned int height = plane_state->base.crtc_h;
9750
9751                 cntl = plane_state->ctl;
9752                 size = (height << 12) | width;
9753
9754                 base = intel_cursor_base(plane_state);
9755                 pos = intel_cursor_position(plane_state);
9756         }
9757
9758         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9759
9760         /* On these chipsets we can only modify the base/size/stride
9761          * whilst the cursor is disabled.
9762          */
9763         if (plane->cursor.base != base ||
9764             plane->cursor.size != size ||
9765             plane->cursor.cntl != cntl) {
9766                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9767                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9768                 I915_WRITE_FW(CURSIZE, size);
9769                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9770                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9771
9772                 plane->cursor.base = base;
9773                 plane->cursor.size = size;
9774                 plane->cursor.cntl = cntl;
9775         } else {
9776                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9777         }
9778
9779         POSTING_READ_FW(CURCNTR(PIPE_A));
9780
9781         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9782 }
9783
9784 static void i845_disable_cursor(struct intel_plane *plane,
9785                                 struct intel_crtc *crtc)
9786 {
9787         i845_update_cursor(plane, NULL, NULL);
9788 }
9789
9790 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
9791                                      enum pipe *pipe)
9792 {
9793         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9794         enum intel_display_power_domain power_domain;
9795         bool ret;
9796
9797         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9798         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9799                 return false;
9800
9801         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9802
9803         *pipe = PIPE_A;
9804
9805         intel_display_power_put(dev_priv, power_domain);
9806
9807         return ret;
9808 }
9809
9810 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9811                            const struct intel_plane_state *plane_state)
9812 {
9813         struct drm_i915_private *dev_priv =
9814                 to_i915(plane_state->base.plane->dev);
9815         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9816         u32 cntl = 0;
9817
9818         if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
9819                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
9820
9821         if (INTEL_GEN(dev_priv) <= 10) {
9822                 cntl |= MCURSOR_GAMMA_ENABLE;
9823
9824                 if (HAS_DDI(dev_priv))
9825                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
9826         }
9827
9828         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9829                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9830
9831         switch (plane_state->base.crtc_w) {
9832         case 64:
9833                 cntl |= MCURSOR_MODE_64_ARGB_AX;
9834                 break;
9835         case 128:
9836                 cntl |= MCURSOR_MODE_128_ARGB_AX;
9837                 break;
9838         case 256:
9839                 cntl |= MCURSOR_MODE_256_ARGB_AX;
9840                 break;
9841         default:
9842                 MISSING_CASE(plane_state->base.crtc_w);
9843                 return 0;
9844         }
9845
9846         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9847                 cntl |= MCURSOR_ROTATE_180;
9848
9849         return cntl;
9850 }
9851
9852 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9853 {
9854         struct drm_i915_private *dev_priv =
9855                 to_i915(plane_state->base.plane->dev);
9856         int width = plane_state->base.crtc_w;
9857         int height = plane_state->base.crtc_h;
9858
9859         if (!intel_cursor_size_ok(plane_state))
9860                 return false;
9861
9862         /* Cursor width is limited to a few power-of-two sizes */
9863         switch (width) {
9864         case 256:
9865         case 128:
9866         case 64:
9867                 break;
9868         default:
9869                 return false;
9870         }
9871
9872         /*
9873          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9874          * height from 8 lines up to the cursor width, when the
9875          * cursor is not rotated. Everything else requires square
9876          * cursors.
9877          */
9878         if (HAS_CUR_FBC(dev_priv) &&
9879             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9880                 if (height < 8 || height > width)
9881                         return false;
9882         } else {
9883                 if (height != width)
9884                         return false;
9885         }
9886
9887         return true;
9888 }
9889
9890 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
9891                              struct intel_plane_state *plane_state)
9892 {
9893         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
9894         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9895         const struct drm_framebuffer *fb = plane_state->base.fb;
9896         enum pipe pipe = plane->pipe;
9897         int ret;
9898
9899         ret = intel_check_cursor(crtc_state, plane_state);
9900         if (ret)
9901                 return ret;
9902
9903         /* if we want to turn off the cursor ignore width and height */
9904         if (!fb)
9905                 return 0;
9906
9907         /* Check for which cursor types we support */
9908         if (!i9xx_cursor_size_ok(plane_state)) {
9909                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9910                           plane_state->base.crtc_w,
9911                           plane_state->base.crtc_h);
9912                 return -EINVAL;
9913         }
9914
9915         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9916                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9917                               fb->pitches[0], plane_state->base.crtc_w);
9918                 return -EINVAL;
9919         }
9920
9921         /*
9922          * There's something wrong with the cursor on CHV pipe C.
9923          * If it straddles the left edge of the screen then
9924          * moving it away from the edge or disabling it often
9925          * results in a pipe underrun, and often that can lead to
9926          * dead pipe (constant underrun reported, and it scans
9927          * out just a solid color). To recover from that, the
9928          * display power well must be turned off and on again.
9929          * Refuse the put the cursor into that compromised position.
9930          */
9931         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9932             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9933                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9934                 return -EINVAL;
9935         }
9936
9937         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9938
9939         return 0;
9940 }
9941
9942 static void i9xx_update_cursor(struct intel_plane *plane,
9943                                const struct intel_crtc_state *crtc_state,
9944                                const struct intel_plane_state *plane_state)
9945 {
9946         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9947         enum pipe pipe = plane->pipe;
9948         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9949         unsigned long irqflags;
9950
9951         if (plane_state && plane_state->base.visible) {
9952                 cntl = plane_state->ctl;
9953
9954                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9955                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9956
9957                 base = intel_cursor_base(plane_state);
9958                 pos = intel_cursor_position(plane_state);
9959         }
9960
9961         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9962
9963         /*
9964          * On some platforms writing CURCNTR first will also
9965          * cause CURPOS to be armed by the CURBASE write.
9966          * Without the CURCNTR write the CURPOS write would
9967          * arm itself. Thus we always start the full update
9968          * with a CURCNTR write.
9969          *
9970          * On other platforms CURPOS always requires the
9971          * CURBASE write to arm the update. Additonally
9972          * a write to any of the cursor register will cancel
9973          * an already armed cursor update. Thus leaving out
9974          * the CURBASE write after CURPOS could lead to a
9975          * cursor that doesn't appear to move, or even change
9976          * shape. Thus we always write CURBASE.
9977          *
9978          * CURCNTR and CUR_FBC_CTL are always
9979          * armed by the CURBASE write only.
9980          */
9981         if (plane->cursor.base != base ||
9982             plane->cursor.size != fbc_ctl ||
9983             plane->cursor.cntl != cntl) {
9984                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9985                 if (HAS_CUR_FBC(dev_priv))
9986                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9987                 I915_WRITE_FW(CURPOS(pipe), pos);
9988                 I915_WRITE_FW(CURBASE(pipe), base);
9989
9990                 plane->cursor.base = base;
9991                 plane->cursor.size = fbc_ctl;
9992                 plane->cursor.cntl = cntl;
9993         } else {
9994                 I915_WRITE_FW(CURPOS(pipe), pos);
9995                 I915_WRITE_FW(CURBASE(pipe), base);
9996         }
9997
9998         POSTING_READ_FW(CURBASE(pipe));
9999
10000         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10001 }
10002
10003 static void i9xx_disable_cursor(struct intel_plane *plane,
10004                                 struct intel_crtc *crtc)
10005 {
10006         i9xx_update_cursor(plane, NULL, NULL);
10007 }
10008
10009 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10010                                      enum pipe *pipe)
10011 {
10012         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10013         enum intel_display_power_domain power_domain;
10014         bool ret;
10015         u32 val;
10016
10017         /*
10018          * Not 100% correct for planes that can move between pipes,
10019          * but that's only the case for gen2-3 which don't have any
10020          * display power wells.
10021          */
10022         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10023         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10024                 return false;
10025
10026         val = I915_READ(CURCNTR(plane->pipe));
10027
10028         ret = val & MCURSOR_MODE;
10029
10030         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10031                 *pipe = plane->pipe;
10032         else
10033                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10034                         MCURSOR_PIPE_SELECT_SHIFT;
10035
10036         intel_display_power_put(dev_priv, power_domain);
10037
10038         return ret;
10039 }
10040
10041 /* VESA 640x480x72Hz mode to set on the pipe */
10042 static const struct drm_display_mode load_detect_mode = {
10043         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10044                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10045 };
10046
10047 struct drm_framebuffer *
10048 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10049                          struct drm_mode_fb_cmd2 *mode_cmd)
10050 {
10051         struct intel_framebuffer *intel_fb;
10052         int ret;
10053
10054         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10055         if (!intel_fb)
10056                 return ERR_PTR(-ENOMEM);
10057
10058         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10059         if (ret)
10060                 goto err;
10061
10062         return &intel_fb->base;
10063
10064 err:
10065         kfree(intel_fb);
10066         return ERR_PTR(ret);
10067 }
10068
10069 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10070                                         struct drm_crtc *crtc)
10071 {
10072         struct drm_plane *plane;
10073         struct drm_plane_state *plane_state;
10074         int ret, i;
10075
10076         ret = drm_atomic_add_affected_planes(state, crtc);
10077         if (ret)
10078                 return ret;
10079
10080         for_each_new_plane_in_state(state, plane, plane_state, i) {
10081                 if (plane_state->crtc != crtc)
10082                         continue;
10083
10084                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10085                 if (ret)
10086                         return ret;
10087
10088                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10089         }
10090
10091         return 0;
10092 }
10093
10094 int intel_get_load_detect_pipe(struct drm_connector *connector,
10095                                const struct drm_display_mode *mode,
10096                                struct intel_load_detect_pipe *old,
10097                                struct drm_modeset_acquire_ctx *ctx)
10098 {
10099         struct intel_crtc *intel_crtc;
10100         struct intel_encoder *intel_encoder =
10101                 intel_attached_encoder(connector);
10102         struct drm_crtc *possible_crtc;
10103         struct drm_encoder *encoder = &intel_encoder->base;
10104         struct drm_crtc *crtc = NULL;
10105         struct drm_device *dev = encoder->dev;
10106         struct drm_i915_private *dev_priv = to_i915(dev);
10107         struct drm_mode_config *config = &dev->mode_config;
10108         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10109         struct drm_connector_state *connector_state;
10110         struct intel_crtc_state *crtc_state;
10111         int ret, i = -1;
10112
10113         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10114                       connector->base.id, connector->name,
10115                       encoder->base.id, encoder->name);
10116
10117         old->restore_state = NULL;
10118
10119         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10120
10121         /*
10122          * Algorithm gets a little messy:
10123          *
10124          *   - if the connector already has an assigned crtc, use it (but make
10125          *     sure it's on first)
10126          *
10127          *   - try to find the first unused crtc that can drive this connector,
10128          *     and use that if we find one
10129          */
10130
10131         /* See if we already have a CRTC for this connector */
10132         if (connector->state->crtc) {
10133                 crtc = connector->state->crtc;
10134
10135                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10136                 if (ret)
10137                         goto fail;
10138
10139                 /* Make sure the crtc and connector are running */
10140                 goto found;
10141         }
10142
10143         /* Find an unused one (if possible) */
10144         for_each_crtc(dev, possible_crtc) {
10145                 i++;
10146                 if (!(encoder->possible_crtcs & (1 << i)))
10147                         continue;
10148
10149                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10150                 if (ret)
10151                         goto fail;
10152
10153                 if (possible_crtc->state->enable) {
10154                         drm_modeset_unlock(&possible_crtc->mutex);
10155                         continue;
10156                 }
10157
10158                 crtc = possible_crtc;
10159                 break;
10160         }
10161
10162         /*
10163          * If we didn't find an unused CRTC, don't use any.
10164          */
10165         if (!crtc) {
10166                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10167                 ret = -ENODEV;
10168                 goto fail;
10169         }
10170
10171 found:
10172         intel_crtc = to_intel_crtc(crtc);
10173
10174         state = drm_atomic_state_alloc(dev);
10175         restore_state = drm_atomic_state_alloc(dev);
10176         if (!state || !restore_state) {
10177                 ret = -ENOMEM;
10178                 goto fail;
10179         }
10180
10181         state->acquire_ctx = ctx;
10182         restore_state->acquire_ctx = ctx;
10183
10184         connector_state = drm_atomic_get_connector_state(state, connector);
10185         if (IS_ERR(connector_state)) {
10186                 ret = PTR_ERR(connector_state);
10187                 goto fail;
10188         }
10189
10190         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10191         if (ret)
10192                 goto fail;
10193
10194         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10195         if (IS_ERR(crtc_state)) {
10196                 ret = PTR_ERR(crtc_state);
10197                 goto fail;
10198         }
10199
10200         crtc_state->base.active = crtc_state->base.enable = true;
10201
10202         if (!mode)
10203                 mode = &load_detect_mode;
10204
10205         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10206         if (ret)
10207                 goto fail;
10208
10209         ret = intel_modeset_disable_planes(state, crtc);
10210         if (ret)
10211                 goto fail;
10212
10213         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10214         if (!ret)
10215                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10216         if (!ret)
10217                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10218         if (ret) {
10219                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10220                 goto fail;
10221         }
10222
10223         ret = drm_atomic_commit(state);
10224         if (ret) {
10225                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10226                 goto fail;
10227         }
10228
10229         old->restore_state = restore_state;
10230         drm_atomic_state_put(state);
10231
10232         /* let the connector get through one full cycle before testing */
10233         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10234         return true;
10235
10236 fail:
10237         if (state) {
10238                 drm_atomic_state_put(state);
10239                 state = NULL;
10240         }
10241         if (restore_state) {
10242                 drm_atomic_state_put(restore_state);
10243                 restore_state = NULL;
10244         }
10245
10246         if (ret == -EDEADLK)
10247                 return ret;
10248
10249         return false;
10250 }
10251
10252 void intel_release_load_detect_pipe(struct drm_connector *connector,
10253                                     struct intel_load_detect_pipe *old,
10254                                     struct drm_modeset_acquire_ctx *ctx)
10255 {
10256         struct intel_encoder *intel_encoder =
10257                 intel_attached_encoder(connector);
10258         struct drm_encoder *encoder = &intel_encoder->base;
10259         struct drm_atomic_state *state = old->restore_state;
10260         int ret;
10261
10262         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10263                       connector->base.id, connector->name,
10264                       encoder->base.id, encoder->name);
10265
10266         if (!state)
10267                 return;
10268
10269         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10270         if (ret)
10271                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10272         drm_atomic_state_put(state);
10273 }
10274
10275 static int i9xx_pll_refclk(struct drm_device *dev,
10276                            const struct intel_crtc_state *pipe_config)
10277 {
10278         struct drm_i915_private *dev_priv = to_i915(dev);
10279         u32 dpll = pipe_config->dpll_hw_state.dpll;
10280
10281         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10282                 return dev_priv->vbt.lvds_ssc_freq;
10283         else if (HAS_PCH_SPLIT(dev_priv))
10284                 return 120000;
10285         else if (!IS_GEN2(dev_priv))
10286                 return 96000;
10287         else
10288                 return 48000;
10289 }
10290
10291 /* Returns the clock of the currently programmed mode of the given pipe. */
10292 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10293                                 struct intel_crtc_state *pipe_config)
10294 {
10295         struct drm_device *dev = crtc->base.dev;
10296         struct drm_i915_private *dev_priv = to_i915(dev);
10297         int pipe = pipe_config->cpu_transcoder;
10298         u32 dpll = pipe_config->dpll_hw_state.dpll;
10299         u32 fp;
10300         struct dpll clock;
10301         int port_clock;
10302         int refclk = i9xx_pll_refclk(dev, pipe_config);
10303
10304         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10305                 fp = pipe_config->dpll_hw_state.fp0;
10306         else
10307                 fp = pipe_config->dpll_hw_state.fp1;
10308
10309         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10310         if (IS_PINEVIEW(dev_priv)) {
10311                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10312                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10313         } else {
10314                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10315                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10316         }
10317
10318         if (!IS_GEN2(dev_priv)) {
10319                 if (IS_PINEVIEW(dev_priv))
10320                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10321                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10322                 else
10323                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10324                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10325
10326                 switch (dpll & DPLL_MODE_MASK) {
10327                 case DPLLB_MODE_DAC_SERIAL:
10328                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10329                                 5 : 10;
10330                         break;
10331                 case DPLLB_MODE_LVDS:
10332                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10333                                 7 : 14;
10334                         break;
10335                 default:
10336                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10337                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10338                         return;
10339                 }
10340
10341                 if (IS_PINEVIEW(dev_priv))
10342                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10343                 else
10344                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10345         } else {
10346                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10347                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10348
10349                 if (is_lvds) {
10350                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10351                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10352
10353                         if (lvds & LVDS_CLKB_POWER_UP)
10354                                 clock.p2 = 7;
10355                         else
10356                                 clock.p2 = 14;
10357                 } else {
10358                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10359                                 clock.p1 = 2;
10360                         else {
10361                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10362                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10363                         }
10364                         if (dpll & PLL_P2_DIVIDE_BY_4)
10365                                 clock.p2 = 4;
10366                         else
10367                                 clock.p2 = 2;
10368                 }
10369
10370                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10371         }
10372
10373         /*
10374          * This value includes pixel_multiplier. We will use
10375          * port_clock to compute adjusted_mode.crtc_clock in the
10376          * encoder's get_config() function.
10377          */
10378         pipe_config->port_clock = port_clock;
10379 }
10380
10381 int intel_dotclock_calculate(int link_freq,
10382                              const struct intel_link_m_n *m_n)
10383 {
10384         /*
10385          * The calculation for the data clock is:
10386          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10387          * But we want to avoid losing precison if possible, so:
10388          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10389          *
10390          * and the link clock is simpler:
10391          * link_clock = (m * link_clock) / n
10392          */
10393
10394         if (!m_n->link_n)
10395                 return 0;
10396
10397         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10398 }
10399
10400 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10401                                    struct intel_crtc_state *pipe_config)
10402 {
10403         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10404
10405         /* read out port_clock from the DPLL */
10406         i9xx_crtc_clock_get(crtc, pipe_config);
10407
10408         /*
10409          * In case there is an active pipe without active ports,
10410          * we may need some idea for the dotclock anyway.
10411          * Calculate one based on the FDI configuration.
10412          */
10413         pipe_config->base.adjusted_mode.crtc_clock =
10414                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10415                                          &pipe_config->fdi_m_n);
10416 }
10417
10418 /* Returns the currently programmed mode of the given encoder. */
10419 struct drm_display_mode *
10420 intel_encoder_current_mode(struct intel_encoder *encoder)
10421 {
10422         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10423         struct intel_crtc_state *crtc_state;
10424         struct drm_display_mode *mode;
10425         struct intel_crtc *crtc;
10426         enum pipe pipe;
10427
10428         if (!encoder->get_hw_state(encoder, &pipe))
10429                 return NULL;
10430
10431         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10432
10433         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10434         if (!mode)
10435                 return NULL;
10436
10437         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10438         if (!crtc_state) {
10439                 kfree(mode);
10440                 return NULL;
10441         }
10442
10443         crtc_state->base.crtc = &crtc->base;
10444
10445         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10446                 kfree(crtc_state);
10447                 kfree(mode);
10448                 return NULL;
10449         }
10450
10451         encoder->get_config(encoder, crtc_state);
10452
10453         intel_mode_from_pipe_config(mode, crtc_state);
10454
10455         kfree(crtc_state);
10456
10457         return mode;
10458 }
10459
10460 static void intel_crtc_destroy(struct drm_crtc *crtc)
10461 {
10462         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10463
10464         drm_crtc_cleanup(crtc);
10465         kfree(intel_crtc);
10466 }
10467
10468 /**
10469  * intel_wm_need_update - Check whether watermarks need updating
10470  * @plane: drm plane
10471  * @state: new plane state
10472  *
10473  * Check current plane state versus the new one to determine whether
10474  * watermarks need to be recalculated.
10475  *
10476  * Returns true or false.
10477  */
10478 static bool intel_wm_need_update(struct drm_plane *plane,
10479                                  struct drm_plane_state *state)
10480 {
10481         struct intel_plane_state *new = to_intel_plane_state(state);
10482         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10483
10484         /* Update watermarks on tiling or size changes. */
10485         if (new->base.visible != cur->base.visible)
10486                 return true;
10487
10488         if (!cur->base.fb || !new->base.fb)
10489                 return false;
10490
10491         if (cur->base.fb->modifier != new->base.fb->modifier ||
10492             cur->base.rotation != new->base.rotation ||
10493             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10494             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10495             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10496             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10497                 return true;
10498
10499         return false;
10500 }
10501
10502 static bool needs_scaling(const struct intel_plane_state *state)
10503 {
10504         int src_w = drm_rect_width(&state->base.src) >> 16;
10505         int src_h = drm_rect_height(&state->base.src) >> 16;
10506         int dst_w = drm_rect_width(&state->base.dst);
10507         int dst_h = drm_rect_height(&state->base.dst);
10508
10509         return (src_w != dst_w || src_h != dst_h);
10510 }
10511
10512 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10513                                     struct drm_crtc_state *crtc_state,
10514                                     const struct intel_plane_state *old_plane_state,
10515                                     struct drm_plane_state *plane_state)
10516 {
10517         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10518         struct drm_crtc *crtc = crtc_state->crtc;
10519         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10520         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10521         struct drm_device *dev = crtc->dev;
10522         struct drm_i915_private *dev_priv = to_i915(dev);
10523         bool mode_changed = needs_modeset(crtc_state);
10524         bool was_crtc_enabled = old_crtc_state->base.active;
10525         bool is_crtc_enabled = crtc_state->active;
10526         bool turn_off, turn_on, visible, was_visible;
10527         struct drm_framebuffer *fb = plane_state->fb;
10528         int ret;
10529
10530         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10531                 ret = skl_update_scaler_plane(
10532                         to_intel_crtc_state(crtc_state),
10533                         to_intel_plane_state(plane_state));
10534                 if (ret)
10535                         return ret;
10536         }
10537
10538         was_visible = old_plane_state->base.visible;
10539         visible = plane_state->visible;
10540
10541         if (!was_crtc_enabled && WARN_ON(was_visible))
10542                 was_visible = false;
10543
10544         /*
10545          * Visibility is calculated as if the crtc was on, but
10546          * after scaler setup everything depends on it being off
10547          * when the crtc isn't active.
10548          *
10549          * FIXME this is wrong for watermarks. Watermarks should also
10550          * be computed as if the pipe would be active. Perhaps move
10551          * per-plane wm computation to the .check_plane() hook, and
10552          * only combine the results from all planes in the current place?
10553          */
10554         if (!is_crtc_enabled) {
10555                 plane_state->visible = visible = false;
10556                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10557         }
10558
10559         if (!was_visible && !visible)
10560                 return 0;
10561
10562         if (fb != old_plane_state->base.fb)
10563                 pipe_config->fb_changed = true;
10564
10565         turn_off = was_visible && (!visible || mode_changed);
10566         turn_on = visible && (!was_visible || mode_changed);
10567
10568         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10569                          intel_crtc->base.base.id, intel_crtc->base.name,
10570                          plane->base.base.id, plane->base.name,
10571                          fb ? fb->base.id : -1);
10572
10573         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10574                          plane->base.base.id, plane->base.name,
10575                          was_visible, visible,
10576                          turn_off, turn_on, mode_changed);
10577
10578         if (turn_on) {
10579                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10580                         pipe_config->update_wm_pre = true;
10581
10582                 /* must disable cxsr around plane enable/disable */
10583                 if (plane->id != PLANE_CURSOR)
10584                         pipe_config->disable_cxsr = true;
10585         } else if (turn_off) {
10586                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10587                         pipe_config->update_wm_post = true;
10588
10589                 /* must disable cxsr around plane enable/disable */
10590                 if (plane->id != PLANE_CURSOR)
10591                         pipe_config->disable_cxsr = true;
10592         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10593                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10594                         /* FIXME bollocks */
10595                         pipe_config->update_wm_pre = true;
10596                         pipe_config->update_wm_post = true;
10597                 }
10598         }
10599
10600         if (visible || was_visible)
10601                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10602
10603         /*
10604          * WaCxSRDisabledForSpriteScaling:ivb
10605          *
10606          * cstate->update_wm was already set above, so this flag will
10607          * take effect when we commit and program watermarks.
10608          */
10609         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10610             needs_scaling(to_intel_plane_state(plane_state)) &&
10611             !needs_scaling(old_plane_state))
10612                 pipe_config->disable_lp_wm = true;
10613
10614         return 0;
10615 }
10616
10617 static bool encoders_cloneable(const struct intel_encoder *a,
10618                                const struct intel_encoder *b)
10619 {
10620         /* masks could be asymmetric, so check both ways */
10621         return a == b || (a->cloneable & (1 << b->type) &&
10622                           b->cloneable & (1 << a->type));
10623 }
10624
10625 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10626                                          struct intel_crtc *crtc,
10627                                          struct intel_encoder *encoder)
10628 {
10629         struct intel_encoder *source_encoder;
10630         struct drm_connector *connector;
10631         struct drm_connector_state *connector_state;
10632         int i;
10633
10634         for_each_new_connector_in_state(state, connector, connector_state, i) {
10635                 if (connector_state->crtc != &crtc->base)
10636                         continue;
10637
10638                 source_encoder =
10639                         to_intel_encoder(connector_state->best_encoder);
10640                 if (!encoders_cloneable(encoder, source_encoder))
10641                         return false;
10642         }
10643
10644         return true;
10645 }
10646
10647 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10648                                    struct drm_crtc_state *crtc_state)
10649 {
10650         struct drm_device *dev = crtc->dev;
10651         struct drm_i915_private *dev_priv = to_i915(dev);
10652         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10653         struct intel_crtc_state *pipe_config =
10654                 to_intel_crtc_state(crtc_state);
10655         struct drm_atomic_state *state = crtc_state->state;
10656         int ret;
10657         bool mode_changed = needs_modeset(crtc_state);
10658
10659         if (mode_changed && !crtc_state->active)
10660                 pipe_config->update_wm_post = true;
10661
10662         if (mode_changed && crtc_state->enable &&
10663             dev_priv->display.crtc_compute_clock &&
10664             !WARN_ON(pipe_config->shared_dpll)) {
10665                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10666                                                            pipe_config);
10667                 if (ret)
10668                         return ret;
10669         }
10670
10671         if (crtc_state->color_mgmt_changed) {
10672                 ret = intel_color_check(crtc, crtc_state);
10673                 if (ret)
10674                         return ret;
10675
10676                 /*
10677                  * Changing color management on Intel hardware is
10678                  * handled as part of planes update.
10679                  */
10680                 crtc_state->planes_changed = true;
10681         }
10682
10683         ret = 0;
10684         if (dev_priv->display.compute_pipe_wm) {
10685                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10686                 if (ret) {
10687                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10688                         return ret;
10689                 }
10690         }
10691
10692         if (dev_priv->display.compute_intermediate_wm &&
10693             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10694                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10695                         return 0;
10696
10697                 /*
10698                  * Calculate 'intermediate' watermarks that satisfy both the
10699                  * old state and the new state.  We can program these
10700                  * immediately.
10701                  */
10702                 ret = dev_priv->display.compute_intermediate_wm(dev,
10703                                                                 intel_crtc,
10704                                                                 pipe_config);
10705                 if (ret) {
10706                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10707                         return ret;
10708                 }
10709         } else if (dev_priv->display.compute_intermediate_wm) {
10710                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10711                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10712         }
10713
10714         if (INTEL_GEN(dev_priv) >= 9) {
10715                 if (mode_changed)
10716                         ret = skl_update_scaler_crtc(pipe_config);
10717
10718                 if (!ret)
10719                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10720                                                             pipe_config);
10721                 if (!ret)
10722                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10723                                                          pipe_config);
10724         }
10725
10726         if (HAS_IPS(dev_priv))
10727                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10728
10729         return ret;
10730 }
10731
10732 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10733         .atomic_begin = intel_begin_crtc_commit,
10734         .atomic_flush = intel_finish_crtc_commit,
10735         .atomic_check = intel_crtc_atomic_check,
10736 };
10737
10738 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10739 {
10740         struct intel_connector *connector;
10741         struct drm_connector_list_iter conn_iter;
10742
10743         drm_connector_list_iter_begin(dev, &conn_iter);
10744         for_each_intel_connector_iter(connector, &conn_iter) {
10745                 if (connector->base.state->crtc)
10746                         drm_connector_put(&connector->base);
10747
10748                 if (connector->base.encoder) {
10749                         connector->base.state->best_encoder =
10750                                 connector->base.encoder;
10751                         connector->base.state->crtc =
10752                                 connector->base.encoder->crtc;
10753
10754                         drm_connector_get(&connector->base);
10755                 } else {
10756                         connector->base.state->best_encoder = NULL;
10757                         connector->base.state->crtc = NULL;
10758                 }
10759         }
10760         drm_connector_list_iter_end(&conn_iter);
10761 }
10762
10763 static void
10764 connected_sink_compute_bpp(struct intel_connector *connector,
10765                            struct intel_crtc_state *pipe_config)
10766 {
10767         const struct drm_display_info *info = &connector->base.display_info;
10768         int bpp = pipe_config->pipe_bpp;
10769
10770         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10771                       connector->base.base.id,
10772                       connector->base.name);
10773
10774         /* Don't use an invalid EDID bpc value */
10775         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10776                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10777                               bpp, info->bpc * 3);
10778                 pipe_config->pipe_bpp = info->bpc * 3;
10779         }
10780
10781         /* Clamp bpp to 8 on screens without EDID 1.4 */
10782         if (info->bpc == 0 && bpp > 24) {
10783                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10784                               bpp);
10785                 pipe_config->pipe_bpp = 24;
10786         }
10787 }
10788
10789 static int
10790 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10791                           struct intel_crtc_state *pipe_config)
10792 {
10793         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10794         struct drm_atomic_state *state;
10795         struct drm_connector *connector;
10796         struct drm_connector_state *connector_state;
10797         int bpp, i;
10798
10799         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10800             IS_CHERRYVIEW(dev_priv)))
10801                 bpp = 10*3;
10802         else if (INTEL_GEN(dev_priv) >= 5)
10803                 bpp = 12*3;
10804         else
10805                 bpp = 8*3;
10806
10807
10808         pipe_config->pipe_bpp = bpp;
10809
10810         state = pipe_config->base.state;
10811
10812         /* Clamp display bpp to EDID value */
10813         for_each_new_connector_in_state(state, connector, connector_state, i) {
10814                 if (connector_state->crtc != &crtc->base)
10815                         continue;
10816
10817                 connected_sink_compute_bpp(to_intel_connector(connector),
10818                                            pipe_config);
10819         }
10820
10821         return bpp;
10822 }
10823
10824 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10825 {
10826         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10827                         "type: 0x%x flags: 0x%x\n",
10828                 mode->crtc_clock,
10829                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10830                 mode->crtc_hsync_end, mode->crtc_htotal,
10831                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10832                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10833 }
10834
10835 static inline void
10836 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10837                       unsigned int lane_count, struct intel_link_m_n *m_n)
10838 {
10839         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10840                       id, lane_count,
10841                       m_n->gmch_m, m_n->gmch_n,
10842                       m_n->link_m, m_n->link_n, m_n->tu);
10843 }
10844
10845 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10846
10847 static const char * const output_type_str[] = {
10848         OUTPUT_TYPE(UNUSED),
10849         OUTPUT_TYPE(ANALOG),
10850         OUTPUT_TYPE(DVO),
10851         OUTPUT_TYPE(SDVO),
10852         OUTPUT_TYPE(LVDS),
10853         OUTPUT_TYPE(TVOUT),
10854         OUTPUT_TYPE(HDMI),
10855         OUTPUT_TYPE(DP),
10856         OUTPUT_TYPE(EDP),
10857         OUTPUT_TYPE(DSI),
10858         OUTPUT_TYPE(DDI),
10859         OUTPUT_TYPE(DP_MST),
10860 };
10861
10862 #undef OUTPUT_TYPE
10863
10864 static void snprintf_output_types(char *buf, size_t len,
10865                                   unsigned int output_types)
10866 {
10867         char *str = buf;
10868         int i;
10869
10870         str[0] = '\0';
10871
10872         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10873                 int r;
10874
10875                 if ((output_types & BIT(i)) == 0)
10876                         continue;
10877
10878                 r = snprintf(str, len, "%s%s",
10879                              str != buf ? "," : "", output_type_str[i]);
10880                 if (r >= len)
10881                         break;
10882                 str += r;
10883                 len -= r;
10884
10885                 output_types &= ~BIT(i);
10886         }
10887
10888         WARN_ON_ONCE(output_types != 0);
10889 }
10890
10891 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10892                                    struct intel_crtc_state *pipe_config,
10893                                    const char *context)
10894 {
10895         struct drm_device *dev = crtc->base.dev;
10896         struct drm_i915_private *dev_priv = to_i915(dev);
10897         struct drm_plane *plane;
10898         struct intel_plane *intel_plane;
10899         struct intel_plane_state *state;
10900         struct drm_framebuffer *fb;
10901         char buf[64];
10902
10903         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10904                       crtc->base.base.id, crtc->base.name, context);
10905
10906         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10907         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10908                       buf, pipe_config->output_types);
10909
10910         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10911                       transcoder_name(pipe_config->cpu_transcoder),
10912                       pipe_config->pipe_bpp, pipe_config->dither);
10913
10914         if (pipe_config->has_pch_encoder)
10915                 intel_dump_m_n_config(pipe_config, "fdi",
10916                                       pipe_config->fdi_lanes,
10917                                       &pipe_config->fdi_m_n);
10918
10919         if (pipe_config->ycbcr420)
10920                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10921
10922         if (intel_crtc_has_dp_encoder(pipe_config)) {
10923                 intel_dump_m_n_config(pipe_config, "dp m_n",
10924                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10925                 if (pipe_config->has_drrs)
10926                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10927                                               pipe_config->lane_count,
10928                                               &pipe_config->dp_m2_n2);
10929         }
10930
10931         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10932                       pipe_config->has_audio, pipe_config->has_infoframe);
10933
10934         DRM_DEBUG_KMS("requested mode:\n");
10935         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10936         DRM_DEBUG_KMS("adjusted mode:\n");
10937         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10938         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10939         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10940                       pipe_config->port_clock,
10941                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10942                       pipe_config->pixel_rate);
10943
10944         if (INTEL_GEN(dev_priv) >= 9)
10945                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10946                               crtc->num_scalers,
10947                               pipe_config->scaler_state.scaler_users,
10948                               pipe_config->scaler_state.scaler_id);
10949
10950         if (HAS_GMCH_DISPLAY(dev_priv))
10951                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10952                               pipe_config->gmch_pfit.control,
10953                               pipe_config->gmch_pfit.pgm_ratios,
10954                               pipe_config->gmch_pfit.lvds_border_bits);
10955         else
10956                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10957                               pipe_config->pch_pfit.pos,
10958                               pipe_config->pch_pfit.size,
10959                               enableddisabled(pipe_config->pch_pfit.enabled));
10960
10961         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10962                       pipe_config->ips_enabled, pipe_config->double_wide);
10963
10964         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10965
10966         DRM_DEBUG_KMS("planes on this crtc\n");
10967         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10968                 struct drm_format_name_buf format_name;
10969                 intel_plane = to_intel_plane(plane);
10970                 if (intel_plane->pipe != crtc->pipe)
10971                         continue;
10972
10973                 state = to_intel_plane_state(plane->state);
10974                 fb = state->base.fb;
10975                 if (!fb) {
10976                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10977                                       plane->base.id, plane->name, state->scaler_id);
10978                         continue;
10979                 }
10980
10981                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10982                               plane->base.id, plane->name,
10983                               fb->base.id, fb->width, fb->height,
10984                               drm_get_format_name(fb->format->format, &format_name));
10985                 if (INTEL_GEN(dev_priv) >= 9)
10986                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10987                                       state->scaler_id,
10988                                       state->base.src.x1 >> 16,
10989                                       state->base.src.y1 >> 16,
10990                                       drm_rect_width(&state->base.src) >> 16,
10991                                       drm_rect_height(&state->base.src) >> 16,
10992                                       state->base.dst.x1, state->base.dst.y1,
10993                                       drm_rect_width(&state->base.dst),
10994                                       drm_rect_height(&state->base.dst));
10995         }
10996 }
10997
10998 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10999 {
11000         struct drm_device *dev = state->dev;
11001         struct drm_connector *connector;
11002         struct drm_connector_list_iter conn_iter;
11003         unsigned int used_ports = 0;
11004         unsigned int used_mst_ports = 0;
11005         bool ret = true;
11006
11007         /*
11008          * Walk the connector list instead of the encoder
11009          * list to detect the problem on ddi platforms
11010          * where there's just one encoder per digital port.
11011          */
11012         drm_connector_list_iter_begin(dev, &conn_iter);
11013         drm_for_each_connector_iter(connector, &conn_iter) {
11014                 struct drm_connector_state *connector_state;
11015                 struct intel_encoder *encoder;
11016
11017                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11018                 if (!connector_state)
11019                         connector_state = connector->state;
11020
11021                 if (!connector_state->best_encoder)
11022                         continue;
11023
11024                 encoder = to_intel_encoder(connector_state->best_encoder);
11025
11026                 WARN_ON(!connector_state->crtc);
11027
11028                 switch (encoder->type) {
11029                         unsigned int port_mask;
11030                 case INTEL_OUTPUT_DDI:
11031                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11032                                 break;
11033                         /* else: fall through */
11034                 case INTEL_OUTPUT_DP:
11035                 case INTEL_OUTPUT_HDMI:
11036                 case INTEL_OUTPUT_EDP:
11037                         port_mask = 1 << encoder->port;
11038
11039                         /* the same port mustn't appear more than once */
11040                         if (used_ports & port_mask)
11041                                 ret = false;
11042
11043                         used_ports |= port_mask;
11044                         break;
11045                 case INTEL_OUTPUT_DP_MST:
11046                         used_mst_ports |=
11047                                 1 << encoder->port;
11048                         break;
11049                 default:
11050                         break;
11051                 }
11052         }
11053         drm_connector_list_iter_end(&conn_iter);
11054
11055         /* can't mix MST and SST/HDMI on the same port */
11056         if (used_ports & used_mst_ports)
11057                 return false;
11058
11059         return ret;
11060 }
11061
11062 static void
11063 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11064 {
11065         struct drm_i915_private *dev_priv =
11066                 to_i915(crtc_state->base.crtc->dev);
11067         struct intel_crtc_scaler_state scaler_state;
11068         struct intel_dpll_hw_state dpll_hw_state;
11069         struct intel_shared_dpll *shared_dpll;
11070         struct intel_crtc_wm_state wm_state;
11071         bool force_thru, ips_force_disable;
11072
11073         /* FIXME: before the switch to atomic started, a new pipe_config was
11074          * kzalloc'd. Code that depends on any field being zero should be
11075          * fixed, so that the crtc_state can be safely duplicated. For now,
11076          * only fields that are know to not cause problems are preserved. */
11077
11078         scaler_state = crtc_state->scaler_state;
11079         shared_dpll = crtc_state->shared_dpll;
11080         dpll_hw_state = crtc_state->dpll_hw_state;
11081         force_thru = crtc_state->pch_pfit.force_thru;
11082         ips_force_disable = crtc_state->ips_force_disable;
11083         if (IS_G4X(dev_priv) ||
11084             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11085                 wm_state = crtc_state->wm;
11086
11087         /* Keep base drm_crtc_state intact, only clear our extended struct */
11088         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11089         memset(&crtc_state->base + 1, 0,
11090                sizeof(*crtc_state) - sizeof(crtc_state->base));
11091
11092         crtc_state->scaler_state = scaler_state;
11093         crtc_state->shared_dpll = shared_dpll;
11094         crtc_state->dpll_hw_state = dpll_hw_state;
11095         crtc_state->pch_pfit.force_thru = force_thru;
11096         crtc_state->ips_force_disable = ips_force_disable;
11097         if (IS_G4X(dev_priv) ||
11098             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11099                 crtc_state->wm = wm_state;
11100 }
11101
11102 static int
11103 intel_modeset_pipe_config(struct drm_crtc *crtc,
11104                           struct intel_crtc_state *pipe_config)
11105 {
11106         struct drm_atomic_state *state = pipe_config->base.state;
11107         struct intel_encoder *encoder;
11108         struct drm_connector *connector;
11109         struct drm_connector_state *connector_state;
11110         int base_bpp, ret = -EINVAL;
11111         int i;
11112         bool retry = true;
11113
11114         clear_intel_crtc_state(pipe_config);
11115
11116         pipe_config->cpu_transcoder =
11117                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11118
11119         /*
11120          * Sanitize sync polarity flags based on requested ones. If neither
11121          * positive or negative polarity is requested, treat this as meaning
11122          * negative polarity.
11123          */
11124         if (!(pipe_config->base.adjusted_mode.flags &
11125               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11126                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11127
11128         if (!(pipe_config->base.adjusted_mode.flags &
11129               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11130                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11131
11132         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11133                                              pipe_config);
11134         if (base_bpp < 0)
11135                 goto fail;
11136
11137         /*
11138          * Determine the real pipe dimensions. Note that stereo modes can
11139          * increase the actual pipe size due to the frame doubling and
11140          * insertion of additional space for blanks between the frame. This
11141          * is stored in the crtc timings. We use the requested mode to do this
11142          * computation to clearly distinguish it from the adjusted mode, which
11143          * can be changed by the connectors in the below retry loop.
11144          */
11145         drm_mode_get_hv_timing(&pipe_config->base.mode,
11146                                &pipe_config->pipe_src_w,
11147                                &pipe_config->pipe_src_h);
11148
11149         for_each_new_connector_in_state(state, connector, connector_state, i) {
11150                 if (connector_state->crtc != crtc)
11151                         continue;
11152
11153                 encoder = to_intel_encoder(connector_state->best_encoder);
11154
11155                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11156                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11157                         goto fail;
11158                 }
11159
11160                 /*
11161                  * Determine output_types before calling the .compute_config()
11162                  * hooks so that the hooks can use this information safely.
11163                  */
11164                 if (encoder->compute_output_type)
11165                         pipe_config->output_types |=
11166                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11167                                                                  connector_state));
11168                 else
11169                         pipe_config->output_types |= BIT(encoder->type);
11170         }
11171
11172 encoder_retry:
11173         /* Ensure the port clock defaults are reset when retrying. */
11174         pipe_config->port_clock = 0;
11175         pipe_config->pixel_multiplier = 1;
11176
11177         /* Fill in default crtc timings, allow encoders to overwrite them. */
11178         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11179                               CRTC_STEREO_DOUBLE);
11180
11181         /* Pass our mode to the connectors and the CRTC to give them a chance to
11182          * adjust it according to limitations or connector properties, and also
11183          * a chance to reject the mode entirely.
11184          */
11185         for_each_new_connector_in_state(state, connector, connector_state, i) {
11186                 if (connector_state->crtc != crtc)
11187                         continue;
11188
11189                 encoder = to_intel_encoder(connector_state->best_encoder);
11190
11191                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11192                         DRM_DEBUG_KMS("Encoder config failure\n");
11193                         goto fail;
11194                 }
11195         }
11196
11197         /* Set default port clock if not overwritten by the encoder. Needs to be
11198          * done afterwards in case the encoder adjusts the mode. */
11199         if (!pipe_config->port_clock)
11200                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11201                         * pipe_config->pixel_multiplier;
11202
11203         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11204         if (ret < 0) {
11205                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11206                 goto fail;
11207         }
11208
11209         if (ret == RETRY) {
11210                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11211                         ret = -EINVAL;
11212                         goto fail;
11213                 }
11214
11215                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11216                 retry = false;
11217                 goto encoder_retry;
11218         }
11219
11220         /* Dithering seems to not pass-through bits correctly when it should, so
11221          * only enable it on 6bpc panels and when its not a compliance
11222          * test requesting 6bpc video pattern.
11223          */
11224         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11225                 !pipe_config->dither_force_disable;
11226         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11227                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11228
11229 fail:
11230         return ret;
11231 }
11232
11233 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11234 {
11235         int diff;
11236
11237         if (clock1 == clock2)
11238                 return true;
11239
11240         if (!clock1 || !clock2)
11241                 return false;
11242
11243         diff = abs(clock1 - clock2);
11244
11245         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11246                 return true;
11247
11248         return false;
11249 }
11250
11251 static bool
11252 intel_compare_m_n(unsigned int m, unsigned int n,
11253                   unsigned int m2, unsigned int n2,
11254                   bool exact)
11255 {
11256         if (m == m2 && n == n2)
11257                 return true;
11258
11259         if (exact || !m || !n || !m2 || !n2)
11260                 return false;
11261
11262         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11263
11264         if (n > n2) {
11265                 while (n > n2) {
11266                         m2 <<= 1;
11267                         n2 <<= 1;
11268                 }
11269         } else if (n < n2) {
11270                 while (n < n2) {
11271                         m <<= 1;
11272                         n <<= 1;
11273                 }
11274         }
11275
11276         if (n != n2)
11277                 return false;
11278
11279         return intel_fuzzy_clock_check(m, m2);
11280 }
11281
11282 static bool
11283 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11284                        struct intel_link_m_n *m2_n2,
11285                        bool adjust)
11286 {
11287         if (m_n->tu == m2_n2->tu &&
11288             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11289                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11290             intel_compare_m_n(m_n->link_m, m_n->link_n,
11291                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11292                 if (adjust)
11293                         *m2_n2 = *m_n;
11294
11295                 return true;
11296         }
11297
11298         return false;
11299 }
11300
11301 static void __printf(3, 4)
11302 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11303 {
11304         struct va_format vaf;
11305         va_list args;
11306
11307         va_start(args, format);
11308         vaf.fmt = format;
11309         vaf.va = &args;
11310
11311         if (adjust)
11312                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11313         else
11314                 drm_err("mismatch in %s %pV", name, &vaf);
11315
11316         va_end(args);
11317 }
11318
11319 static bool
11320 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11321                           struct intel_crtc_state *current_config,
11322                           struct intel_crtc_state *pipe_config,
11323                           bool adjust)
11324 {
11325         bool ret = true;
11326         bool fixup_inherited = adjust &&
11327                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11328                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11329
11330 #define PIPE_CONF_CHECK_X(name) do { \
11331         if (current_config->name != pipe_config->name) { \
11332                 pipe_config_err(adjust, __stringify(name), \
11333                           "(expected 0x%08x, found 0x%08x)\n", \
11334                           current_config->name, \
11335                           pipe_config->name); \
11336                 ret = false; \
11337         } \
11338 } while (0)
11339
11340 #define PIPE_CONF_CHECK_I(name) do { \
11341         if (current_config->name != pipe_config->name) { \
11342                 pipe_config_err(adjust, __stringify(name), \
11343                           "(expected %i, found %i)\n", \
11344                           current_config->name, \
11345                           pipe_config->name); \
11346                 ret = false; \
11347         } \
11348 } while (0)
11349
11350 #define PIPE_CONF_CHECK_BOOL(name) do { \
11351         if (current_config->name != pipe_config->name) { \
11352                 pipe_config_err(adjust, __stringify(name), \
11353                           "(expected %s, found %s)\n", \
11354                           yesno(current_config->name), \
11355                           yesno(pipe_config->name)); \
11356                 ret = false; \
11357         } \
11358 } while (0)
11359
11360 /*
11361  * Checks state where we only read out the enabling, but not the entire
11362  * state itself (like full infoframes or ELD for audio). These states
11363  * require a full modeset on bootup to fix up.
11364  */
11365 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11366         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11367                 PIPE_CONF_CHECK_BOOL(name); \
11368         } else { \
11369                 pipe_config_err(adjust, __stringify(name), \
11370                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11371                           yesno(current_config->name), \
11372                           yesno(pipe_config->name)); \
11373                 ret = false; \
11374         } \
11375 } while (0)
11376
11377 #define PIPE_CONF_CHECK_P(name) do { \
11378         if (current_config->name != pipe_config->name) { \
11379                 pipe_config_err(adjust, __stringify(name), \
11380                           "(expected %p, found %p)\n", \
11381                           current_config->name, \
11382                           pipe_config->name); \
11383                 ret = false; \
11384         } \
11385 } while (0)
11386
11387 #define PIPE_CONF_CHECK_M_N(name) do { \
11388         if (!intel_compare_link_m_n(&current_config->name, \
11389                                     &pipe_config->name,\
11390                                     adjust)) { \
11391                 pipe_config_err(adjust, __stringify(name), \
11392                           "(expected tu %i gmch %i/%i link %i/%i, " \
11393                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11394                           current_config->name.tu, \
11395                           current_config->name.gmch_m, \
11396                           current_config->name.gmch_n, \
11397                           current_config->name.link_m, \
11398                           current_config->name.link_n, \
11399                           pipe_config->name.tu, \
11400                           pipe_config->name.gmch_m, \
11401                           pipe_config->name.gmch_n, \
11402                           pipe_config->name.link_m, \
11403                           pipe_config->name.link_n); \
11404                 ret = false; \
11405         } \
11406 } while (0)
11407
11408 /* This is required for BDW+ where there is only one set of registers for
11409  * switching between high and low RR.
11410  * This macro can be used whenever a comparison has to be made between one
11411  * hw state and multiple sw state variables.
11412  */
11413 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11414         if (!intel_compare_link_m_n(&current_config->name, \
11415                                     &pipe_config->name, adjust) && \
11416             !intel_compare_link_m_n(&current_config->alt_name, \
11417                                     &pipe_config->name, adjust)) { \
11418                 pipe_config_err(adjust, __stringify(name), \
11419                           "(expected tu %i gmch %i/%i link %i/%i, " \
11420                           "or tu %i gmch %i/%i link %i/%i, " \
11421                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11422                           current_config->name.tu, \
11423                           current_config->name.gmch_m, \
11424                           current_config->name.gmch_n, \
11425                           current_config->name.link_m, \
11426                           current_config->name.link_n, \
11427                           current_config->alt_name.tu, \
11428                           current_config->alt_name.gmch_m, \
11429                           current_config->alt_name.gmch_n, \
11430                           current_config->alt_name.link_m, \
11431                           current_config->alt_name.link_n, \
11432                           pipe_config->name.tu, \
11433                           pipe_config->name.gmch_m, \
11434                           pipe_config->name.gmch_n, \
11435                           pipe_config->name.link_m, \
11436                           pipe_config->name.link_n); \
11437                 ret = false; \
11438         } \
11439 } while (0)
11440
11441 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11442         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11443                 pipe_config_err(adjust, __stringify(name), \
11444                           "(%x) (expected %i, found %i)\n", \
11445                           (mask), \
11446                           current_config->name & (mask), \
11447                           pipe_config->name & (mask)); \
11448                 ret = false; \
11449         } \
11450 } while (0)
11451
11452 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11453         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11454                 pipe_config_err(adjust, __stringify(name), \
11455                           "(expected %i, found %i)\n", \
11456                           current_config->name, \
11457                           pipe_config->name); \
11458                 ret = false; \
11459         } \
11460 } while (0)
11461
11462 #define PIPE_CONF_QUIRK(quirk)  \
11463         ((current_config->quirks | pipe_config->quirks) & (quirk))
11464
11465         PIPE_CONF_CHECK_I(cpu_transcoder);
11466
11467         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11468         PIPE_CONF_CHECK_I(fdi_lanes);
11469         PIPE_CONF_CHECK_M_N(fdi_m_n);
11470
11471         PIPE_CONF_CHECK_I(lane_count);
11472         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11473
11474         if (INTEL_GEN(dev_priv) < 8) {
11475                 PIPE_CONF_CHECK_M_N(dp_m_n);
11476
11477                 if (current_config->has_drrs)
11478                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11479         } else
11480                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11481
11482         PIPE_CONF_CHECK_X(output_types);
11483
11484         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11485         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11486         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11487         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11488         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11489         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11490
11491         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11492         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11493         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11494         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11495         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11496         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11497
11498         PIPE_CONF_CHECK_I(pixel_multiplier);
11499         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11500         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11501             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11502                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11503
11504         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11505         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11506         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11507         PIPE_CONF_CHECK_BOOL(ycbcr420);
11508
11509         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11510
11511         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11512                               DRM_MODE_FLAG_INTERLACE);
11513
11514         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11515                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11516                                       DRM_MODE_FLAG_PHSYNC);
11517                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11518                                       DRM_MODE_FLAG_NHSYNC);
11519                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11520                                       DRM_MODE_FLAG_PVSYNC);
11521                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11522                                       DRM_MODE_FLAG_NVSYNC);
11523         }
11524
11525         PIPE_CONF_CHECK_X(gmch_pfit.control);
11526         /* pfit ratios are autocomputed by the hw on gen4+ */
11527         if (INTEL_GEN(dev_priv) < 4)
11528                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11529         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11530
11531         if (!adjust) {
11532                 PIPE_CONF_CHECK_I(pipe_src_w);
11533                 PIPE_CONF_CHECK_I(pipe_src_h);
11534
11535                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11536                 if (current_config->pch_pfit.enabled) {
11537                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11538                         PIPE_CONF_CHECK_X(pch_pfit.size);
11539                 }
11540
11541                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11542                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11543         }
11544
11545         PIPE_CONF_CHECK_BOOL(double_wide);
11546
11547         PIPE_CONF_CHECK_P(shared_dpll);
11548         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11549         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11550         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11551         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11552         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11553         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11554         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11555         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11556         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11557         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11558         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11559         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11560         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11561         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11562         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11563         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11564         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11565         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11566         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11567         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11568         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11569         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11570         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11571         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11572         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11573         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11574         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11575         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11576         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11577         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11578         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11579
11580         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11581         PIPE_CONF_CHECK_X(dsi_pll.div);
11582
11583         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11584                 PIPE_CONF_CHECK_I(pipe_bpp);
11585
11586         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11587         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11588
11589         PIPE_CONF_CHECK_I(min_voltage_level);
11590
11591 #undef PIPE_CONF_CHECK_X
11592 #undef PIPE_CONF_CHECK_I
11593 #undef PIPE_CONF_CHECK_BOOL
11594 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11595 #undef PIPE_CONF_CHECK_P
11596 #undef PIPE_CONF_CHECK_FLAGS
11597 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11598 #undef PIPE_CONF_QUIRK
11599
11600         return ret;
11601 }
11602
11603 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11604                                            const struct intel_crtc_state *pipe_config)
11605 {
11606         if (pipe_config->has_pch_encoder) {
11607                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11608                                                             &pipe_config->fdi_m_n);
11609                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11610
11611                 /*
11612                  * FDI already provided one idea for the dotclock.
11613                  * Yell if the encoder disagrees.
11614                  */
11615                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11616                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11617                      fdi_dotclock, dotclock);
11618         }
11619 }
11620
11621 static void verify_wm_state(struct drm_crtc *crtc,
11622                             struct drm_crtc_state *new_state)
11623 {
11624         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11625         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11626         struct skl_pipe_wm hw_wm, *sw_wm;
11627         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11628         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11629         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11630         const enum pipe pipe = intel_crtc->pipe;
11631         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11632
11633         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11634                 return;
11635
11636         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11637         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11638
11639         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11640         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11641
11642         if (INTEL_GEN(dev_priv) >= 11)
11643                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
11644                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
11645                                   sw_ddb->enabled_slices,
11646                                   hw_ddb.enabled_slices);
11647         /* planes */
11648         for_each_universal_plane(dev_priv, pipe, plane) {
11649                 hw_plane_wm = &hw_wm.planes[plane];
11650                 sw_plane_wm = &sw_wm->planes[plane];
11651
11652                 /* Watermarks */
11653                 for (level = 0; level <= max_level; level++) {
11654                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11655                                                 &sw_plane_wm->wm[level]))
11656                                 continue;
11657
11658                         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",
11659                                   pipe_name(pipe), plane + 1, level,
11660                                   sw_plane_wm->wm[level].plane_en,
11661                                   sw_plane_wm->wm[level].plane_res_b,
11662                                   sw_plane_wm->wm[level].plane_res_l,
11663                                   hw_plane_wm->wm[level].plane_en,
11664                                   hw_plane_wm->wm[level].plane_res_b,
11665                                   hw_plane_wm->wm[level].plane_res_l);
11666                 }
11667
11668                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11669                                          &sw_plane_wm->trans_wm)) {
11670                         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",
11671                                   pipe_name(pipe), plane + 1,
11672                                   sw_plane_wm->trans_wm.plane_en,
11673                                   sw_plane_wm->trans_wm.plane_res_b,
11674                                   sw_plane_wm->trans_wm.plane_res_l,
11675                                   hw_plane_wm->trans_wm.plane_en,
11676                                   hw_plane_wm->trans_wm.plane_res_b,
11677                                   hw_plane_wm->trans_wm.plane_res_l);
11678                 }
11679
11680                 /* DDB */
11681                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11682                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11683
11684                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11685                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11686                                   pipe_name(pipe), plane + 1,
11687                                   sw_ddb_entry->start, sw_ddb_entry->end,
11688                                   hw_ddb_entry->start, hw_ddb_entry->end);
11689                 }
11690         }
11691
11692         /*
11693          * cursor
11694          * If the cursor plane isn't active, we may not have updated it's ddb
11695          * allocation. In that case since the ddb allocation will be updated
11696          * once the plane becomes visible, we can skip this check
11697          */
11698         if (1) {
11699                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11700                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11701
11702                 /* Watermarks */
11703                 for (level = 0; level <= max_level; level++) {
11704                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11705                                                 &sw_plane_wm->wm[level]))
11706                                 continue;
11707
11708                         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",
11709                                   pipe_name(pipe), level,
11710                                   sw_plane_wm->wm[level].plane_en,
11711                                   sw_plane_wm->wm[level].plane_res_b,
11712                                   sw_plane_wm->wm[level].plane_res_l,
11713                                   hw_plane_wm->wm[level].plane_en,
11714                                   hw_plane_wm->wm[level].plane_res_b,
11715                                   hw_plane_wm->wm[level].plane_res_l);
11716                 }
11717
11718                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11719                                          &sw_plane_wm->trans_wm)) {
11720                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11721                                   pipe_name(pipe),
11722                                   sw_plane_wm->trans_wm.plane_en,
11723                                   sw_plane_wm->trans_wm.plane_res_b,
11724                                   sw_plane_wm->trans_wm.plane_res_l,
11725                                   hw_plane_wm->trans_wm.plane_en,
11726                                   hw_plane_wm->trans_wm.plane_res_b,
11727                                   hw_plane_wm->trans_wm.plane_res_l);
11728                 }
11729
11730                 /* DDB */
11731                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11732                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11733
11734                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11735                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11736                                   pipe_name(pipe),
11737                                   sw_ddb_entry->start, sw_ddb_entry->end,
11738                                   hw_ddb_entry->start, hw_ddb_entry->end);
11739                 }
11740         }
11741 }
11742
11743 static void
11744 verify_connector_state(struct drm_device *dev,
11745                        struct drm_atomic_state *state,
11746                        struct drm_crtc *crtc)
11747 {
11748         struct drm_connector *connector;
11749         struct drm_connector_state *new_conn_state;
11750         int i;
11751
11752         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11753                 struct drm_encoder *encoder = connector->encoder;
11754                 struct drm_crtc_state *crtc_state = NULL;
11755
11756                 if (new_conn_state->crtc != crtc)
11757                         continue;
11758
11759                 if (crtc)
11760                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11761
11762                 intel_connector_verify_state(crtc_state, new_conn_state);
11763
11764                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11765                      "connector's atomic encoder doesn't match legacy encoder\n");
11766         }
11767 }
11768
11769 static void
11770 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11771 {
11772         struct intel_encoder *encoder;
11773         struct drm_connector *connector;
11774         struct drm_connector_state *old_conn_state, *new_conn_state;
11775         int i;
11776
11777         for_each_intel_encoder(dev, encoder) {
11778                 bool enabled = false, found = false;
11779                 enum pipe pipe;
11780
11781                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11782                               encoder->base.base.id,
11783                               encoder->base.name);
11784
11785                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11786                                                    new_conn_state, i) {
11787                         if (old_conn_state->best_encoder == &encoder->base)
11788                                 found = true;
11789
11790                         if (new_conn_state->best_encoder != &encoder->base)
11791                                 continue;
11792                         found = enabled = true;
11793
11794                         I915_STATE_WARN(new_conn_state->crtc !=
11795                                         encoder->base.crtc,
11796                              "connector's crtc doesn't match encoder crtc\n");
11797                 }
11798
11799                 if (!found)
11800                         continue;
11801
11802                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11803                      "encoder's enabled state mismatch "
11804                      "(expected %i, found %i)\n",
11805                      !!encoder->base.crtc, enabled);
11806
11807                 if (!encoder->base.crtc) {
11808                         bool active;
11809
11810                         active = encoder->get_hw_state(encoder, &pipe);
11811                         I915_STATE_WARN(active,
11812                              "encoder detached but still enabled on pipe %c.\n",
11813                              pipe_name(pipe));
11814                 }
11815         }
11816 }
11817
11818 static void
11819 verify_crtc_state(struct drm_crtc *crtc,
11820                   struct drm_crtc_state *old_crtc_state,
11821                   struct drm_crtc_state *new_crtc_state)
11822 {
11823         struct drm_device *dev = crtc->dev;
11824         struct drm_i915_private *dev_priv = to_i915(dev);
11825         struct intel_encoder *encoder;
11826         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11827         struct intel_crtc_state *pipe_config, *sw_config;
11828         struct drm_atomic_state *old_state;
11829         bool active;
11830
11831         old_state = old_crtc_state->state;
11832         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11833         pipe_config = to_intel_crtc_state(old_crtc_state);
11834         memset(pipe_config, 0, sizeof(*pipe_config));
11835         pipe_config->base.crtc = crtc;
11836         pipe_config->base.state = old_state;
11837
11838         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11839
11840         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11841
11842         /* we keep both pipes enabled on 830 */
11843         if (IS_I830(dev_priv))
11844                 active = new_crtc_state->active;
11845
11846         I915_STATE_WARN(new_crtc_state->active != active,
11847              "crtc active state doesn't match with hw state "
11848              "(expected %i, found %i)\n", new_crtc_state->active, active);
11849
11850         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11851              "transitional active state does not match atomic hw state "
11852              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11853
11854         for_each_encoder_on_crtc(dev, crtc, encoder) {
11855                 enum pipe pipe;
11856
11857                 active = encoder->get_hw_state(encoder, &pipe);
11858                 I915_STATE_WARN(active != new_crtc_state->active,
11859                         "[ENCODER:%i] active %i with crtc active %i\n",
11860                         encoder->base.base.id, active, new_crtc_state->active);
11861
11862                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11863                                 "Encoder connected to wrong pipe %c\n",
11864                                 pipe_name(pipe));
11865
11866                 if (active)
11867                         encoder->get_config(encoder, pipe_config);
11868         }
11869
11870         intel_crtc_compute_pixel_rate(pipe_config);
11871
11872         if (!new_crtc_state->active)
11873                 return;
11874
11875         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11876
11877         sw_config = to_intel_crtc_state(new_crtc_state);
11878         if (!intel_pipe_config_compare(dev_priv, sw_config,
11879                                        pipe_config, false)) {
11880                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11881                 intel_dump_pipe_config(intel_crtc, pipe_config,
11882                                        "[hw state]");
11883                 intel_dump_pipe_config(intel_crtc, sw_config,
11884                                        "[sw state]");
11885         }
11886 }
11887
11888 static void
11889 intel_verify_planes(struct intel_atomic_state *state)
11890 {
11891         struct intel_plane *plane;
11892         const struct intel_plane_state *plane_state;
11893         int i;
11894
11895         for_each_new_intel_plane_in_state(state, plane,
11896                                           plane_state, i)
11897                 assert_plane(plane, plane_state->base.visible);
11898 }
11899
11900 static void
11901 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11902                          struct intel_shared_dpll *pll,
11903                          struct drm_crtc *crtc,
11904                          struct drm_crtc_state *new_state)
11905 {
11906         struct intel_dpll_hw_state dpll_hw_state;
11907         unsigned int crtc_mask;
11908         bool active;
11909
11910         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11911
11912         DRM_DEBUG_KMS("%s\n", pll->info->name);
11913
11914         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
11915
11916         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
11917                 I915_STATE_WARN(!pll->on && pll->active_mask,
11918                      "pll in active use but not on in sw tracking\n");
11919                 I915_STATE_WARN(pll->on && !pll->active_mask,
11920                      "pll is on but not used by any active crtc\n");
11921                 I915_STATE_WARN(pll->on != active,
11922                      "pll on state mismatch (expected %i, found %i)\n",
11923                      pll->on, active);
11924         }
11925
11926         if (!crtc) {
11927                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11928                                 "more active pll users than references: %x vs %x\n",
11929                                 pll->active_mask, pll->state.crtc_mask);
11930
11931                 return;
11932         }
11933
11934         crtc_mask = drm_crtc_mask(crtc);
11935
11936         if (new_state->active)
11937                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11938                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11939                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11940         else
11941                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11942                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11943                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11944
11945         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11946                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11947                         crtc_mask, pll->state.crtc_mask);
11948
11949         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11950                                           &dpll_hw_state,
11951                                           sizeof(dpll_hw_state)),
11952                         "pll hw state mismatch\n");
11953 }
11954
11955 static void
11956 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11957                          struct drm_crtc_state *old_crtc_state,
11958                          struct drm_crtc_state *new_crtc_state)
11959 {
11960         struct drm_i915_private *dev_priv = to_i915(dev);
11961         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11962         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11963
11964         if (new_state->shared_dpll)
11965                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11966
11967         if (old_state->shared_dpll &&
11968             old_state->shared_dpll != new_state->shared_dpll) {
11969                 unsigned int crtc_mask = drm_crtc_mask(crtc);
11970                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11971
11972                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11973                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11974                                 pipe_name(drm_crtc_index(crtc)));
11975                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11976                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11977                                 pipe_name(drm_crtc_index(crtc)));
11978         }
11979 }
11980
11981 static void
11982 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11983                           struct drm_atomic_state *state,
11984                           struct drm_crtc_state *old_state,
11985                           struct drm_crtc_state *new_state)
11986 {
11987         if (!needs_modeset(new_state) &&
11988             !to_intel_crtc_state(new_state)->update_pipe)
11989                 return;
11990
11991         verify_wm_state(crtc, new_state);
11992         verify_connector_state(crtc->dev, state, crtc);
11993         verify_crtc_state(crtc, old_state, new_state);
11994         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11995 }
11996
11997 static void
11998 verify_disabled_dpll_state(struct drm_device *dev)
11999 {
12000         struct drm_i915_private *dev_priv = to_i915(dev);
12001         int i;
12002
12003         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12004                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12005 }
12006
12007 static void
12008 intel_modeset_verify_disabled(struct drm_device *dev,
12009                               struct drm_atomic_state *state)
12010 {
12011         verify_encoder_state(dev, state);
12012         verify_connector_state(dev, state, NULL);
12013         verify_disabled_dpll_state(dev);
12014 }
12015
12016 static void update_scanline_offset(struct intel_crtc *crtc)
12017 {
12018         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12019
12020         /*
12021          * The scanline counter increments at the leading edge of hsync.
12022          *
12023          * On most platforms it starts counting from vtotal-1 on the
12024          * first active line. That means the scanline counter value is
12025          * always one less than what we would expect. Ie. just after
12026          * start of vblank, which also occurs at start of hsync (on the
12027          * last active line), the scanline counter will read vblank_start-1.
12028          *
12029          * On gen2 the scanline counter starts counting from 1 instead
12030          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12031          * to keep the value positive), instead of adding one.
12032          *
12033          * On HSW+ the behaviour of the scanline counter depends on the output
12034          * type. For DP ports it behaves like most other platforms, but on HDMI
12035          * there's an extra 1 line difference. So we need to add two instead of
12036          * one to the value.
12037          *
12038          * On VLV/CHV DSI the scanline counter would appear to increment
12039          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12040          * that means we can't tell whether we're in vblank or not while
12041          * we're on that particular line. We must still set scanline_offset
12042          * to 1 so that the vblank timestamps come out correct when we query
12043          * the scanline counter from within the vblank interrupt handler.
12044          * However if queried just before the start of vblank we'll get an
12045          * answer that's slightly in the future.
12046          */
12047         if (IS_GEN2(dev_priv)) {
12048                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12049                 int vtotal;
12050
12051                 vtotal = adjusted_mode->crtc_vtotal;
12052                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12053                         vtotal /= 2;
12054
12055                 crtc->scanline_offset = vtotal - 1;
12056         } else if (HAS_DDI(dev_priv) &&
12057                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12058                 crtc->scanline_offset = 2;
12059         } else
12060                 crtc->scanline_offset = 1;
12061 }
12062
12063 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12064 {
12065         struct drm_device *dev = state->dev;
12066         struct drm_i915_private *dev_priv = to_i915(dev);
12067         struct drm_crtc *crtc;
12068         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12069         int i;
12070
12071         if (!dev_priv->display.crtc_compute_clock)
12072                 return;
12073
12074         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12075                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12076                 struct intel_shared_dpll *old_dpll =
12077                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12078
12079                 if (!needs_modeset(new_crtc_state))
12080                         continue;
12081
12082                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12083
12084                 if (!old_dpll)
12085                         continue;
12086
12087                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12088         }
12089 }
12090
12091 /*
12092  * This implements the workaround described in the "notes" section of the mode
12093  * set sequence documentation. When going from no pipes or single pipe to
12094  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12095  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12096  */
12097 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12098 {
12099         struct drm_crtc_state *crtc_state;
12100         struct intel_crtc *intel_crtc;
12101         struct drm_crtc *crtc;
12102         struct intel_crtc_state *first_crtc_state = NULL;
12103         struct intel_crtc_state *other_crtc_state = NULL;
12104         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12105         int i;
12106
12107         /* look at all crtc's that are going to be enabled in during modeset */
12108         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12109                 intel_crtc = to_intel_crtc(crtc);
12110
12111                 if (!crtc_state->active || !needs_modeset(crtc_state))
12112                         continue;
12113
12114                 if (first_crtc_state) {
12115                         other_crtc_state = to_intel_crtc_state(crtc_state);
12116                         break;
12117                 } else {
12118                         first_crtc_state = to_intel_crtc_state(crtc_state);
12119                         first_pipe = intel_crtc->pipe;
12120                 }
12121         }
12122
12123         /* No workaround needed? */
12124         if (!first_crtc_state)
12125                 return 0;
12126
12127         /* w/a possibly needed, check how many crtc's are already enabled. */
12128         for_each_intel_crtc(state->dev, intel_crtc) {
12129                 struct intel_crtc_state *pipe_config;
12130
12131                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12132                 if (IS_ERR(pipe_config))
12133                         return PTR_ERR(pipe_config);
12134
12135                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12136
12137                 if (!pipe_config->base.active ||
12138                     needs_modeset(&pipe_config->base))
12139                         continue;
12140
12141                 /* 2 or more enabled crtcs means no need for w/a */
12142                 if (enabled_pipe != INVALID_PIPE)
12143                         return 0;
12144
12145                 enabled_pipe = intel_crtc->pipe;
12146         }
12147
12148         if (enabled_pipe != INVALID_PIPE)
12149                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12150         else if (other_crtc_state)
12151                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12152
12153         return 0;
12154 }
12155
12156 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12157 {
12158         struct drm_crtc *crtc;
12159
12160         /* Add all pipes to the state */
12161         for_each_crtc(state->dev, crtc) {
12162                 struct drm_crtc_state *crtc_state;
12163
12164                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12165                 if (IS_ERR(crtc_state))
12166                         return PTR_ERR(crtc_state);
12167         }
12168
12169         return 0;
12170 }
12171
12172 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12173 {
12174         struct drm_crtc *crtc;
12175
12176         /*
12177          * Add all pipes to the state, and force
12178          * a modeset on all the active ones.
12179          */
12180         for_each_crtc(state->dev, crtc) {
12181                 struct drm_crtc_state *crtc_state;
12182                 int ret;
12183
12184                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12185                 if (IS_ERR(crtc_state))
12186                         return PTR_ERR(crtc_state);
12187
12188                 if (!crtc_state->active || needs_modeset(crtc_state))
12189                         continue;
12190
12191                 crtc_state->mode_changed = true;
12192
12193                 ret = drm_atomic_add_affected_connectors(state, crtc);
12194                 if (ret)
12195                         return ret;
12196
12197                 ret = drm_atomic_add_affected_planes(state, crtc);
12198                 if (ret)
12199                         return ret;
12200         }
12201
12202         return 0;
12203 }
12204
12205 static int intel_modeset_checks(struct drm_atomic_state *state)
12206 {
12207         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12208         struct drm_i915_private *dev_priv = to_i915(state->dev);
12209         struct drm_crtc *crtc;
12210         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12211         int ret = 0, i;
12212
12213         if (!check_digital_port_conflicts(state)) {
12214                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12215                 return -EINVAL;
12216         }
12217
12218         intel_state->modeset = true;
12219         intel_state->active_crtcs = dev_priv->active_crtcs;
12220         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12221         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12222
12223         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12224                 if (new_crtc_state->active)
12225                         intel_state->active_crtcs |= 1 << i;
12226                 else
12227                         intel_state->active_crtcs &= ~(1 << i);
12228
12229                 if (old_crtc_state->active != new_crtc_state->active)
12230                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12231         }
12232
12233         /*
12234          * See if the config requires any additional preparation, e.g.
12235          * to adjust global state with pipes off.  We need to do this
12236          * here so we can get the modeset_pipe updated config for the new
12237          * mode set on this crtc.  For other crtcs we need to use the
12238          * adjusted_mode bits in the crtc directly.
12239          */
12240         if (dev_priv->display.modeset_calc_cdclk) {
12241                 ret = dev_priv->display.modeset_calc_cdclk(state);
12242                 if (ret < 0)
12243                         return ret;
12244
12245                 /*
12246                  * Writes to dev_priv->cdclk.logical must protected by
12247                  * holding all the crtc locks, even if we don't end up
12248                  * touching the hardware
12249                  */
12250                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12251                                         &intel_state->cdclk.logical)) {
12252                         ret = intel_lock_all_pipes(state);
12253                         if (ret < 0)
12254                                 return ret;
12255                 }
12256
12257                 /* All pipes must be switched off while we change the cdclk. */
12258                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12259                                               &intel_state->cdclk.actual)) {
12260                         ret = intel_modeset_all_pipes(state);
12261                         if (ret < 0)
12262                                 return ret;
12263                 }
12264
12265                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12266                               intel_state->cdclk.logical.cdclk,
12267                               intel_state->cdclk.actual.cdclk);
12268                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12269                               intel_state->cdclk.logical.voltage_level,
12270                               intel_state->cdclk.actual.voltage_level);
12271         } else {
12272                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12273         }
12274
12275         intel_modeset_clear_plls(state);
12276
12277         if (IS_HASWELL(dev_priv))
12278                 return haswell_mode_set_planes_workaround(state);
12279
12280         return 0;
12281 }
12282
12283 /*
12284  * Handle calculation of various watermark data at the end of the atomic check
12285  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12286  * handlers to ensure that all derived state has been updated.
12287  */
12288 static int calc_watermark_data(struct drm_atomic_state *state)
12289 {
12290         struct drm_device *dev = state->dev;
12291         struct drm_i915_private *dev_priv = to_i915(dev);
12292
12293         /* Is there platform-specific watermark information to calculate? */
12294         if (dev_priv->display.compute_global_watermarks)
12295                 return dev_priv->display.compute_global_watermarks(state);
12296
12297         return 0;
12298 }
12299
12300 /**
12301  * intel_atomic_check - validate state object
12302  * @dev: drm device
12303  * @state: state to validate
12304  */
12305 static int intel_atomic_check(struct drm_device *dev,
12306                               struct drm_atomic_state *state)
12307 {
12308         struct drm_i915_private *dev_priv = to_i915(dev);
12309         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12310         struct drm_crtc *crtc;
12311         struct drm_crtc_state *old_crtc_state, *crtc_state;
12312         int ret, i;
12313         bool any_ms = false;
12314
12315         /* Catch I915_MODE_FLAG_INHERITED */
12316         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12317                                       crtc_state, i) {
12318                 if (crtc_state->mode.private_flags !=
12319                     old_crtc_state->mode.private_flags)
12320                         crtc_state->mode_changed = true;
12321         }
12322
12323         ret = drm_atomic_helper_check_modeset(dev, state);
12324         if (ret)
12325                 return ret;
12326
12327         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12328                 struct intel_crtc_state *pipe_config =
12329                         to_intel_crtc_state(crtc_state);
12330
12331                 if (!needs_modeset(crtc_state))
12332                         continue;
12333
12334                 if (!crtc_state->enable) {
12335                         any_ms = true;
12336                         continue;
12337                 }
12338
12339                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12340                 if (ret) {
12341                         intel_dump_pipe_config(to_intel_crtc(crtc),
12342                                                pipe_config, "[failed]");
12343                         return ret;
12344                 }
12345
12346                 if (i915_modparams.fastboot &&
12347                     intel_pipe_config_compare(dev_priv,
12348                                         to_intel_crtc_state(old_crtc_state),
12349                                         pipe_config, true)) {
12350                         crtc_state->mode_changed = false;
12351                         pipe_config->update_pipe = true;
12352                 }
12353
12354                 if (needs_modeset(crtc_state))
12355                         any_ms = true;
12356
12357                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12358                                        needs_modeset(crtc_state) ?
12359                                        "[modeset]" : "[fastset]");
12360         }
12361
12362         if (any_ms) {
12363                 ret = intel_modeset_checks(state);
12364
12365                 if (ret)
12366                         return ret;
12367         } else {
12368                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12369         }
12370
12371         ret = drm_atomic_helper_check_planes(dev, state);
12372         if (ret)
12373                 return ret;
12374
12375         intel_fbc_choose_crtc(dev_priv, intel_state);
12376         return calc_watermark_data(state);
12377 }
12378
12379 static int intel_atomic_prepare_commit(struct drm_device *dev,
12380                                        struct drm_atomic_state *state)
12381 {
12382         return drm_atomic_helper_prepare_planes(dev, state);
12383 }
12384
12385 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12386 {
12387         struct drm_device *dev = crtc->base.dev;
12388
12389         if (!dev->max_vblank_count)
12390                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12391
12392         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12393 }
12394
12395 static void intel_update_crtc(struct drm_crtc *crtc,
12396                               struct drm_atomic_state *state,
12397                               struct drm_crtc_state *old_crtc_state,
12398                               struct drm_crtc_state *new_crtc_state)
12399 {
12400         struct drm_device *dev = crtc->dev;
12401         struct drm_i915_private *dev_priv = to_i915(dev);
12402         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12403         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12404         bool modeset = needs_modeset(new_crtc_state);
12405         struct intel_plane_state *new_plane_state =
12406                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12407                                                  to_intel_plane(crtc->primary));
12408
12409         if (modeset) {
12410                 update_scanline_offset(intel_crtc);
12411                 dev_priv->display.crtc_enable(pipe_config, state);
12412
12413                 /* vblanks work again, re-enable pipe CRC. */
12414                 intel_crtc_enable_pipe_crc(intel_crtc);
12415         } else {
12416                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12417                                        pipe_config);
12418         }
12419
12420         if (new_plane_state)
12421                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12422
12423         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12424 }
12425
12426 static void intel_update_crtcs(struct drm_atomic_state *state)
12427 {
12428         struct drm_crtc *crtc;
12429         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12430         int i;
12431
12432         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12433                 if (!new_crtc_state->active)
12434                         continue;
12435
12436                 intel_update_crtc(crtc, state, old_crtc_state,
12437                                   new_crtc_state);
12438         }
12439 }
12440
12441 static void skl_update_crtcs(struct drm_atomic_state *state)
12442 {
12443         struct drm_i915_private *dev_priv = to_i915(state->dev);
12444         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12445         struct drm_crtc *crtc;
12446         struct intel_crtc *intel_crtc;
12447         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12448         struct intel_crtc_state *cstate;
12449         unsigned int updated = 0;
12450         bool progress;
12451         enum pipe pipe;
12452         int i;
12453         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12454         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12455
12456         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12457
12458         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12459                 /* ignore allocations for crtc's that have been turned off. */
12460                 if (new_crtc_state->active)
12461                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12462
12463         /* If 2nd DBuf slice required, enable it here */
12464         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12465                 icl_dbuf_slices_update(dev_priv, required_slices);
12466
12467         /*
12468          * Whenever the number of active pipes changes, we need to make sure we
12469          * update the pipes in the right order so that their ddb allocations
12470          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12471          * cause pipe underruns and other bad stuff.
12472          */
12473         do {
12474                 progress = false;
12475
12476                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12477                         bool vbl_wait = false;
12478                         unsigned int cmask = drm_crtc_mask(crtc);
12479
12480                         intel_crtc = to_intel_crtc(crtc);
12481                         cstate = to_intel_crtc_state(new_crtc_state);
12482                         pipe = intel_crtc->pipe;
12483
12484                         if (updated & cmask || !cstate->base.active)
12485                                 continue;
12486
12487                         if (skl_ddb_allocation_overlaps(dev_priv,
12488                                                         entries,
12489                                                         &cstate->wm.skl.ddb,
12490                                                         i))
12491                                 continue;
12492
12493                         updated |= cmask;
12494                         entries[i] = &cstate->wm.skl.ddb;
12495
12496                         /*
12497                          * If this is an already active pipe, it's DDB changed,
12498                          * and this isn't the last pipe that needs updating
12499                          * then we need to wait for a vblank to pass for the
12500                          * new ddb allocation to take effect.
12501                          */
12502                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12503                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12504                             !new_crtc_state->active_changed &&
12505                             intel_state->wm_results.dirty_pipes != updated)
12506                                 vbl_wait = true;
12507
12508                         intel_update_crtc(crtc, state, old_crtc_state,
12509                                           new_crtc_state);
12510
12511                         if (vbl_wait)
12512                                 intel_wait_for_vblank(dev_priv, pipe);
12513
12514                         progress = true;
12515                 }
12516         } while (progress);
12517
12518         /* If 2nd DBuf slice is no more required disable it */
12519         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12520                 icl_dbuf_slices_update(dev_priv, required_slices);
12521 }
12522
12523 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12524 {
12525         struct intel_atomic_state *state, *next;
12526         struct llist_node *freed;
12527
12528         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12529         llist_for_each_entry_safe(state, next, freed, freed)
12530                 drm_atomic_state_put(&state->base);
12531 }
12532
12533 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12534 {
12535         struct drm_i915_private *dev_priv =
12536                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12537
12538         intel_atomic_helper_free_state(dev_priv);
12539 }
12540
12541 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12542 {
12543         struct wait_queue_entry wait_fence, wait_reset;
12544         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12545
12546         init_wait_entry(&wait_fence, 0);
12547         init_wait_entry(&wait_reset, 0);
12548         for (;;) {
12549                 prepare_to_wait(&intel_state->commit_ready.wait,
12550                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12551                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12552                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12553
12554
12555                 if (i915_sw_fence_done(&intel_state->commit_ready)
12556                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12557                         break;
12558
12559                 schedule();
12560         }
12561         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12562         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12563 }
12564
12565 static void intel_atomic_cleanup_work(struct work_struct *work)
12566 {
12567         struct drm_atomic_state *state =
12568                 container_of(work, struct drm_atomic_state, commit_work);
12569         struct drm_i915_private *i915 = to_i915(state->dev);
12570
12571         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12572         drm_atomic_helper_commit_cleanup_done(state);
12573         drm_atomic_state_put(state);
12574
12575         intel_atomic_helper_free_state(i915);
12576 }
12577
12578 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12579 {
12580         struct drm_device *dev = state->dev;
12581         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12582         struct drm_i915_private *dev_priv = to_i915(dev);
12583         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12584         struct drm_crtc *crtc;
12585         struct intel_crtc_state *intel_cstate;
12586         u64 put_domains[I915_MAX_PIPES] = {};
12587         int i;
12588
12589         intel_atomic_commit_fence_wait(intel_state);
12590
12591         drm_atomic_helper_wait_for_dependencies(state);
12592
12593         if (intel_state->modeset)
12594                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12595
12596         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12597                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12598
12599                 if (needs_modeset(new_crtc_state) ||
12600                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12601
12602                         put_domains[to_intel_crtc(crtc)->pipe] =
12603                                 modeset_get_crtc_power_domains(crtc,
12604                                         to_intel_crtc_state(new_crtc_state));
12605                 }
12606
12607                 if (!needs_modeset(new_crtc_state))
12608                         continue;
12609
12610                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12611                                        to_intel_crtc_state(new_crtc_state));
12612
12613                 if (old_crtc_state->active) {
12614                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12615
12616                         /*
12617                          * We need to disable pipe CRC before disabling the pipe,
12618                          * or we race against vblank off.
12619                          */
12620                         intel_crtc_disable_pipe_crc(intel_crtc);
12621
12622                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12623                         intel_crtc->active = false;
12624                         intel_fbc_disable(intel_crtc);
12625                         intel_disable_shared_dpll(intel_crtc);
12626
12627                         /*
12628                          * Underruns don't always raise
12629                          * interrupts, so check manually.
12630                          */
12631                         intel_check_cpu_fifo_underruns(dev_priv);
12632                         intel_check_pch_fifo_underruns(dev_priv);
12633
12634                         if (!new_crtc_state->active) {
12635                                 /*
12636                                  * Make sure we don't call initial_watermarks
12637                                  * for ILK-style watermark updates.
12638                                  *
12639                                  * No clue what this is supposed to achieve.
12640                                  */
12641                                 if (INTEL_GEN(dev_priv) >= 9)
12642                                         dev_priv->display.initial_watermarks(intel_state,
12643                                                                              to_intel_crtc_state(new_crtc_state));
12644                         }
12645                 }
12646         }
12647
12648         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12649         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12650                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12651
12652         if (intel_state->modeset) {
12653                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12654
12655                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12656
12657                 /*
12658                  * SKL workaround: bspec recommends we disable the SAGV when we
12659                  * have more then one pipe enabled
12660                  */
12661                 if (!intel_can_enable_sagv(state))
12662                         intel_disable_sagv(dev_priv);
12663
12664                 intel_modeset_verify_disabled(dev, state);
12665         }
12666
12667         /* Complete the events for pipes that have now been disabled */
12668         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12669                 bool modeset = needs_modeset(new_crtc_state);
12670
12671                 /* Complete events for now disable pipes here. */
12672                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12673                         spin_lock_irq(&dev->event_lock);
12674                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12675                         spin_unlock_irq(&dev->event_lock);
12676
12677                         new_crtc_state->event = NULL;
12678                 }
12679         }
12680
12681         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12682         dev_priv->display.update_crtcs(state);
12683
12684         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12685          * already, but still need the state for the delayed optimization. To
12686          * fix this:
12687          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12688          * - schedule that vblank worker _before_ calling hw_done
12689          * - at the start of commit_tail, cancel it _synchrously
12690          * - switch over to the vblank wait helper in the core after that since
12691          *   we don't need out special handling any more.
12692          */
12693         drm_atomic_helper_wait_for_flip_done(dev, state);
12694
12695         /*
12696          * Now that the vblank has passed, we can go ahead and program the
12697          * optimal watermarks on platforms that need two-step watermark
12698          * programming.
12699          *
12700          * TODO: Move this (and other cleanup) to an async worker eventually.
12701          */
12702         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12703                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12704
12705                 if (dev_priv->display.optimize_watermarks)
12706                         dev_priv->display.optimize_watermarks(intel_state,
12707                                                               intel_cstate);
12708         }
12709
12710         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12711                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12712
12713                 if (put_domains[i])
12714                         modeset_put_power_domains(dev_priv, put_domains[i]);
12715
12716                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12717         }
12718
12719         if (intel_state->modeset)
12720                 intel_verify_planes(intel_state);
12721
12722         if (intel_state->modeset && intel_can_enable_sagv(state))
12723                 intel_enable_sagv(dev_priv);
12724
12725         drm_atomic_helper_commit_hw_done(state);
12726
12727         if (intel_state->modeset) {
12728                 /* As one of the primary mmio accessors, KMS has a high
12729                  * likelihood of triggering bugs in unclaimed access. After we
12730                  * finish modesetting, see if an error has been flagged, and if
12731                  * so enable debugging for the next modeset - and hope we catch
12732                  * the culprit.
12733                  */
12734                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12735                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12736         }
12737
12738         /*
12739          * Defer the cleanup of the old state to a separate worker to not
12740          * impede the current task (userspace for blocking modesets) that
12741          * are executed inline. For out-of-line asynchronous modesets/flips,
12742          * deferring to a new worker seems overkill, but we would place a
12743          * schedule point (cond_resched()) here anyway to keep latencies
12744          * down.
12745          */
12746         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
12747         queue_work(system_highpri_wq, &state->commit_work);
12748 }
12749
12750 static void intel_atomic_commit_work(struct work_struct *work)
12751 {
12752         struct drm_atomic_state *state =
12753                 container_of(work, struct drm_atomic_state, commit_work);
12754
12755         intel_atomic_commit_tail(state);
12756 }
12757
12758 static int __i915_sw_fence_call
12759 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12760                           enum i915_sw_fence_notify notify)
12761 {
12762         struct intel_atomic_state *state =
12763                 container_of(fence, struct intel_atomic_state, commit_ready);
12764
12765         switch (notify) {
12766         case FENCE_COMPLETE:
12767                 /* we do blocking waits in the worker, nothing to do here */
12768                 break;
12769         case FENCE_FREE:
12770                 {
12771                         struct intel_atomic_helper *helper =
12772                                 &to_i915(state->base.dev)->atomic_helper;
12773
12774                         if (llist_add(&state->freed, &helper->free_list))
12775                                 schedule_work(&helper->free_work);
12776                         break;
12777                 }
12778         }
12779
12780         return NOTIFY_DONE;
12781 }
12782
12783 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12784 {
12785         struct drm_plane_state *old_plane_state, *new_plane_state;
12786         struct drm_plane *plane;
12787         int i;
12788
12789         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12790                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12791                                   intel_fb_obj(new_plane_state->fb),
12792                                   to_intel_plane(plane)->frontbuffer_bit);
12793 }
12794
12795 /**
12796  * intel_atomic_commit - commit validated state object
12797  * @dev: DRM device
12798  * @state: the top-level driver state object
12799  * @nonblock: nonblocking commit
12800  *
12801  * This function commits a top-level state object that has been validated
12802  * with drm_atomic_helper_check().
12803  *
12804  * RETURNS
12805  * Zero for success or -errno.
12806  */
12807 static int intel_atomic_commit(struct drm_device *dev,
12808                                struct drm_atomic_state *state,
12809                                bool nonblock)
12810 {
12811         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12812         struct drm_i915_private *dev_priv = to_i915(dev);
12813         int ret = 0;
12814
12815         drm_atomic_state_get(state);
12816         i915_sw_fence_init(&intel_state->commit_ready,
12817                            intel_atomic_commit_ready);
12818
12819         /*
12820          * The intel_legacy_cursor_update() fast path takes care
12821          * of avoiding the vblank waits for simple cursor
12822          * movement and flips. For cursor on/off and size changes,
12823          * we want to perform the vblank waits so that watermark
12824          * updates happen during the correct frames. Gen9+ have
12825          * double buffered watermarks and so shouldn't need this.
12826          *
12827          * Unset state->legacy_cursor_update before the call to
12828          * drm_atomic_helper_setup_commit() because otherwise
12829          * drm_atomic_helper_wait_for_flip_done() is a noop and
12830          * we get FIFO underruns because we didn't wait
12831          * for vblank.
12832          *
12833          * FIXME doing watermarks and fb cleanup from a vblank worker
12834          * (assuming we had any) would solve these problems.
12835          */
12836         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12837                 struct intel_crtc_state *new_crtc_state;
12838                 struct intel_crtc *crtc;
12839                 int i;
12840
12841                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12842                         if (new_crtc_state->wm.need_postvbl_update ||
12843                             new_crtc_state->update_wm_post)
12844                                 state->legacy_cursor_update = false;
12845         }
12846
12847         ret = intel_atomic_prepare_commit(dev, state);
12848         if (ret) {
12849                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12850                 i915_sw_fence_commit(&intel_state->commit_ready);
12851                 return ret;
12852         }
12853
12854         ret = drm_atomic_helper_setup_commit(state, nonblock);
12855         if (!ret)
12856                 ret = drm_atomic_helper_swap_state(state, true);
12857
12858         if (ret) {
12859                 i915_sw_fence_commit(&intel_state->commit_ready);
12860
12861                 drm_atomic_helper_cleanup_planes(dev, state);
12862                 return ret;
12863         }
12864         dev_priv->wm.distrust_bios_wm = false;
12865         intel_shared_dpll_swap_state(state);
12866         intel_atomic_track_fbs(state);
12867
12868         if (intel_state->modeset) {
12869                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12870                        sizeof(intel_state->min_cdclk));
12871                 memcpy(dev_priv->min_voltage_level,
12872                        intel_state->min_voltage_level,
12873                        sizeof(intel_state->min_voltage_level));
12874                 dev_priv->active_crtcs = intel_state->active_crtcs;
12875                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12876                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12877         }
12878
12879         drm_atomic_state_get(state);
12880         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12881
12882         i915_sw_fence_commit(&intel_state->commit_ready);
12883         if (nonblock && intel_state->modeset) {
12884                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12885         } else if (nonblock) {
12886                 queue_work(system_unbound_wq, &state->commit_work);
12887         } else {
12888                 if (intel_state->modeset)
12889                         flush_workqueue(dev_priv->modeset_wq);
12890                 intel_atomic_commit_tail(state);
12891         }
12892
12893         return 0;
12894 }
12895
12896 static const struct drm_crtc_funcs intel_crtc_funcs = {
12897         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12898         .set_config = drm_atomic_helper_set_config,
12899         .destroy = intel_crtc_destroy,
12900         .page_flip = drm_atomic_helper_page_flip,
12901         .atomic_duplicate_state = intel_crtc_duplicate_state,
12902         .atomic_destroy_state = intel_crtc_destroy_state,
12903         .set_crc_source = intel_crtc_set_crc_source,
12904         .verify_crc_source = intel_crtc_verify_crc_source,
12905         .get_crc_sources = intel_crtc_get_crc_sources,
12906 };
12907
12908 struct wait_rps_boost {
12909         struct wait_queue_entry wait;
12910
12911         struct drm_crtc *crtc;
12912         struct i915_request *request;
12913 };
12914
12915 static int do_rps_boost(struct wait_queue_entry *_wait,
12916                         unsigned mode, int sync, void *key)
12917 {
12918         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12919         struct i915_request *rq = wait->request;
12920
12921         /*
12922          * If we missed the vblank, but the request is already running it
12923          * is reasonable to assume that it will complete before the next
12924          * vblank without our intervention, so leave RPS alone.
12925          */
12926         if (!i915_request_started(rq))
12927                 gen6_rps_boost(rq, NULL);
12928         i915_request_put(rq);
12929
12930         drm_crtc_vblank_put(wait->crtc);
12931
12932         list_del(&wait->wait.entry);
12933         kfree(wait);
12934         return 1;
12935 }
12936
12937 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12938                                        struct dma_fence *fence)
12939 {
12940         struct wait_rps_boost *wait;
12941
12942         if (!dma_fence_is_i915(fence))
12943                 return;
12944
12945         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12946                 return;
12947
12948         if (drm_crtc_vblank_get(crtc))
12949                 return;
12950
12951         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12952         if (!wait) {
12953                 drm_crtc_vblank_put(crtc);
12954                 return;
12955         }
12956
12957         wait->request = to_request(dma_fence_get(fence));
12958         wait->crtc = crtc;
12959
12960         wait->wait.func = do_rps_boost;
12961         wait->wait.flags = 0;
12962
12963         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12964 }
12965
12966 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
12967 {
12968         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
12969         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12970         struct drm_framebuffer *fb = plane_state->base.fb;
12971         struct i915_vma *vma;
12972
12973         if (plane->id == PLANE_CURSOR &&
12974             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12975                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12976                 const int align = intel_cursor_alignment(dev_priv);
12977                 int err;
12978
12979                 err = i915_gem_object_attach_phys(obj, align);
12980                 if (err)
12981                         return err;
12982         }
12983
12984         vma = intel_pin_and_fence_fb_obj(fb,
12985                                          plane_state->base.rotation,
12986                                          intel_plane_uses_fence(plane_state),
12987                                          &plane_state->flags);
12988         if (IS_ERR(vma))
12989                 return PTR_ERR(vma);
12990
12991         plane_state->vma = vma;
12992
12993         return 0;
12994 }
12995
12996 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
12997 {
12998         struct i915_vma *vma;
12999
13000         vma = fetch_and_zero(&old_plane_state->vma);
13001         if (vma)
13002                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13003 }
13004
13005 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13006 {
13007         struct i915_sched_attr attr = {
13008                 .priority = I915_PRIORITY_DISPLAY,
13009         };
13010
13011         i915_gem_object_wait_priority(obj, 0, &attr);
13012 }
13013
13014 /**
13015  * intel_prepare_plane_fb - Prepare fb for usage on plane
13016  * @plane: drm plane to prepare for
13017  * @new_state: the plane state being prepared
13018  *
13019  * Prepares a framebuffer for usage on a display plane.  Generally this
13020  * involves pinning the underlying object and updating the frontbuffer tracking
13021  * bits.  Some older platforms need special physical address handling for
13022  * cursor planes.
13023  *
13024  * Must be called with struct_mutex held.
13025  *
13026  * Returns 0 on success, negative error code on failure.
13027  */
13028 int
13029 intel_prepare_plane_fb(struct drm_plane *plane,
13030                        struct drm_plane_state *new_state)
13031 {
13032         struct intel_atomic_state *intel_state =
13033                 to_intel_atomic_state(new_state->state);
13034         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13035         struct drm_framebuffer *fb = new_state->fb;
13036         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13037         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13038         int ret;
13039
13040         if (old_obj) {
13041                 struct drm_crtc_state *crtc_state =
13042                         drm_atomic_get_new_crtc_state(new_state->state,
13043                                                       plane->state->crtc);
13044
13045                 /* Big Hammer, we also need to ensure that any pending
13046                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13047                  * current scanout is retired before unpinning the old
13048                  * framebuffer. Note that we rely on userspace rendering
13049                  * into the buffer attached to the pipe they are waiting
13050                  * on. If not, userspace generates a GPU hang with IPEHR
13051                  * point to the MI_WAIT_FOR_EVENT.
13052                  *
13053                  * This should only fail upon a hung GPU, in which case we
13054                  * can safely continue.
13055                  */
13056                 if (needs_modeset(crtc_state)) {
13057                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13058                                                               old_obj->resv, NULL,
13059                                                               false, 0,
13060                                                               GFP_KERNEL);
13061                         if (ret < 0)
13062                                 return ret;
13063                 }
13064         }
13065
13066         if (new_state->fence) { /* explicit fencing */
13067                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13068                                                     new_state->fence,
13069                                                     I915_FENCE_TIMEOUT,
13070                                                     GFP_KERNEL);
13071                 if (ret < 0)
13072                         return ret;
13073         }
13074
13075         if (!obj)
13076                 return 0;
13077
13078         ret = i915_gem_object_pin_pages(obj);
13079         if (ret)
13080                 return ret;
13081
13082         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13083         if (ret) {
13084                 i915_gem_object_unpin_pages(obj);
13085                 return ret;
13086         }
13087
13088         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13089
13090         fb_obj_bump_render_priority(obj);
13091
13092         mutex_unlock(&dev_priv->drm.struct_mutex);
13093         i915_gem_object_unpin_pages(obj);
13094         if (ret)
13095                 return ret;
13096
13097         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13098
13099         if (!new_state->fence) { /* implicit fencing */
13100                 struct dma_fence *fence;
13101
13102                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13103                                                       obj->resv, NULL,
13104                                                       false, I915_FENCE_TIMEOUT,
13105                                                       GFP_KERNEL);
13106                 if (ret < 0)
13107                         return ret;
13108
13109                 fence = reservation_object_get_excl_rcu(obj->resv);
13110                 if (fence) {
13111                         add_rps_boost_after_vblank(new_state->crtc, fence);
13112                         dma_fence_put(fence);
13113                 }
13114         } else {
13115                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13116         }
13117
13118         /*
13119          * We declare pageflips to be interactive and so merit a small bias
13120          * towards upclocking to deliver the frame on time. By only changing
13121          * the RPS thresholds to sample more regularly and aim for higher
13122          * clocks we can hopefully deliver low power workloads (like kodi)
13123          * that are not quite steady state without resorting to forcing
13124          * maximum clocks following a vblank miss (see do_rps_boost()).
13125          */
13126         if (!intel_state->rps_interactive) {
13127                 intel_rps_mark_interactive(dev_priv, true);
13128                 intel_state->rps_interactive = true;
13129         }
13130
13131         return 0;
13132 }
13133
13134 /**
13135  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13136  * @plane: drm plane to clean up for
13137  * @old_state: the state from the previous modeset
13138  *
13139  * Cleans up a framebuffer that has just been removed from a plane.
13140  *
13141  * Must be called with struct_mutex held.
13142  */
13143 void
13144 intel_cleanup_plane_fb(struct drm_plane *plane,
13145                        struct drm_plane_state *old_state)
13146 {
13147         struct intel_atomic_state *intel_state =
13148                 to_intel_atomic_state(old_state->state);
13149         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13150
13151         if (intel_state->rps_interactive) {
13152                 intel_rps_mark_interactive(dev_priv, false);
13153                 intel_state->rps_interactive = false;
13154         }
13155
13156         /* Should only be called after a successful intel_prepare_plane_fb()! */
13157         mutex_lock(&dev_priv->drm.struct_mutex);
13158         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13159         mutex_unlock(&dev_priv->drm.struct_mutex);
13160 }
13161
13162 int
13163 skl_max_scale(struct intel_crtc *intel_crtc,
13164               struct intel_crtc_state *crtc_state,
13165               uint32_t pixel_format)
13166 {
13167         struct drm_i915_private *dev_priv;
13168         int max_scale, mult;
13169         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13170
13171         if (!intel_crtc || !crtc_state->base.enable)
13172                 return DRM_PLANE_HELPER_NO_SCALING;
13173
13174         dev_priv = to_i915(intel_crtc->base.dev);
13175
13176         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13177         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13178
13179         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13180                 max_dotclk *= 2;
13181
13182         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13183                 return DRM_PLANE_HELPER_NO_SCALING;
13184
13185         /*
13186          * skl max scale is lower of:
13187          *    close to 3 but not 3, -1 is for that purpose
13188          *            or
13189          *    cdclk/crtc_clock
13190          */
13191         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13192         tmpclk1 = (1 << 16) * mult - 1;
13193         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13194         max_scale = min(tmpclk1, tmpclk2);
13195
13196         return max_scale;
13197 }
13198
13199 static int
13200 intel_check_primary_plane(struct intel_crtc_state *crtc_state,
13201                           struct intel_plane_state *state)
13202 {
13203         struct intel_plane *plane = to_intel_plane(state->base.plane);
13204         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13205         struct drm_crtc *crtc = state->base.crtc;
13206         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13207         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13208         bool can_position = false;
13209         int ret;
13210         uint32_t pixel_format = 0;
13211
13212         if (INTEL_GEN(dev_priv) >= 9) {
13213                 /* use scaler when colorkey is not required */
13214                 if (!state->ckey.flags) {
13215                         min_scale = 1;
13216                         if (state->base.fb)
13217                                 pixel_format = state->base.fb->format->format;
13218                         max_scale = skl_max_scale(to_intel_crtc(crtc),
13219                                                   crtc_state, pixel_format);
13220                 }
13221                 can_position = true;
13222         }
13223
13224         ret = drm_atomic_helper_check_plane_state(&state->base,
13225                                                   &crtc_state->base,
13226                                                   min_scale, max_scale,
13227                                                   can_position, true);
13228         if (ret)
13229                 return ret;
13230
13231         if (!state->base.fb)
13232                 return 0;
13233
13234         if (INTEL_GEN(dev_priv) >= 9) {
13235                 ret = skl_check_plane_surface(crtc_state, state);
13236                 if (ret)
13237                         return ret;
13238
13239                 state->ctl = skl_plane_ctl(crtc_state, state);
13240         } else {
13241                 ret = i9xx_check_plane_surface(state);
13242                 if (ret)
13243                         return ret;
13244
13245                 state->ctl = i9xx_plane_ctl(crtc_state, state);
13246         }
13247
13248         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
13249                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
13250
13251         return 0;
13252 }
13253
13254 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13255                                     struct drm_crtc_state *old_crtc_state)
13256 {
13257         struct drm_device *dev = crtc->dev;
13258         struct drm_i915_private *dev_priv = to_i915(dev);
13259         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13260         struct intel_crtc_state *old_intel_cstate =
13261                 to_intel_crtc_state(old_crtc_state);
13262         struct intel_atomic_state *old_intel_state =
13263                 to_intel_atomic_state(old_crtc_state->state);
13264         struct intel_crtc_state *intel_cstate =
13265                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13266         bool modeset = needs_modeset(&intel_cstate->base);
13267
13268         if (!modeset &&
13269             (intel_cstate->base.color_mgmt_changed ||
13270              intel_cstate->update_pipe)) {
13271                 intel_color_set_csc(&intel_cstate->base);
13272                 intel_color_load_luts(&intel_cstate->base);
13273         }
13274
13275         /* Perform vblank evasion around commit operation */
13276         intel_pipe_update_start(intel_cstate);
13277
13278         if (modeset)
13279                 goto out;
13280
13281         if (intel_cstate->update_pipe)
13282                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13283         else if (INTEL_GEN(dev_priv) >= 9)
13284                 skl_detach_scalers(intel_crtc);
13285
13286 out:
13287         if (dev_priv->display.atomic_update_watermarks)
13288                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13289                                                            intel_cstate);
13290 }
13291
13292 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13293                                   struct intel_crtc_state *crtc_state)
13294 {
13295         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13296
13297         if (!IS_GEN2(dev_priv))
13298                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13299
13300         if (crtc_state->has_pch_encoder) {
13301                 enum pipe pch_transcoder =
13302                         intel_crtc_pch_transcoder(crtc);
13303
13304                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13305         }
13306 }
13307
13308 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13309                                      struct drm_crtc_state *old_crtc_state)
13310 {
13311         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13312         struct intel_atomic_state *old_intel_state =
13313                 to_intel_atomic_state(old_crtc_state->state);
13314         struct intel_crtc_state *new_crtc_state =
13315                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13316
13317         intel_pipe_update_end(new_crtc_state);
13318
13319         if (new_crtc_state->update_pipe &&
13320             !needs_modeset(&new_crtc_state->base) &&
13321             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13322                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13323 }
13324
13325 /**
13326  * intel_plane_destroy - destroy a plane
13327  * @plane: plane to destroy
13328  *
13329  * Common destruction function for all types of planes (primary, cursor,
13330  * sprite).
13331  */
13332 void intel_plane_destroy(struct drm_plane *plane)
13333 {
13334         drm_plane_cleanup(plane);
13335         kfree(to_intel_plane(plane));
13336 }
13337
13338 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13339                                             u32 format, u64 modifier)
13340 {
13341         switch (modifier) {
13342         case DRM_FORMAT_MOD_LINEAR:
13343         case I915_FORMAT_MOD_X_TILED:
13344                 break;
13345         default:
13346                 return false;
13347         }
13348
13349         switch (format) {
13350         case DRM_FORMAT_C8:
13351         case DRM_FORMAT_RGB565:
13352         case DRM_FORMAT_XRGB1555:
13353         case DRM_FORMAT_XRGB8888:
13354                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13355                         modifier == I915_FORMAT_MOD_X_TILED;
13356         default:
13357                 return false;
13358         }
13359 }
13360
13361 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13362                                             u32 format, u64 modifier)
13363 {
13364         switch (modifier) {
13365         case DRM_FORMAT_MOD_LINEAR:
13366         case I915_FORMAT_MOD_X_TILED:
13367                 break;
13368         default:
13369                 return false;
13370         }
13371
13372         switch (format) {
13373         case DRM_FORMAT_C8:
13374         case DRM_FORMAT_RGB565:
13375         case DRM_FORMAT_XRGB8888:
13376         case DRM_FORMAT_XBGR8888:
13377         case DRM_FORMAT_XRGB2101010:
13378         case DRM_FORMAT_XBGR2101010:
13379                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13380                         modifier == I915_FORMAT_MOD_X_TILED;
13381         default:
13382                 return false;
13383         }
13384 }
13385
13386 static bool skl_plane_format_mod_supported(struct drm_plane *_plane,
13387                                            u32 format, u64 modifier)
13388 {
13389         struct intel_plane *plane = to_intel_plane(_plane);
13390
13391         switch (modifier) {
13392         case DRM_FORMAT_MOD_LINEAR:
13393         case I915_FORMAT_MOD_X_TILED:
13394         case I915_FORMAT_MOD_Y_TILED:
13395         case I915_FORMAT_MOD_Yf_TILED:
13396                 break;
13397         case I915_FORMAT_MOD_Y_TILED_CCS:
13398         case I915_FORMAT_MOD_Yf_TILED_CCS:
13399                 if (!plane->has_ccs)
13400                         return false;
13401                 break;
13402         default:
13403                 return false;
13404         }
13405
13406         switch (format) {
13407         case DRM_FORMAT_XRGB8888:
13408         case DRM_FORMAT_XBGR8888:
13409         case DRM_FORMAT_ARGB8888:
13410         case DRM_FORMAT_ABGR8888:
13411                 if (is_ccs_modifier(modifier))
13412                         return true;
13413                 /* fall through */
13414         case DRM_FORMAT_RGB565:
13415         case DRM_FORMAT_XRGB2101010:
13416         case DRM_FORMAT_XBGR2101010:
13417         case DRM_FORMAT_YUYV:
13418         case DRM_FORMAT_YVYU:
13419         case DRM_FORMAT_UYVY:
13420         case DRM_FORMAT_VYUY:
13421         case DRM_FORMAT_NV12:
13422                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13423                         return true;
13424                 /* fall through */
13425         case DRM_FORMAT_C8:
13426                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13427                     modifier == I915_FORMAT_MOD_X_TILED ||
13428                     modifier == I915_FORMAT_MOD_Y_TILED)
13429                         return true;
13430                 /* fall through */
13431         default:
13432                 return false;
13433         }
13434 }
13435
13436 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13437                                               u32 format, u64 modifier)
13438 {
13439         return modifier == DRM_FORMAT_MOD_LINEAR &&
13440                 format == DRM_FORMAT_ARGB8888;
13441 }
13442
13443 static struct drm_plane_funcs skl_plane_funcs = {
13444         .update_plane = drm_atomic_helper_update_plane,
13445         .disable_plane = drm_atomic_helper_disable_plane,
13446         .destroy = intel_plane_destroy,
13447         .atomic_get_property = intel_plane_atomic_get_property,
13448         .atomic_set_property = intel_plane_atomic_set_property,
13449         .atomic_duplicate_state = intel_plane_duplicate_state,
13450         .atomic_destroy_state = intel_plane_destroy_state,
13451         .format_mod_supported = skl_plane_format_mod_supported,
13452 };
13453
13454 static struct drm_plane_funcs i965_plane_funcs = {
13455         .update_plane = drm_atomic_helper_update_plane,
13456         .disable_plane = drm_atomic_helper_disable_plane,
13457         .destroy = intel_plane_destroy,
13458         .atomic_get_property = intel_plane_atomic_get_property,
13459         .atomic_set_property = intel_plane_atomic_set_property,
13460         .atomic_duplicate_state = intel_plane_duplicate_state,
13461         .atomic_destroy_state = intel_plane_destroy_state,
13462         .format_mod_supported = i965_plane_format_mod_supported,
13463 };
13464
13465 static struct drm_plane_funcs i8xx_plane_funcs = {
13466         .update_plane = drm_atomic_helper_update_plane,
13467         .disable_plane = drm_atomic_helper_disable_plane,
13468         .destroy = intel_plane_destroy,
13469         .atomic_get_property = intel_plane_atomic_get_property,
13470         .atomic_set_property = intel_plane_atomic_set_property,
13471         .atomic_duplicate_state = intel_plane_duplicate_state,
13472         .atomic_destroy_state = intel_plane_destroy_state,
13473         .format_mod_supported = i8xx_plane_format_mod_supported,
13474 };
13475
13476 static int
13477 intel_legacy_cursor_update(struct drm_plane *plane,
13478                            struct drm_crtc *crtc,
13479                            struct drm_framebuffer *fb,
13480                            int crtc_x, int crtc_y,
13481                            unsigned int crtc_w, unsigned int crtc_h,
13482                            uint32_t src_x, uint32_t src_y,
13483                            uint32_t src_w, uint32_t src_h,
13484                            struct drm_modeset_acquire_ctx *ctx)
13485 {
13486         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13487         int ret;
13488         struct drm_plane_state *old_plane_state, *new_plane_state;
13489         struct intel_plane *intel_plane = to_intel_plane(plane);
13490         struct drm_framebuffer *old_fb;
13491         struct drm_crtc_state *crtc_state = crtc->state;
13492
13493         /*
13494          * When crtc is inactive or there is a modeset pending,
13495          * wait for it to complete in the slowpath
13496          */
13497         if (!crtc_state->active || needs_modeset(crtc_state) ||
13498             to_intel_crtc_state(crtc_state)->update_pipe)
13499                 goto slow;
13500
13501         old_plane_state = plane->state;
13502         /*
13503          * Don't do an async update if there is an outstanding commit modifying
13504          * the plane.  This prevents our async update's changes from getting
13505          * overridden by a previous synchronous update's state.
13506          */
13507         if (old_plane_state->commit &&
13508             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13509                 goto slow;
13510
13511         /*
13512          * If any parameters change that may affect watermarks,
13513          * take the slowpath. Only changing fb or position should be
13514          * in the fastpath.
13515          */
13516         if (old_plane_state->crtc != crtc ||
13517             old_plane_state->src_w != src_w ||
13518             old_plane_state->src_h != src_h ||
13519             old_plane_state->crtc_w != crtc_w ||
13520             old_plane_state->crtc_h != crtc_h ||
13521             !old_plane_state->fb != !fb)
13522                 goto slow;
13523
13524         new_plane_state = intel_plane_duplicate_state(plane);
13525         if (!new_plane_state)
13526                 return -ENOMEM;
13527
13528         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13529
13530         new_plane_state->src_x = src_x;
13531         new_plane_state->src_y = src_y;
13532         new_plane_state->src_w = src_w;
13533         new_plane_state->src_h = src_h;
13534         new_plane_state->crtc_x = crtc_x;
13535         new_plane_state->crtc_y = crtc_y;
13536         new_plane_state->crtc_w = crtc_w;
13537         new_plane_state->crtc_h = crtc_h;
13538
13539         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13540                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13541                                                   to_intel_plane_state(plane->state),
13542                                                   to_intel_plane_state(new_plane_state));
13543         if (ret)
13544                 goto out_free;
13545
13546         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13547         if (ret)
13548                 goto out_free;
13549
13550         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13551         if (ret)
13552                 goto out_unlock;
13553
13554         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13555
13556         old_fb = old_plane_state->fb;
13557         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13558                           intel_plane->frontbuffer_bit);
13559
13560         /* Swap plane state */
13561         plane->state = new_plane_state;
13562
13563         if (plane->state->visible) {
13564                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13565                 intel_plane->update_plane(intel_plane,
13566                                           to_intel_crtc_state(crtc->state),
13567                                           to_intel_plane_state(plane->state));
13568         } else {
13569                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13570                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13571         }
13572
13573         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13574
13575 out_unlock:
13576         mutex_unlock(&dev_priv->drm.struct_mutex);
13577 out_free:
13578         if (ret)
13579                 intel_plane_destroy_state(plane, new_plane_state);
13580         else
13581                 intel_plane_destroy_state(plane, old_plane_state);
13582         return ret;
13583
13584 slow:
13585         return drm_atomic_helper_update_plane(plane, crtc, fb,
13586                                               crtc_x, crtc_y, crtc_w, crtc_h,
13587                                               src_x, src_y, src_w, src_h, ctx);
13588 }
13589
13590 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13591         .update_plane = intel_legacy_cursor_update,
13592         .disable_plane = drm_atomic_helper_disable_plane,
13593         .destroy = intel_plane_destroy,
13594         .atomic_get_property = intel_plane_atomic_get_property,
13595         .atomic_set_property = intel_plane_atomic_set_property,
13596         .atomic_duplicate_state = intel_plane_duplicate_state,
13597         .atomic_destroy_state = intel_plane_destroy_state,
13598         .format_mod_supported = intel_cursor_format_mod_supported,
13599 };
13600
13601 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13602                                enum i9xx_plane_id i9xx_plane)
13603 {
13604         if (!HAS_FBC(dev_priv))
13605                 return false;
13606
13607         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13608                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13609         else if (IS_IVYBRIDGE(dev_priv))
13610                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13611                         i9xx_plane == PLANE_C;
13612         else if (INTEL_GEN(dev_priv) >= 4)
13613                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13614         else
13615                 return i9xx_plane == PLANE_A;
13616 }
13617
13618 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13619                               enum pipe pipe, enum plane_id plane_id)
13620 {
13621         if (!HAS_FBC(dev_priv))
13622                 return false;
13623
13624         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13625 }
13626
13627 bool skl_plane_has_planar(struct drm_i915_private *dev_priv,
13628                           enum pipe pipe, enum plane_id plane_id)
13629 {
13630         /*
13631          * FIXME: ICL requires two hardware planes for scanning out NV12
13632          * framebuffers. Do not advertize support until this is implemented.
13633          */
13634         if (INTEL_GEN(dev_priv) >= 11)
13635                 return false;
13636
13637         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
13638                 return false;
13639
13640         if (INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv) && pipe == PIPE_C)
13641                 return false;
13642
13643         if (plane_id != PLANE_PRIMARY && plane_id != PLANE_SPRITE0)
13644                 return false;
13645
13646         return true;
13647 }
13648
13649 static struct intel_plane *
13650 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13651 {
13652         struct intel_plane *primary = NULL;
13653         struct intel_plane_state *state = NULL;
13654         const struct drm_plane_funcs *plane_funcs;
13655         const uint32_t *intel_primary_formats;
13656         unsigned int supported_rotations;
13657         unsigned int num_formats;
13658         const uint64_t *modifiers;
13659         int ret;
13660
13661         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13662         if (!primary) {
13663                 ret = -ENOMEM;
13664                 goto fail;
13665         }
13666
13667         state = intel_create_plane_state(&primary->base);
13668         if (!state) {
13669                 ret = -ENOMEM;
13670                 goto fail;
13671         }
13672
13673         primary->base.state = &state->base;
13674
13675         primary->can_scale = false;
13676         primary->max_downscale = 1;
13677         if (INTEL_GEN(dev_priv) >= 9) {
13678                 primary->can_scale = true;
13679                 state->scaler_id = -1;
13680         }
13681         primary->pipe = pipe;
13682         /*
13683          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13684          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13685          */
13686         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13687                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13688         else
13689                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13690         primary->id = PLANE_PRIMARY;
13691         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13692
13693         if (INTEL_GEN(dev_priv) >= 9)
13694                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13695                                                      primary->pipe,
13696                                                      primary->id);
13697         else
13698                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13699                                                       primary->i9xx_plane);
13700
13701         if (primary->has_fbc) {
13702                 struct intel_fbc *fbc = &dev_priv->fbc;
13703
13704                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13705         }
13706
13707         primary->check_plane = intel_check_primary_plane;
13708
13709         if (INTEL_GEN(dev_priv) >= 9) {
13710                 primary->has_ccs = skl_plane_has_ccs(dev_priv, pipe,
13711                                                      PLANE_PRIMARY);
13712
13713                 if (skl_plane_has_planar(dev_priv, pipe, PLANE_PRIMARY)) {
13714                         intel_primary_formats = skl_pri_planar_formats;
13715                         num_formats = ARRAY_SIZE(skl_pri_planar_formats);
13716                 } else {
13717                         intel_primary_formats = skl_primary_formats;
13718                         num_formats = ARRAY_SIZE(skl_primary_formats);
13719                 }
13720
13721                 if (primary->has_ccs)
13722                         modifiers = skl_format_modifiers_ccs;
13723                 else
13724                         modifiers = skl_format_modifiers_noccs;
13725
13726                 primary->update_plane = skl_update_plane;
13727                 primary->disable_plane = skl_disable_plane;
13728                 primary->get_hw_state = skl_plane_get_hw_state;
13729
13730                 plane_funcs = &skl_plane_funcs;
13731         } else if (INTEL_GEN(dev_priv) >= 4) {
13732                 intel_primary_formats = i965_primary_formats;
13733                 num_formats = ARRAY_SIZE(i965_primary_formats);
13734                 modifiers = i9xx_format_modifiers;
13735
13736                 primary->update_plane = i9xx_update_plane;
13737                 primary->disable_plane = i9xx_disable_plane;
13738                 primary->get_hw_state = i9xx_plane_get_hw_state;
13739
13740                 plane_funcs = &i965_plane_funcs;
13741         } else {
13742                 intel_primary_formats = i8xx_primary_formats;
13743                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13744                 modifiers = i9xx_format_modifiers;
13745
13746                 primary->update_plane = i9xx_update_plane;
13747                 primary->disable_plane = i9xx_disable_plane;
13748                 primary->get_hw_state = i9xx_plane_get_hw_state;
13749
13750                 plane_funcs = &i8xx_plane_funcs;
13751         }
13752
13753         if (INTEL_GEN(dev_priv) >= 9)
13754                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13755                                                0, plane_funcs,
13756                                                intel_primary_formats, num_formats,
13757                                                modifiers,
13758                                                DRM_PLANE_TYPE_PRIMARY,
13759                                                "plane 1%c", pipe_name(pipe));
13760         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13761                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13762                                                0, plane_funcs,
13763                                                intel_primary_formats, num_formats,
13764                                                modifiers,
13765                                                DRM_PLANE_TYPE_PRIMARY,
13766                                                "primary %c", pipe_name(pipe));
13767         else
13768                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13769                                                0, plane_funcs,
13770                                                intel_primary_formats, num_formats,
13771                                                modifiers,
13772                                                DRM_PLANE_TYPE_PRIMARY,
13773                                                "plane %c",
13774                                                plane_name(primary->i9xx_plane));
13775         if (ret)
13776                 goto fail;
13777
13778         if (INTEL_GEN(dev_priv) >= 10) {
13779                 supported_rotations =
13780                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13781                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13782                         DRM_MODE_REFLECT_X;
13783         } else if (INTEL_GEN(dev_priv) >= 9) {
13784                 supported_rotations =
13785                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13786                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13787         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13788                 supported_rotations =
13789                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13790                         DRM_MODE_REFLECT_X;
13791         } else if (INTEL_GEN(dev_priv) >= 4) {
13792                 supported_rotations =
13793                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13794         } else {
13795                 supported_rotations = DRM_MODE_ROTATE_0;
13796         }
13797
13798         if (INTEL_GEN(dev_priv) >= 4)
13799                 drm_plane_create_rotation_property(&primary->base,
13800                                                    DRM_MODE_ROTATE_0,
13801                                                    supported_rotations);
13802
13803         if (INTEL_GEN(dev_priv) >= 9)
13804                 drm_plane_create_color_properties(&primary->base,
13805                                                   BIT(DRM_COLOR_YCBCR_BT601) |
13806                                                   BIT(DRM_COLOR_YCBCR_BT709),
13807                                                   BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
13808                                                   BIT(DRM_COLOR_YCBCR_FULL_RANGE),
13809                                                   DRM_COLOR_YCBCR_BT709,
13810                                                   DRM_COLOR_YCBCR_LIMITED_RANGE);
13811
13812         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13813
13814         return primary;
13815
13816 fail:
13817         kfree(state);
13818         kfree(primary);
13819
13820         return ERR_PTR(ret);
13821 }
13822
13823 static struct intel_plane *
13824 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13825                           enum pipe pipe)
13826 {
13827         struct intel_plane *cursor = NULL;
13828         struct intel_plane_state *state = NULL;
13829         int ret;
13830
13831         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13832         if (!cursor) {
13833                 ret = -ENOMEM;
13834                 goto fail;
13835         }
13836
13837         state = intel_create_plane_state(&cursor->base);
13838         if (!state) {
13839                 ret = -ENOMEM;
13840                 goto fail;
13841         }
13842
13843         cursor->base.state = &state->base;
13844
13845         cursor->can_scale = false;
13846         cursor->max_downscale = 1;
13847         cursor->pipe = pipe;
13848         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13849         cursor->id = PLANE_CURSOR;
13850         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13851
13852         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13853                 cursor->update_plane = i845_update_cursor;
13854                 cursor->disable_plane = i845_disable_cursor;
13855                 cursor->get_hw_state = i845_cursor_get_hw_state;
13856                 cursor->check_plane = i845_check_cursor;
13857         } else {
13858                 cursor->update_plane = i9xx_update_cursor;
13859                 cursor->disable_plane = i9xx_disable_cursor;
13860                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13861                 cursor->check_plane = i9xx_check_cursor;
13862         }
13863
13864         cursor->cursor.base = ~0;
13865         cursor->cursor.cntl = ~0;
13866
13867         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13868                 cursor->cursor.size = ~0;
13869
13870         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13871                                        0, &intel_cursor_plane_funcs,
13872                                        intel_cursor_formats,
13873                                        ARRAY_SIZE(intel_cursor_formats),
13874                                        cursor_format_modifiers,
13875                                        DRM_PLANE_TYPE_CURSOR,
13876                                        "cursor %c", pipe_name(pipe));
13877         if (ret)
13878                 goto fail;
13879
13880         if (INTEL_GEN(dev_priv) >= 4)
13881                 drm_plane_create_rotation_property(&cursor->base,
13882                                                    DRM_MODE_ROTATE_0,
13883                                                    DRM_MODE_ROTATE_0 |
13884                                                    DRM_MODE_ROTATE_180);
13885
13886         if (INTEL_GEN(dev_priv) >= 9)
13887                 state->scaler_id = -1;
13888
13889         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13890
13891         return cursor;
13892
13893 fail:
13894         kfree(state);
13895         kfree(cursor);
13896
13897         return ERR_PTR(ret);
13898 }
13899
13900 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13901                                     struct intel_crtc_state *crtc_state)
13902 {
13903         struct intel_crtc_scaler_state *scaler_state =
13904                 &crtc_state->scaler_state;
13905         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13906         int i;
13907
13908         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13909         if (!crtc->num_scalers)
13910                 return;
13911
13912         for (i = 0; i < crtc->num_scalers; i++) {
13913                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13914
13915                 scaler->in_use = 0;
13916                 scaler->mode = PS_SCALER_MODE_DYN;
13917         }
13918
13919         scaler_state->scaler_id = -1;
13920 }
13921
13922 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13923 {
13924         struct intel_crtc *intel_crtc;
13925         struct intel_crtc_state *crtc_state = NULL;
13926         struct intel_plane *primary = NULL;
13927         struct intel_plane *cursor = NULL;
13928         int sprite, ret;
13929
13930         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13931         if (!intel_crtc)
13932                 return -ENOMEM;
13933
13934         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13935         if (!crtc_state) {
13936                 ret = -ENOMEM;
13937                 goto fail;
13938         }
13939         intel_crtc->config = crtc_state;
13940         intel_crtc->base.state = &crtc_state->base;
13941         crtc_state->base.crtc = &intel_crtc->base;
13942
13943         primary = intel_primary_plane_create(dev_priv, pipe);
13944         if (IS_ERR(primary)) {
13945                 ret = PTR_ERR(primary);
13946                 goto fail;
13947         }
13948         intel_crtc->plane_ids_mask |= BIT(primary->id);
13949
13950         for_each_sprite(dev_priv, pipe, sprite) {
13951                 struct intel_plane *plane;
13952
13953                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13954                 if (IS_ERR(plane)) {
13955                         ret = PTR_ERR(plane);
13956                         goto fail;
13957                 }
13958                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13959         }
13960
13961         cursor = intel_cursor_plane_create(dev_priv, pipe);
13962         if (IS_ERR(cursor)) {
13963                 ret = PTR_ERR(cursor);
13964                 goto fail;
13965         }
13966         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13967
13968         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13969                                         &primary->base, &cursor->base,
13970                                         &intel_crtc_funcs,
13971                                         "pipe %c", pipe_name(pipe));
13972         if (ret)
13973                 goto fail;
13974
13975         intel_crtc->pipe = pipe;
13976
13977         /* initialize shared scalers */
13978         intel_crtc_init_scalers(intel_crtc, crtc_state);
13979
13980         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
13981                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
13982         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
13983
13984         if (INTEL_GEN(dev_priv) < 9) {
13985                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
13986
13987                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13988                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
13989                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
13990         }
13991
13992         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13993
13994         intel_color_init(&intel_crtc->base);
13995
13996         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13997
13998         return 0;
13999
14000 fail:
14001         /*
14002          * drm_mode_config_cleanup() will free up any
14003          * crtcs/planes already initialized.
14004          */
14005         kfree(crtc_state);
14006         kfree(intel_crtc);
14007
14008         return ret;
14009 }
14010
14011 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14012 {
14013         struct drm_device *dev = connector->base.dev;
14014
14015         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14016
14017         if (!connector->base.state->crtc)
14018                 return INVALID_PIPE;
14019
14020         return to_intel_crtc(connector->base.state->crtc)->pipe;
14021 }
14022
14023 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14024                                       struct drm_file *file)
14025 {
14026         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14027         struct drm_crtc *drmmode_crtc;
14028         struct intel_crtc *crtc;
14029
14030         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14031         if (!drmmode_crtc)
14032                 return -ENOENT;
14033
14034         crtc = to_intel_crtc(drmmode_crtc);
14035         pipe_from_crtc_id->pipe = crtc->pipe;
14036
14037         return 0;
14038 }
14039
14040 static int intel_encoder_clones(struct intel_encoder *encoder)
14041 {
14042         struct drm_device *dev = encoder->base.dev;
14043         struct intel_encoder *source_encoder;
14044         int index_mask = 0;
14045         int entry = 0;
14046
14047         for_each_intel_encoder(dev, source_encoder) {
14048                 if (encoders_cloneable(encoder, source_encoder))
14049                         index_mask |= (1 << entry);
14050
14051                 entry++;
14052         }
14053
14054         return index_mask;
14055 }
14056
14057 static bool has_edp_a(struct drm_i915_private *dev_priv)
14058 {
14059         if (!IS_MOBILE(dev_priv))
14060                 return false;
14061
14062         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14063                 return false;
14064
14065         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14066                 return false;
14067
14068         return true;
14069 }
14070
14071 static bool intel_crt_present(struct drm_i915_private *dev_priv)
14072 {
14073         if (INTEL_GEN(dev_priv) >= 9)
14074                 return false;
14075
14076         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14077                 return false;
14078
14079         if (IS_CHERRYVIEW(dev_priv))
14080                 return false;
14081
14082         if (HAS_PCH_LPT_H(dev_priv) &&
14083             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14084                 return false;
14085
14086         /* DDI E can't be used if DDI A requires 4 lanes */
14087         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14088                 return false;
14089
14090         if (!dev_priv->vbt.int_crt_support)
14091                 return false;
14092
14093         return true;
14094 }
14095
14096 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14097 {
14098         int pps_num;
14099         int pps_idx;
14100
14101         if (HAS_DDI(dev_priv))
14102                 return;
14103         /*
14104          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14105          * everywhere where registers can be write protected.
14106          */
14107         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14108                 pps_num = 2;
14109         else
14110                 pps_num = 1;
14111
14112         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14113                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14114
14115                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14116                 I915_WRITE(PP_CONTROL(pps_idx), val);
14117         }
14118 }
14119
14120 static void intel_pps_init(struct drm_i915_private *dev_priv)
14121 {
14122         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14123                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14124         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14125                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14126         else
14127                 dev_priv->pps_mmio_base = PPS_BASE;
14128
14129         intel_pps_unlock_regs_wa(dev_priv);
14130 }
14131
14132 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14133 {
14134         struct intel_encoder *encoder;
14135         bool dpd_is_edp = false;
14136
14137         intel_pps_init(dev_priv);
14138
14139         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14140                 return;
14141
14142         /*
14143          * intel_edp_init_connector() depends on this completing first, to
14144          * prevent the registeration of both eDP and LVDS and the incorrect
14145          * sharing of the PPS.
14146          */
14147         intel_lvds_init(dev_priv);
14148
14149         if (intel_crt_present(dev_priv))
14150                 intel_crt_init(dev_priv);
14151
14152         if (IS_ICELAKE(dev_priv)) {
14153                 intel_ddi_init(dev_priv, PORT_A);
14154                 intel_ddi_init(dev_priv, PORT_B);
14155                 intel_ddi_init(dev_priv, PORT_C);
14156                 intel_ddi_init(dev_priv, PORT_D);
14157                 intel_ddi_init(dev_priv, PORT_E);
14158                 intel_ddi_init(dev_priv, PORT_F);
14159         } else if (IS_GEN9_LP(dev_priv)) {
14160                 /*
14161                  * FIXME: Broxton doesn't support port detection via the
14162                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14163                  * detect the ports.
14164                  */
14165                 intel_ddi_init(dev_priv, PORT_A);
14166                 intel_ddi_init(dev_priv, PORT_B);
14167                 intel_ddi_init(dev_priv, PORT_C);
14168
14169                 vlv_dsi_init(dev_priv);
14170         } else if (HAS_DDI(dev_priv)) {
14171                 int found;
14172
14173                 /*
14174                  * Haswell uses DDI functions to detect digital outputs.
14175                  * On SKL pre-D0 the strap isn't connected, so we assume
14176                  * it's there.
14177                  */
14178                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14179                 /* WaIgnoreDDIAStrap: skl */
14180                 if (found || IS_GEN9_BC(dev_priv))
14181                         intel_ddi_init(dev_priv, PORT_A);
14182
14183                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14184                  * register */
14185                 found = I915_READ(SFUSE_STRAP);
14186
14187                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14188                         intel_ddi_init(dev_priv, PORT_B);
14189                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14190                         intel_ddi_init(dev_priv, PORT_C);
14191                 if (found & SFUSE_STRAP_DDID_DETECTED)
14192                         intel_ddi_init(dev_priv, PORT_D);
14193                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14194                         intel_ddi_init(dev_priv, PORT_F);
14195                 /*
14196                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14197                  */
14198                 if (IS_GEN9_BC(dev_priv) &&
14199                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14200                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14201                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14202                         intel_ddi_init(dev_priv, PORT_E);
14203
14204         } else if (HAS_PCH_SPLIT(dev_priv)) {
14205                 int found;
14206                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14207
14208                 if (has_edp_a(dev_priv))
14209                         intel_dp_init(dev_priv, DP_A, PORT_A);
14210
14211                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14212                         /* PCH SDVOB multiplex with HDMIB */
14213                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14214                         if (!found)
14215                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14216                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14217                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14218                 }
14219
14220                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14221                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14222
14223                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14224                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14225
14226                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14227                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14228
14229                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14230                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14231         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14232                 bool has_edp, has_port;
14233
14234                 /*
14235                  * The DP_DETECTED bit is the latched state of the DDC
14236                  * SDA pin at boot. However since eDP doesn't require DDC
14237                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14238                  * eDP ports may have been muxed to an alternate function.
14239                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14240                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14241                  * detect eDP ports.
14242                  *
14243                  * Sadly the straps seem to be missing sometimes even for HDMI
14244                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14245                  * and VBT for the presence of the port. Additionally we can't
14246                  * trust the port type the VBT declares as we've seen at least
14247                  * HDMI ports that the VBT claim are DP or eDP.
14248                  */
14249                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14250                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14251                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14252                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14253                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14254                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14255
14256                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14257                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14258                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14259                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14260                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14261                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14262
14263                 if (IS_CHERRYVIEW(dev_priv)) {
14264                         /*
14265                          * eDP not supported on port D,
14266                          * so no need to worry about it
14267                          */
14268                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14269                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14270                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14271                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14272                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14273                 }
14274
14275                 vlv_dsi_init(dev_priv);
14276         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14277                 bool found = false;
14278
14279                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14280                         DRM_DEBUG_KMS("probing SDVOB\n");
14281                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14282                         if (!found && IS_G4X(dev_priv)) {
14283                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14284                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14285                         }
14286
14287                         if (!found && IS_G4X(dev_priv))
14288                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14289                 }
14290
14291                 /* Before G4X SDVOC doesn't have its own detect register */
14292
14293                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14294                         DRM_DEBUG_KMS("probing SDVOC\n");
14295                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14296                 }
14297
14298                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14299
14300                         if (IS_G4X(dev_priv)) {
14301                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14302                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14303                         }
14304                         if (IS_G4X(dev_priv))
14305                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14306                 }
14307
14308                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14309                         intel_dp_init(dev_priv, DP_D, PORT_D);
14310         } else if (IS_GEN2(dev_priv))
14311                 intel_dvo_init(dev_priv);
14312
14313         if (SUPPORTS_TV(dev_priv))
14314                 intel_tv_init(dev_priv);
14315
14316         intel_psr_init(dev_priv);
14317
14318         for_each_intel_encoder(&dev_priv->drm, encoder) {
14319                 encoder->base.possible_crtcs = encoder->crtc_mask;
14320                 encoder->base.possible_clones =
14321                         intel_encoder_clones(encoder);
14322         }
14323
14324         intel_init_pch_refclk(dev_priv);
14325
14326         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14327 }
14328
14329 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14330 {
14331         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14332         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14333
14334         drm_framebuffer_cleanup(fb);
14335
14336         i915_gem_object_lock(obj);
14337         WARN_ON(!obj->framebuffer_references--);
14338         i915_gem_object_unlock(obj);
14339
14340         i915_gem_object_put(obj);
14341
14342         kfree(intel_fb);
14343 }
14344
14345 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14346                                                 struct drm_file *file,
14347                                                 unsigned int *handle)
14348 {
14349         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14350
14351         if (obj->userptr.mm) {
14352                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14353                 return -EINVAL;
14354         }
14355
14356         return drm_gem_handle_create(file, &obj->base, handle);
14357 }
14358
14359 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14360                                         struct drm_file *file,
14361                                         unsigned flags, unsigned color,
14362                                         struct drm_clip_rect *clips,
14363                                         unsigned num_clips)
14364 {
14365         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14366
14367         i915_gem_object_flush_if_display(obj);
14368         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14369
14370         return 0;
14371 }
14372
14373 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14374         .destroy = intel_user_framebuffer_destroy,
14375         .create_handle = intel_user_framebuffer_create_handle,
14376         .dirty = intel_user_framebuffer_dirty,
14377 };
14378
14379 static
14380 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14381                          uint64_t fb_modifier, uint32_t pixel_format)
14382 {
14383         u32 gen = INTEL_GEN(dev_priv);
14384
14385         if (gen >= 9) {
14386                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14387
14388                 /* "The stride in bytes must not exceed the of the size of 8K
14389                  *  pixels and 32K bytes."
14390                  */
14391                 return min(8192 * cpp, 32768);
14392         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
14393                 return 32*1024;
14394         } else if (gen >= 4) {
14395                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14396                         return 16*1024;
14397                 else
14398                         return 32*1024;
14399         } else if (gen >= 3) {
14400                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14401                         return 8*1024;
14402                 else
14403                         return 16*1024;
14404         } else {
14405                 /* XXX DSPC is limited to 4k tiled */
14406                 return 8*1024;
14407         }
14408 }
14409
14410 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14411                                   struct drm_i915_gem_object *obj,
14412                                   struct drm_mode_fb_cmd2 *mode_cmd)
14413 {
14414         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14415         struct drm_framebuffer *fb = &intel_fb->base;
14416         struct drm_format_name_buf format_name;
14417         u32 pitch_limit;
14418         unsigned int tiling, stride;
14419         int ret = -EINVAL;
14420         int i;
14421
14422         i915_gem_object_lock(obj);
14423         obj->framebuffer_references++;
14424         tiling = i915_gem_object_get_tiling(obj);
14425         stride = i915_gem_object_get_stride(obj);
14426         i915_gem_object_unlock(obj);
14427
14428         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14429                 /*
14430                  * If there's a fence, enforce that
14431                  * the fb modifier and tiling mode match.
14432                  */
14433                 if (tiling != I915_TILING_NONE &&
14434                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14435                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14436                         goto err;
14437                 }
14438         } else {
14439                 if (tiling == I915_TILING_X) {
14440                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14441                 } else if (tiling == I915_TILING_Y) {
14442                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14443                         goto err;
14444                 }
14445         }
14446
14447         /* Passed in modifier sanity checking. */
14448         switch (mode_cmd->modifier[0]) {
14449         case I915_FORMAT_MOD_Y_TILED_CCS:
14450         case I915_FORMAT_MOD_Yf_TILED_CCS:
14451                 switch (mode_cmd->pixel_format) {
14452                 case DRM_FORMAT_XBGR8888:
14453                 case DRM_FORMAT_ABGR8888:
14454                 case DRM_FORMAT_XRGB8888:
14455                 case DRM_FORMAT_ARGB8888:
14456                         break;
14457                 default:
14458                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14459                         goto err;
14460                 }
14461                 /* fall through */
14462         case I915_FORMAT_MOD_Y_TILED:
14463         case I915_FORMAT_MOD_Yf_TILED:
14464                 if (INTEL_GEN(dev_priv) < 9) {
14465                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14466                                       mode_cmd->modifier[0]);
14467                         goto err;
14468                 }
14469         case DRM_FORMAT_MOD_LINEAR:
14470         case I915_FORMAT_MOD_X_TILED:
14471                 break;
14472         default:
14473                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14474                               mode_cmd->modifier[0]);
14475                 goto err;
14476         }
14477
14478         /*
14479          * gen2/3 display engine uses the fence if present,
14480          * so the tiling mode must match the fb modifier exactly.
14481          */
14482         if (INTEL_GEN(dev_priv) < 4 &&
14483             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14484                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14485                 goto err;
14486         }
14487
14488         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14489                                            mode_cmd->pixel_format);
14490         if (mode_cmd->pitches[0] > pitch_limit) {
14491                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14492                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14493                               "tiled" : "linear",
14494                               mode_cmd->pitches[0], pitch_limit);
14495                 goto err;
14496         }
14497
14498         /*
14499          * If there's a fence, enforce that
14500          * the fb pitch and fence stride match.
14501          */
14502         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14503                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14504                               mode_cmd->pitches[0], stride);
14505                 goto err;
14506         }
14507
14508         /* Reject formats not supported by any plane early. */
14509         switch (mode_cmd->pixel_format) {
14510         case DRM_FORMAT_C8:
14511         case DRM_FORMAT_RGB565:
14512         case DRM_FORMAT_XRGB8888:
14513         case DRM_FORMAT_ARGB8888:
14514                 break;
14515         case DRM_FORMAT_XRGB1555:
14516                 if (INTEL_GEN(dev_priv) > 3) {
14517                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14518                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14519                         goto err;
14520                 }
14521                 break;
14522         case DRM_FORMAT_ABGR8888:
14523                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14524                     INTEL_GEN(dev_priv) < 9) {
14525                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14526                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14527                         goto err;
14528                 }
14529                 break;
14530         case DRM_FORMAT_XBGR8888:
14531         case DRM_FORMAT_XRGB2101010:
14532         case DRM_FORMAT_XBGR2101010:
14533                 if (INTEL_GEN(dev_priv) < 4) {
14534                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14535                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14536                         goto err;
14537                 }
14538                 break;
14539         case DRM_FORMAT_ABGR2101010:
14540                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14541                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14542                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14543                         goto err;
14544                 }
14545                 break;
14546         case DRM_FORMAT_YUYV:
14547         case DRM_FORMAT_UYVY:
14548         case DRM_FORMAT_YVYU:
14549         case DRM_FORMAT_VYUY:
14550                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14551                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14552                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14553                         goto err;
14554                 }
14555                 break;
14556         case DRM_FORMAT_NV12:
14557                 if (INTEL_GEN(dev_priv) < 9 || IS_SKYLAKE(dev_priv) ||
14558                     IS_BROXTON(dev_priv) || INTEL_GEN(dev_priv) >= 11) {
14559                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14560                                       drm_get_format_name(mode_cmd->pixel_format,
14561                                                           &format_name));
14562                         goto err;
14563                 }
14564                 break;
14565         default:
14566                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14567                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14568                 goto err;
14569         }
14570
14571         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14572         if (mode_cmd->offsets[0] != 0)
14573                 goto err;
14574
14575         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14576
14577         if (fb->format->format == DRM_FORMAT_NV12 &&
14578             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14579              fb->height < SKL_MIN_YUV_420_SRC_H ||
14580              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14581                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14582                 return -EINVAL;
14583         }
14584
14585         for (i = 0; i < fb->format->num_planes; i++) {
14586                 u32 stride_alignment;
14587
14588                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14589                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14590                         goto err;
14591                 }
14592
14593                 stride_alignment = intel_fb_stride_alignment(fb, i);
14594
14595                 /*
14596                  * Display WA #0531: skl,bxt,kbl,glk
14597                  *
14598                  * Render decompression and plane width > 3840
14599                  * combined with horizontal panning requires the
14600                  * plane stride to be a multiple of 4. We'll just
14601                  * require the entire fb to accommodate that to avoid
14602                  * potential runtime errors at plane configuration time.
14603                  */
14604                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14605                     is_ccs_modifier(fb->modifier))
14606                         stride_alignment *= 4;
14607
14608                 if (fb->pitches[i] & (stride_alignment - 1)) {
14609                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14610                                       i, fb->pitches[i], stride_alignment);
14611                         goto err;
14612                 }
14613
14614                 fb->obj[i] = &obj->base;
14615         }
14616
14617         ret = intel_fill_fb_info(dev_priv, fb);
14618         if (ret)
14619                 goto err;
14620
14621         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14622         if (ret) {
14623                 DRM_ERROR("framebuffer init failed %d\n", ret);
14624                 goto err;
14625         }
14626
14627         return 0;
14628
14629 err:
14630         i915_gem_object_lock(obj);
14631         obj->framebuffer_references--;
14632         i915_gem_object_unlock(obj);
14633         return ret;
14634 }
14635
14636 static struct drm_framebuffer *
14637 intel_user_framebuffer_create(struct drm_device *dev,
14638                               struct drm_file *filp,
14639                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14640 {
14641         struct drm_framebuffer *fb;
14642         struct drm_i915_gem_object *obj;
14643         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14644
14645         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14646         if (!obj)
14647                 return ERR_PTR(-ENOENT);
14648
14649         fb = intel_framebuffer_create(obj, &mode_cmd);
14650         if (IS_ERR(fb))
14651                 i915_gem_object_put(obj);
14652
14653         return fb;
14654 }
14655
14656 static void intel_atomic_state_free(struct drm_atomic_state *state)
14657 {
14658         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14659
14660         drm_atomic_state_default_release(state);
14661
14662         i915_sw_fence_fini(&intel_state->commit_ready);
14663
14664         kfree(state);
14665 }
14666
14667 static enum drm_mode_status
14668 intel_mode_valid(struct drm_device *dev,
14669                  const struct drm_display_mode *mode)
14670 {
14671         struct drm_i915_private *dev_priv = to_i915(dev);
14672         int hdisplay_max, htotal_max;
14673         int vdisplay_max, vtotal_max;
14674
14675         /*
14676          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14677          * of DBLSCAN modes to the output's mode list when they detect
14678          * the scaling mode property on the connector. And they don't
14679          * ask the kernel to validate those modes in any way until
14680          * modeset time at which point the client gets a protocol error.
14681          * So in order to not upset those clients we silently ignore the
14682          * DBLSCAN flag on such connectors. For other connectors we will
14683          * reject modes with the DBLSCAN flag in encoder->compute_config().
14684          * And we always reject DBLSCAN modes in connector->mode_valid()
14685          * as we never want such modes on the connector's mode list.
14686          */
14687
14688         if (mode->vscan > 1)
14689                 return MODE_NO_VSCAN;
14690
14691         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14692                 return MODE_H_ILLEGAL;
14693
14694         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14695                            DRM_MODE_FLAG_NCSYNC |
14696                            DRM_MODE_FLAG_PCSYNC))
14697                 return MODE_HSYNC;
14698
14699         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14700                            DRM_MODE_FLAG_PIXMUX |
14701                            DRM_MODE_FLAG_CLKDIV2))
14702                 return MODE_BAD;
14703
14704         if (INTEL_GEN(dev_priv) >= 9 ||
14705             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14706                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14707                 vdisplay_max = 4096;
14708                 htotal_max = 8192;
14709                 vtotal_max = 8192;
14710         } else if (INTEL_GEN(dev_priv) >= 3) {
14711                 hdisplay_max = 4096;
14712                 vdisplay_max = 4096;
14713                 htotal_max = 8192;
14714                 vtotal_max = 8192;
14715         } else {
14716                 hdisplay_max = 2048;
14717                 vdisplay_max = 2048;
14718                 htotal_max = 4096;
14719                 vtotal_max = 4096;
14720         }
14721
14722         if (mode->hdisplay > hdisplay_max ||
14723             mode->hsync_start > htotal_max ||
14724             mode->hsync_end > htotal_max ||
14725             mode->htotal > htotal_max)
14726                 return MODE_H_ILLEGAL;
14727
14728         if (mode->vdisplay > vdisplay_max ||
14729             mode->vsync_start > vtotal_max ||
14730             mode->vsync_end > vtotal_max ||
14731             mode->vtotal > vtotal_max)
14732                 return MODE_V_ILLEGAL;
14733
14734         return MODE_OK;
14735 }
14736
14737 static const struct drm_mode_config_funcs intel_mode_funcs = {
14738         .fb_create = intel_user_framebuffer_create,
14739         .get_format_info = intel_get_format_info,
14740         .output_poll_changed = intel_fbdev_output_poll_changed,
14741         .mode_valid = intel_mode_valid,
14742         .atomic_check = intel_atomic_check,
14743         .atomic_commit = intel_atomic_commit,
14744         .atomic_state_alloc = intel_atomic_state_alloc,
14745         .atomic_state_clear = intel_atomic_state_clear,
14746         .atomic_state_free = intel_atomic_state_free,
14747 };
14748
14749 /**
14750  * intel_init_display_hooks - initialize the display modesetting hooks
14751  * @dev_priv: device private
14752  */
14753 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14754 {
14755         intel_init_cdclk_hooks(dev_priv);
14756
14757         if (INTEL_GEN(dev_priv) >= 9) {
14758                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14759                 dev_priv->display.get_initial_plane_config =
14760                         skylake_get_initial_plane_config;
14761                 dev_priv->display.crtc_compute_clock =
14762                         haswell_crtc_compute_clock;
14763                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14764                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14765         } else if (HAS_DDI(dev_priv)) {
14766                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14767                 dev_priv->display.get_initial_plane_config =
14768                         i9xx_get_initial_plane_config;
14769                 dev_priv->display.crtc_compute_clock =
14770                         haswell_crtc_compute_clock;
14771                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14772                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14773         } else if (HAS_PCH_SPLIT(dev_priv)) {
14774                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14775                 dev_priv->display.get_initial_plane_config =
14776                         i9xx_get_initial_plane_config;
14777                 dev_priv->display.crtc_compute_clock =
14778                         ironlake_crtc_compute_clock;
14779                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14780                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14781         } else if (IS_CHERRYVIEW(dev_priv)) {
14782                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14783                 dev_priv->display.get_initial_plane_config =
14784                         i9xx_get_initial_plane_config;
14785                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14786                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14787                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14788         } else if (IS_VALLEYVIEW(dev_priv)) {
14789                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14790                 dev_priv->display.get_initial_plane_config =
14791                         i9xx_get_initial_plane_config;
14792                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14793                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14794                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14795         } else if (IS_G4X(dev_priv)) {
14796                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14797                 dev_priv->display.get_initial_plane_config =
14798                         i9xx_get_initial_plane_config;
14799                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14800                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14801                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14802         } else if (IS_PINEVIEW(dev_priv)) {
14803                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14804                 dev_priv->display.get_initial_plane_config =
14805                         i9xx_get_initial_plane_config;
14806                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14807                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14808                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14809         } else if (!IS_GEN2(dev_priv)) {
14810                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14811                 dev_priv->display.get_initial_plane_config =
14812                         i9xx_get_initial_plane_config;
14813                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14814                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14815                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14816         } else {
14817                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14818                 dev_priv->display.get_initial_plane_config =
14819                         i9xx_get_initial_plane_config;
14820                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14821                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14822                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14823         }
14824
14825         if (IS_GEN5(dev_priv)) {
14826                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14827         } else if (IS_GEN6(dev_priv)) {
14828                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14829         } else if (IS_IVYBRIDGE(dev_priv)) {
14830                 /* FIXME: detect B0+ stepping and use auto training */
14831                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14832         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14833                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14834         }
14835
14836         if (INTEL_GEN(dev_priv) >= 9)
14837                 dev_priv->display.update_crtcs = skl_update_crtcs;
14838         else
14839                 dev_priv->display.update_crtcs = intel_update_crtcs;
14840 }
14841
14842 /*
14843  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14844  */
14845 static void quirk_ssc_force_disable(struct drm_device *dev)
14846 {
14847         struct drm_i915_private *dev_priv = to_i915(dev);
14848         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14849         DRM_INFO("applying lvds SSC disable quirk\n");
14850 }
14851
14852 /*
14853  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14854  * brightness value
14855  */
14856 static void quirk_invert_brightness(struct drm_device *dev)
14857 {
14858         struct drm_i915_private *dev_priv = to_i915(dev);
14859         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14860         DRM_INFO("applying inverted panel brightness quirk\n");
14861 }
14862
14863 /* Some VBT's incorrectly indicate no backlight is present */
14864 static void quirk_backlight_present(struct drm_device *dev)
14865 {
14866         struct drm_i915_private *dev_priv = to_i915(dev);
14867         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14868         DRM_INFO("applying backlight present quirk\n");
14869 }
14870
14871 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14872  * which is 300 ms greater than eDP spec T12 min.
14873  */
14874 static void quirk_increase_t12_delay(struct drm_device *dev)
14875 {
14876         struct drm_i915_private *dev_priv = to_i915(dev);
14877
14878         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14879         DRM_INFO("Applying T12 delay quirk\n");
14880 }
14881
14882 /*
14883  * GeminiLake NUC HDMI outputs require additional off time
14884  * this allows the onboard retimer to correctly sync to signal
14885  */
14886 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14887 {
14888         struct drm_i915_private *dev_priv = to_i915(dev);
14889
14890         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14891         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14892 }
14893
14894 struct intel_quirk {
14895         int device;
14896         int subsystem_vendor;
14897         int subsystem_device;
14898         void (*hook)(struct drm_device *dev);
14899 };
14900
14901 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14902 struct intel_dmi_quirk {
14903         void (*hook)(struct drm_device *dev);
14904         const struct dmi_system_id (*dmi_id_list)[];
14905 };
14906
14907 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14908 {
14909         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14910         return 1;
14911 }
14912
14913 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14914         {
14915                 .dmi_id_list = &(const struct dmi_system_id[]) {
14916                         {
14917                                 .callback = intel_dmi_reverse_brightness,
14918                                 .ident = "NCR Corporation",
14919                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14920                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14921                                 },
14922                         },
14923                         { }  /* terminating entry */
14924                 },
14925                 .hook = quirk_invert_brightness,
14926         },
14927 };
14928
14929 static struct intel_quirk intel_quirks[] = {
14930         /* Lenovo U160 cannot use SSC on LVDS */
14931         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14932
14933         /* Sony Vaio Y cannot use SSC on LVDS */
14934         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14935
14936         /* Acer Aspire 5734Z must invert backlight brightness */
14937         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14938
14939         /* Acer/eMachines G725 */
14940         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14941
14942         /* Acer/eMachines e725 */
14943         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14944
14945         /* Acer/Packard Bell NCL20 */
14946         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14947
14948         /* Acer Aspire 4736Z */
14949         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14950
14951         /* Acer Aspire 5336 */
14952         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14953
14954         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14955         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14956
14957         /* Acer C720 Chromebook (Core i3 4005U) */
14958         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14959
14960         /* Apple Macbook 2,1 (Core 2 T7400) */
14961         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14962
14963         /* Apple Macbook 4,1 */
14964         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14965
14966         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14967         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14968
14969         /* HP Chromebook 14 (Celeron 2955U) */
14970         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14971
14972         /* Dell Chromebook 11 */
14973         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14974
14975         /* Dell Chromebook 11 (2015 version) */
14976         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14977
14978         /* Toshiba Satellite P50-C-18C */
14979         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14980
14981         /* GeminiLake NUC */
14982         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14983         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14984         /* ASRock ITX*/
14985         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14986         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14987 };
14988
14989 static void intel_init_quirks(struct drm_device *dev)
14990 {
14991         struct pci_dev *d = dev->pdev;
14992         int i;
14993
14994         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14995                 struct intel_quirk *q = &intel_quirks[i];
14996
14997                 if (d->device == q->device &&
14998                     (d->subsystem_vendor == q->subsystem_vendor ||
14999                      q->subsystem_vendor == PCI_ANY_ID) &&
15000                     (d->subsystem_device == q->subsystem_device ||
15001                      q->subsystem_device == PCI_ANY_ID))
15002                         q->hook(dev);
15003         }
15004         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15005                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15006                         intel_dmi_quirks[i].hook(dev);
15007         }
15008 }
15009
15010 /* Disable the VGA plane that we never use */
15011 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15012 {
15013         struct pci_dev *pdev = dev_priv->drm.pdev;
15014         u8 sr1;
15015         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15016
15017         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15018         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15019         outb(SR01, VGA_SR_INDEX);
15020         sr1 = inb(VGA_SR_DATA);
15021         outb(sr1 | 1<<5, VGA_SR_DATA);
15022         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15023         udelay(300);
15024
15025         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15026         POSTING_READ(vga_reg);
15027 }
15028
15029 void intel_modeset_init_hw(struct drm_device *dev)
15030 {
15031         struct drm_i915_private *dev_priv = to_i915(dev);
15032
15033         intel_update_cdclk(dev_priv);
15034         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15035         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15036 }
15037
15038 /*
15039  * Calculate what we think the watermarks should be for the state we've read
15040  * out of the hardware and then immediately program those watermarks so that
15041  * we ensure the hardware settings match our internal state.
15042  *
15043  * We can calculate what we think WM's should be by creating a duplicate of the
15044  * current state (which was constructed during hardware readout) and running it
15045  * through the atomic check code to calculate new watermark values in the
15046  * state object.
15047  */
15048 static void sanitize_watermarks(struct drm_device *dev)
15049 {
15050         struct drm_i915_private *dev_priv = to_i915(dev);
15051         struct drm_atomic_state *state;
15052         struct intel_atomic_state *intel_state;
15053         struct drm_crtc *crtc;
15054         struct drm_crtc_state *cstate;
15055         struct drm_modeset_acquire_ctx ctx;
15056         int ret;
15057         int i;
15058
15059         /* Only supported on platforms that use atomic watermark design */
15060         if (!dev_priv->display.optimize_watermarks)
15061                 return;
15062
15063         /*
15064          * We need to hold connection_mutex before calling duplicate_state so
15065          * that the connector loop is protected.
15066          */
15067         drm_modeset_acquire_init(&ctx, 0);
15068 retry:
15069         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15070         if (ret == -EDEADLK) {
15071                 drm_modeset_backoff(&ctx);
15072                 goto retry;
15073         } else if (WARN_ON(ret)) {
15074                 goto fail;
15075         }
15076
15077         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15078         if (WARN_ON(IS_ERR(state)))
15079                 goto fail;
15080
15081         intel_state = to_intel_atomic_state(state);
15082
15083         /*
15084          * Hardware readout is the only time we don't want to calculate
15085          * intermediate watermarks (since we don't trust the current
15086          * watermarks).
15087          */
15088         if (!HAS_GMCH_DISPLAY(dev_priv))
15089                 intel_state->skip_intermediate_wm = true;
15090
15091         ret = intel_atomic_check(dev, state);
15092         if (ret) {
15093                 /*
15094                  * If we fail here, it means that the hardware appears to be
15095                  * programmed in a way that shouldn't be possible, given our
15096                  * understanding of watermark requirements.  This might mean a
15097                  * mistake in the hardware readout code or a mistake in the
15098                  * watermark calculations for a given platform.  Raise a WARN
15099                  * so that this is noticeable.
15100                  *
15101                  * If this actually happens, we'll have to just leave the
15102                  * BIOS-programmed watermarks untouched and hope for the best.
15103                  */
15104                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15105                 goto put_state;
15106         }
15107
15108         /* Write calculated watermark values back */
15109         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15110                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15111
15112                 cs->wm.need_postvbl_update = true;
15113                 dev_priv->display.optimize_watermarks(intel_state, cs);
15114
15115                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15116         }
15117
15118 put_state:
15119         drm_atomic_state_put(state);
15120 fail:
15121         drm_modeset_drop_locks(&ctx);
15122         drm_modeset_acquire_fini(&ctx);
15123 }
15124
15125 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15126 {
15127         if (IS_GEN5(dev_priv)) {
15128                 u32 fdi_pll_clk =
15129                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15130
15131                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15132         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
15133                 dev_priv->fdi_pll_freq = 270000;
15134         } else {
15135                 return;
15136         }
15137
15138         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15139 }
15140
15141 static int intel_initial_commit(struct drm_device *dev)
15142 {
15143         struct drm_atomic_state *state = NULL;
15144         struct drm_modeset_acquire_ctx ctx;
15145         struct drm_crtc *crtc;
15146         struct drm_crtc_state *crtc_state;
15147         int ret = 0;
15148
15149         state = drm_atomic_state_alloc(dev);
15150         if (!state)
15151                 return -ENOMEM;
15152
15153         drm_modeset_acquire_init(&ctx, 0);
15154
15155 retry:
15156         state->acquire_ctx = &ctx;
15157
15158         drm_for_each_crtc(crtc, dev) {
15159                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15160                 if (IS_ERR(crtc_state)) {
15161                         ret = PTR_ERR(crtc_state);
15162                         goto out;
15163                 }
15164
15165                 if (crtc_state->active) {
15166                         ret = drm_atomic_add_affected_planes(state, crtc);
15167                         if (ret)
15168                                 goto out;
15169                 }
15170         }
15171
15172         ret = drm_atomic_commit(state);
15173
15174 out:
15175         if (ret == -EDEADLK) {
15176                 drm_atomic_state_clear(state);
15177                 drm_modeset_backoff(&ctx);
15178                 goto retry;
15179         }
15180
15181         drm_atomic_state_put(state);
15182
15183         drm_modeset_drop_locks(&ctx);
15184         drm_modeset_acquire_fini(&ctx);
15185
15186         return ret;
15187 }
15188
15189 int intel_modeset_init(struct drm_device *dev)
15190 {
15191         struct drm_i915_private *dev_priv = to_i915(dev);
15192         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15193         enum pipe pipe;
15194         struct intel_crtc *crtc;
15195         int ret;
15196
15197         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15198
15199         drm_mode_config_init(dev);
15200
15201         dev->mode_config.min_width = 0;
15202         dev->mode_config.min_height = 0;
15203
15204         dev->mode_config.preferred_depth = 24;
15205         dev->mode_config.prefer_shadow = 1;
15206
15207         dev->mode_config.allow_fb_modifiers = true;
15208
15209         dev->mode_config.funcs = &intel_mode_funcs;
15210
15211         init_llist_head(&dev_priv->atomic_helper.free_list);
15212         INIT_WORK(&dev_priv->atomic_helper.free_work,
15213                   intel_atomic_helper_free_state_worker);
15214
15215         intel_init_quirks(dev);
15216
15217         intel_init_pm(dev_priv);
15218
15219         /*
15220          * There may be no VBT; and if the BIOS enabled SSC we can
15221          * just keep using it to avoid unnecessary flicker.  Whereas if the
15222          * BIOS isn't using it, don't assume it will work even if the VBT
15223          * indicates as much.
15224          */
15225         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15226                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15227                                             DREF_SSC1_ENABLE);
15228
15229                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15230                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15231                                      bios_lvds_use_ssc ? "en" : "dis",
15232                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15233                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15234                 }
15235         }
15236
15237         /* maximum framebuffer dimensions */
15238         if (IS_GEN2(dev_priv)) {
15239                 dev->mode_config.max_width = 2048;
15240                 dev->mode_config.max_height = 2048;
15241         } else if (IS_GEN3(dev_priv)) {
15242                 dev->mode_config.max_width = 4096;
15243                 dev->mode_config.max_height = 4096;
15244         } else {
15245                 dev->mode_config.max_width = 8192;
15246                 dev->mode_config.max_height = 8192;
15247         }
15248
15249         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15250                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15251                 dev->mode_config.cursor_height = 1023;
15252         } else if (IS_GEN2(dev_priv)) {
15253                 dev->mode_config.cursor_width = 64;
15254                 dev->mode_config.cursor_height = 64;
15255         } else {
15256                 dev->mode_config.cursor_width = 256;
15257                 dev->mode_config.cursor_height = 256;
15258         }
15259
15260         dev->mode_config.fb_base = ggtt->gmadr.start;
15261
15262         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15263                       INTEL_INFO(dev_priv)->num_pipes,
15264                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15265
15266         for_each_pipe(dev_priv, pipe) {
15267                 ret = intel_crtc_init(dev_priv, pipe);
15268                 if (ret) {
15269                         drm_mode_config_cleanup(dev);
15270                         return ret;
15271                 }
15272         }
15273
15274         intel_shared_dpll_init(dev);
15275         intel_update_fdi_pll_freq(dev_priv);
15276
15277         intel_update_czclk(dev_priv);
15278         intel_modeset_init_hw(dev);
15279
15280         if (dev_priv->max_cdclk_freq == 0)
15281                 intel_update_max_cdclk(dev_priv);
15282
15283         /* Just disable it once at startup */
15284         i915_disable_vga(dev_priv);
15285         intel_setup_outputs(dev_priv);
15286
15287         drm_modeset_lock_all(dev);
15288         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15289         drm_modeset_unlock_all(dev);
15290
15291         for_each_intel_crtc(dev, crtc) {
15292                 struct intel_initial_plane_config plane_config = {};
15293
15294                 if (!crtc->active)
15295                         continue;
15296
15297                 /*
15298                  * Note that reserving the BIOS fb up front prevents us
15299                  * from stuffing other stolen allocations like the ring
15300                  * on top.  This prevents some ugliness at boot time, and
15301                  * can even allow for smooth boot transitions if the BIOS
15302                  * fb is large enough for the active pipe configuration.
15303                  */
15304                 dev_priv->display.get_initial_plane_config(crtc,
15305                                                            &plane_config);
15306
15307                 /*
15308                  * If the fb is shared between multiple heads, we'll
15309                  * just get the first one.
15310                  */
15311                 intel_find_initial_plane_obj(crtc, &plane_config);
15312         }
15313
15314         /*
15315          * Make sure hardware watermarks really match the state we read out.
15316          * Note that we need to do this after reconstructing the BIOS fb's
15317          * since the watermark calculation done here will use pstate->fb.
15318          */
15319         if (!HAS_GMCH_DISPLAY(dev_priv))
15320                 sanitize_watermarks(dev);
15321
15322         /*
15323          * Force all active planes to recompute their states. So that on
15324          * mode_setcrtc after probe, all the intel_plane_state variables
15325          * are already calculated and there is no assert_plane warnings
15326          * during bootup.
15327          */
15328         ret = intel_initial_commit(dev);
15329         if (ret)
15330                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15331
15332         return 0;
15333 }
15334
15335 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15336 {
15337         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15338         /* 640x480@60Hz, ~25175 kHz */
15339         struct dpll clock = {
15340                 .m1 = 18,
15341                 .m2 = 7,
15342                 .p1 = 13,
15343                 .p2 = 4,
15344                 .n = 2,
15345         };
15346         u32 dpll, fp;
15347         int i;
15348
15349         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15350
15351         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15352                       pipe_name(pipe), clock.vco, clock.dot);
15353
15354         fp = i9xx_dpll_compute_fp(&clock);
15355         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15356                 DPLL_VGA_MODE_DIS |
15357                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15358                 PLL_P2_DIVIDE_BY_4 |
15359                 PLL_REF_INPUT_DREFCLK |
15360                 DPLL_VCO_ENABLE;
15361
15362         I915_WRITE(FP0(pipe), fp);
15363         I915_WRITE(FP1(pipe), fp);
15364
15365         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15366         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15367         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15368         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15369         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15370         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15371         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15372
15373         /*
15374          * Apparently we need to have VGA mode enabled prior to changing
15375          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15376          * dividers, even though the register value does change.
15377          */
15378         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15379         I915_WRITE(DPLL(pipe), dpll);
15380
15381         /* Wait for the clocks to stabilize. */
15382         POSTING_READ(DPLL(pipe));
15383         udelay(150);
15384
15385         /* The pixel multiplier can only be updated once the
15386          * DPLL is enabled and the clocks are stable.
15387          *
15388          * So write it again.
15389          */
15390         I915_WRITE(DPLL(pipe), dpll);
15391
15392         /* We do this three times for luck */
15393         for (i = 0; i < 3 ; i++) {
15394                 I915_WRITE(DPLL(pipe), dpll);
15395                 POSTING_READ(DPLL(pipe));
15396                 udelay(150); /* wait for warmup */
15397         }
15398
15399         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15400         POSTING_READ(PIPECONF(pipe));
15401
15402         intel_wait_for_pipe_scanline_moving(crtc);
15403 }
15404
15405 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15406 {
15407         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15408
15409         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15410                       pipe_name(pipe));
15411
15412         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15413         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15414         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15415         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15416         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15417
15418         I915_WRITE(PIPECONF(pipe), 0);
15419         POSTING_READ(PIPECONF(pipe));
15420
15421         intel_wait_for_pipe_scanline_stopped(crtc);
15422
15423         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15424         POSTING_READ(DPLL(pipe));
15425 }
15426
15427 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
15428                                    struct intel_plane *plane)
15429 {
15430         enum pipe pipe;
15431
15432         if (!plane->get_hw_state(plane, &pipe))
15433                 return true;
15434
15435         return pipe == crtc->pipe;
15436 }
15437
15438 static void
15439 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15440 {
15441         struct intel_crtc *crtc;
15442
15443         if (INTEL_GEN(dev_priv) >= 4)
15444                 return;
15445
15446         for_each_intel_crtc(&dev_priv->drm, crtc) {
15447                 struct intel_plane *plane =
15448                         to_intel_plane(crtc->base.primary);
15449
15450                 if (intel_plane_mapping_ok(crtc, plane))
15451                         continue;
15452
15453                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
15454                               plane->base.name);
15455                 intel_plane_disable_noatomic(crtc, plane);
15456         }
15457 }
15458
15459 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15460 {
15461         struct drm_device *dev = crtc->base.dev;
15462         struct intel_encoder *encoder;
15463
15464         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15465                 return true;
15466
15467         return false;
15468 }
15469
15470 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15471 {
15472         struct drm_device *dev = encoder->base.dev;
15473         struct intel_connector *connector;
15474
15475         for_each_connector_on_encoder(dev, &encoder->base, connector)
15476                 return connector;
15477
15478         return NULL;
15479 }
15480
15481 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15482                               enum pipe pch_transcoder)
15483 {
15484         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15485                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15486 }
15487
15488 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15489                                 struct drm_modeset_acquire_ctx *ctx)
15490 {
15491         struct drm_device *dev = crtc->base.dev;
15492         struct drm_i915_private *dev_priv = to_i915(dev);
15493         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15494
15495         /* Clear any frame start delays used for debugging left by the BIOS */
15496         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15497                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15498
15499                 I915_WRITE(reg,
15500                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15501         }
15502
15503         /* restore vblank interrupts to correct state */
15504         drm_crtc_vblank_reset(&crtc->base);
15505         if (crtc->active) {
15506                 struct intel_plane *plane;
15507
15508                 drm_crtc_vblank_on(&crtc->base);
15509
15510                 /* Disable everything but the primary plane */
15511                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15512                         const struct intel_plane_state *plane_state =
15513                                 to_intel_plane_state(plane->base.state);
15514
15515                         if (plane_state->base.visible &&
15516                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15517                                 intel_plane_disable_noatomic(crtc, plane);
15518                 }
15519         }
15520
15521         /* Adjust the state of the output pipe according to whether we
15522          * have active connectors/encoders. */
15523         if (crtc->active && !intel_crtc_has_encoders(crtc))
15524                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15525
15526         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15527                 /*
15528                  * We start out with underrun reporting disabled to avoid races.
15529                  * For correct bookkeeping mark this on active crtcs.
15530                  *
15531                  * Also on gmch platforms we dont have any hardware bits to
15532                  * disable the underrun reporting. Which means we need to start
15533                  * out with underrun reporting disabled also on inactive pipes,
15534                  * since otherwise we'll complain about the garbage we read when
15535                  * e.g. coming up after runtime pm.
15536                  *
15537                  * No protection against concurrent access is required - at
15538                  * worst a fifo underrun happens which also sets this to false.
15539                  */
15540                 crtc->cpu_fifo_underrun_disabled = true;
15541                 /*
15542                  * We track the PCH trancoder underrun reporting state
15543                  * within the crtc. With crtc for pipe A housing the underrun
15544                  * reporting state for PCH transcoder A, crtc for pipe B housing
15545                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15546                  * and marking underrun reporting as disabled for the non-existing
15547                  * PCH transcoders B and C would prevent enabling the south
15548                  * error interrupt (see cpt_can_enable_serr_int()).
15549                  */
15550                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15551                         crtc->pch_fifo_underrun_disabled = true;
15552         }
15553 }
15554
15555 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15556 {
15557         struct intel_connector *connector;
15558
15559         /* We need to check both for a crtc link (meaning that the
15560          * encoder is active and trying to read from a pipe) and the
15561          * pipe itself being active. */
15562         bool has_active_crtc = encoder->base.crtc &&
15563                 to_intel_crtc(encoder->base.crtc)->active;
15564
15565         connector = intel_encoder_find_connector(encoder);
15566         if (connector && !has_active_crtc) {
15567                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15568                               encoder->base.base.id,
15569                               encoder->base.name);
15570
15571                 /* Connector is active, but has no active pipe. This is
15572                  * fallout from our resume register restoring. Disable
15573                  * the encoder manually again. */
15574                 if (encoder->base.crtc) {
15575                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15576
15577                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15578                                       encoder->base.base.id,
15579                                       encoder->base.name);
15580                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15581                         if (encoder->post_disable)
15582                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15583                 }
15584                 encoder->base.crtc = NULL;
15585
15586                 /* Inconsistent output/port/pipe state happens presumably due to
15587                  * a bug in one of the get_hw_state functions. Or someplace else
15588                  * in our code, like the register restore mess on resume. Clamp
15589                  * things to off as a safer default. */
15590
15591                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15592                 connector->base.encoder = NULL;
15593         }
15594
15595         /* notify opregion of the sanitized encoder state */
15596         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15597 }
15598
15599 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15600 {
15601         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15602
15603         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15604                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15605                 i915_disable_vga(dev_priv);
15606         }
15607 }
15608
15609 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15610 {
15611         /* This function can be called both from intel_modeset_setup_hw_state or
15612          * at a very early point in our resume sequence, where the power well
15613          * structures are not yet restored. Since this function is at a very
15614          * paranoid "someone might have enabled VGA while we were not looking"
15615          * level, just check if the power well is enabled instead of trying to
15616          * follow the "don't touch the power well if we don't need it" policy
15617          * the rest of the driver uses. */
15618         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15619                 return;
15620
15621         i915_redisable_vga_power_on(dev_priv);
15622
15623         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15624 }
15625
15626 /* FIXME read out full plane state for all planes */
15627 static void readout_plane_state(struct intel_crtc *crtc)
15628 {
15629         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15630         struct intel_crtc_state *crtc_state =
15631                 to_intel_crtc_state(crtc->base.state);
15632         struct intel_plane *plane;
15633
15634         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
15635                 struct intel_plane_state *plane_state =
15636                         to_intel_plane_state(plane->base.state);
15637                 enum pipe pipe;
15638                 bool visible;
15639
15640                 visible = plane->get_hw_state(plane, &pipe);
15641
15642                 intel_set_plane_visible(crtc_state, plane_state, visible);
15643         }
15644 }
15645
15646 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15647 {
15648         struct drm_i915_private *dev_priv = to_i915(dev);
15649         enum pipe pipe;
15650         struct intel_crtc *crtc;
15651         struct intel_encoder *encoder;
15652         struct intel_connector *connector;
15653         struct drm_connector_list_iter conn_iter;
15654         int i;
15655
15656         dev_priv->active_crtcs = 0;
15657
15658         for_each_intel_crtc(dev, crtc) {
15659                 struct intel_crtc_state *crtc_state =
15660                         to_intel_crtc_state(crtc->base.state);
15661
15662                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15663                 memset(crtc_state, 0, sizeof(*crtc_state));
15664                 crtc_state->base.crtc = &crtc->base;
15665
15666                 crtc_state->base.active = crtc_state->base.enable =
15667                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15668
15669                 crtc->base.enabled = crtc_state->base.enable;
15670                 crtc->active = crtc_state->base.active;
15671
15672                 if (crtc_state->base.active)
15673                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15674
15675                 readout_plane_state(crtc);
15676
15677                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15678                               crtc->base.base.id, crtc->base.name,
15679                               enableddisabled(crtc_state->base.active));
15680         }
15681
15682         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15683                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15684
15685                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15686                                                         &pll->state.hw_state);
15687                 pll->state.crtc_mask = 0;
15688                 for_each_intel_crtc(dev, crtc) {
15689                         struct intel_crtc_state *crtc_state =
15690                                 to_intel_crtc_state(crtc->base.state);
15691
15692                         if (crtc_state->base.active &&
15693                             crtc_state->shared_dpll == pll)
15694                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15695                 }
15696                 pll->active_mask = pll->state.crtc_mask;
15697
15698                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15699                               pll->info->name, pll->state.crtc_mask, pll->on);
15700         }
15701
15702         for_each_intel_encoder(dev, encoder) {
15703                 pipe = 0;
15704
15705                 if (encoder->get_hw_state(encoder, &pipe)) {
15706                         struct intel_crtc_state *crtc_state;
15707
15708                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15709                         crtc_state = to_intel_crtc_state(crtc->base.state);
15710
15711                         encoder->base.crtc = &crtc->base;
15712                         encoder->get_config(encoder, crtc_state);
15713                 } else {
15714                         encoder->base.crtc = NULL;
15715                 }
15716
15717                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15718                               encoder->base.base.id, encoder->base.name,
15719                               enableddisabled(encoder->base.crtc),
15720                               pipe_name(pipe));
15721         }
15722
15723         drm_connector_list_iter_begin(dev, &conn_iter);
15724         for_each_intel_connector_iter(connector, &conn_iter) {
15725                 if (connector->get_hw_state(connector)) {
15726                         connector->base.dpms = DRM_MODE_DPMS_ON;
15727
15728                         encoder = connector->encoder;
15729                         connector->base.encoder = &encoder->base;
15730
15731                         if (encoder->base.crtc &&
15732                             encoder->base.crtc->state->active) {
15733                                 /*
15734                                  * This has to be done during hardware readout
15735                                  * because anything calling .crtc_disable may
15736                                  * rely on the connector_mask being accurate.
15737                                  */
15738                                 encoder->base.crtc->state->connector_mask |=
15739                                         drm_connector_mask(&connector->base);
15740                                 encoder->base.crtc->state->encoder_mask |=
15741                                         drm_encoder_mask(&encoder->base);
15742                         }
15743
15744                 } else {
15745                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15746                         connector->base.encoder = NULL;
15747                 }
15748                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15749                               connector->base.base.id, connector->base.name,
15750                               enableddisabled(connector->base.encoder));
15751         }
15752         drm_connector_list_iter_end(&conn_iter);
15753
15754         for_each_intel_crtc(dev, crtc) {
15755                 struct intel_crtc_state *crtc_state =
15756                         to_intel_crtc_state(crtc->base.state);
15757                 int min_cdclk = 0;
15758
15759                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15760                 if (crtc_state->base.active) {
15761                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15762                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15763                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15764                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15765                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15766
15767                         /*
15768                          * The initial mode needs to be set in order to keep
15769                          * the atomic core happy. It wants a valid mode if the
15770                          * crtc's enabled, so we do the above call.
15771                          *
15772                          * But we don't set all the derived state fully, hence
15773                          * set a flag to indicate that a full recalculation is
15774                          * needed on the next commit.
15775                          */
15776                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15777
15778                         intel_crtc_compute_pixel_rate(crtc_state);
15779
15780                         if (dev_priv->display.modeset_calc_cdclk) {
15781                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15782                                 if (WARN_ON(min_cdclk < 0))
15783                                         min_cdclk = 0;
15784                         }
15785
15786                         drm_calc_timestamping_constants(&crtc->base,
15787                                                         &crtc_state->base.adjusted_mode);
15788                         update_scanline_offset(crtc);
15789                 }
15790
15791                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15792                 dev_priv->min_voltage_level[crtc->pipe] =
15793                         crtc_state->min_voltage_level;
15794
15795                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15796         }
15797 }
15798
15799 static void
15800 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15801 {
15802         struct intel_encoder *encoder;
15803
15804         for_each_intel_encoder(&dev_priv->drm, encoder) {
15805                 u64 get_domains;
15806                 enum intel_display_power_domain domain;
15807                 struct intel_crtc_state *crtc_state;
15808
15809                 if (!encoder->get_power_domains)
15810                         continue;
15811
15812                 /*
15813                  * MST-primary and inactive encoders don't have a crtc state
15814                  * and neither of these require any power domain references.
15815                  */
15816                 if (!encoder->base.crtc)
15817                         continue;
15818
15819                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15820                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15821                 for_each_power_domain(domain, get_domains)
15822                         intel_display_power_get(dev_priv, domain);
15823         }
15824 }
15825
15826 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15827 {
15828         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15829         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15830                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15831                            DARBF_GATING_DIS);
15832
15833         if (IS_HASWELL(dev_priv)) {
15834                 /*
15835                  * WaRsPkgCStateDisplayPMReq:hsw
15836                  * System hang if this isn't done before disabling all planes!
15837                  */
15838                 I915_WRITE(CHICKEN_PAR1_1,
15839                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15840         }
15841 }
15842
15843 /* Scan out the current hw modeset state,
15844  * and sanitizes it to the current state
15845  */
15846 static void
15847 intel_modeset_setup_hw_state(struct drm_device *dev,
15848                              struct drm_modeset_acquire_ctx *ctx)
15849 {
15850         struct drm_i915_private *dev_priv = to_i915(dev);
15851         enum pipe pipe;
15852         struct intel_crtc *crtc;
15853         struct intel_encoder *encoder;
15854         int i;
15855
15856         intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15857
15858         intel_early_display_was(dev_priv);
15859         intel_modeset_readout_hw_state(dev);
15860
15861         /* HW state is read out, now we need to sanitize this mess. */
15862         get_encoder_power_domains(dev_priv);
15863
15864         intel_sanitize_plane_mapping(dev_priv);
15865
15866         for_each_intel_encoder(dev, encoder) {
15867                 intel_sanitize_encoder(encoder);
15868         }
15869
15870         for_each_pipe(dev_priv, pipe) {
15871                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15872
15873                 intel_sanitize_crtc(crtc, ctx);
15874                 intel_dump_pipe_config(crtc, crtc->config,
15875                                        "[setup_hw_state]");
15876         }
15877
15878         intel_modeset_update_connector_atomic_state(dev);
15879
15880         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15881                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15882
15883                 if (!pll->on || pll->active_mask)
15884                         continue;
15885
15886                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15887                               pll->info->name);
15888
15889                 pll->info->funcs->disable(dev_priv, pll);
15890                 pll->on = false;
15891         }
15892
15893         if (IS_G4X(dev_priv)) {
15894                 g4x_wm_get_hw_state(dev);
15895                 g4x_wm_sanitize(dev_priv);
15896         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15897                 vlv_wm_get_hw_state(dev);
15898                 vlv_wm_sanitize(dev_priv);
15899         } else if (INTEL_GEN(dev_priv) >= 9) {
15900                 skl_wm_get_hw_state(dev);
15901         } else if (HAS_PCH_SPLIT(dev_priv)) {
15902                 ilk_wm_get_hw_state(dev);
15903         }
15904
15905         for_each_intel_crtc(dev, crtc) {
15906                 u64 put_domains;
15907
15908                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15909                 if (WARN_ON(put_domains))
15910                         modeset_put_power_domains(dev_priv, put_domains);
15911         }
15912
15913         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
15914
15915         intel_fbc_init_pipe_state(dev_priv);
15916 }
15917
15918 void intel_display_resume(struct drm_device *dev)
15919 {
15920         struct drm_i915_private *dev_priv = to_i915(dev);
15921         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15922         struct drm_modeset_acquire_ctx ctx;
15923         int ret;
15924
15925         dev_priv->modeset_restore_state = NULL;
15926         if (state)
15927                 state->acquire_ctx = &ctx;
15928
15929         drm_modeset_acquire_init(&ctx, 0);
15930
15931         while (1) {
15932                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15933                 if (ret != -EDEADLK)
15934                         break;
15935
15936                 drm_modeset_backoff(&ctx);
15937         }
15938
15939         if (!ret)
15940                 ret = __intel_display_resume(dev, state, &ctx);
15941
15942         intel_enable_ipc(dev_priv);
15943         drm_modeset_drop_locks(&ctx);
15944         drm_modeset_acquire_fini(&ctx);
15945
15946         if (ret)
15947                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15948         if (state)
15949                 drm_atomic_state_put(state);
15950 }
15951
15952 int intel_connector_register(struct drm_connector *connector)
15953 {
15954         struct intel_connector *intel_connector = to_intel_connector(connector);
15955         int ret;
15956
15957         ret = intel_backlight_device_register(intel_connector);
15958         if (ret)
15959                 goto err;
15960
15961         return 0;
15962
15963 err:
15964         return ret;
15965 }
15966
15967 void intel_connector_unregister(struct drm_connector *connector)
15968 {
15969         struct intel_connector *intel_connector = to_intel_connector(connector);
15970
15971         intel_backlight_device_unregister(intel_connector);
15972         intel_panel_destroy_backlight(connector);
15973 }
15974
15975 static void intel_hpd_poll_fini(struct drm_device *dev)
15976 {
15977         struct intel_connector *connector;
15978         struct drm_connector_list_iter conn_iter;
15979
15980         /* Kill all the work that may have been queued by hpd. */
15981         drm_connector_list_iter_begin(dev, &conn_iter);
15982         for_each_intel_connector_iter(connector, &conn_iter) {
15983                 if (connector->modeset_retry_work.func)
15984                         cancel_work_sync(&connector->modeset_retry_work);
15985                 if (connector->hdcp_shim) {
15986                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15987                         cancel_work_sync(&connector->hdcp_prop_work);
15988                 }
15989         }
15990         drm_connector_list_iter_end(&conn_iter);
15991 }
15992
15993 void intel_modeset_cleanup(struct drm_device *dev)
15994 {
15995         struct drm_i915_private *dev_priv = to_i915(dev);
15996
15997         flush_workqueue(dev_priv->modeset_wq);
15998
15999         flush_work(&dev_priv->atomic_helper.free_work);
16000         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16001
16002         /*
16003          * Interrupts and polling as the first thing to avoid creating havoc.
16004          * Too much stuff here (turning of connectors, ...) would
16005          * experience fancy races otherwise.
16006          */
16007         intel_irq_uninstall(dev_priv);
16008
16009         /*
16010          * Due to the hpd irq storm handling the hotplug work can re-arm the
16011          * poll handlers. Hence disable polling after hpd handling is shut down.
16012          */
16013         intel_hpd_poll_fini(dev);
16014
16015         /* poll work can call into fbdev, hence clean that up afterwards */
16016         intel_fbdev_fini(dev_priv);
16017
16018         intel_unregister_dsm_handler();
16019
16020         intel_fbc_global_disable(dev_priv);
16021
16022         /* flush any delayed tasks or pending work */
16023         flush_scheduled_work();
16024
16025         drm_mode_config_cleanup(dev);
16026
16027         intel_cleanup_overlay(dev_priv);
16028
16029         intel_teardown_gmbus(dev_priv);
16030
16031         destroy_workqueue(dev_priv->modeset_wq);
16032 }
16033
16034 void intel_connector_attach_encoder(struct intel_connector *connector,
16035                                     struct intel_encoder *encoder)
16036 {
16037         connector->encoder = encoder;
16038         drm_connector_attach_encoder(&connector->base, &encoder->base);
16039 }
16040
16041 /*
16042  * set vga decode state - true == enable VGA decode
16043  */
16044 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16045 {
16046         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16047         u16 gmch_ctrl;
16048
16049         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16050                 DRM_ERROR("failed to read control word\n");
16051                 return -EIO;
16052         }
16053
16054         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16055                 return 0;
16056
16057         if (state)
16058                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16059         else
16060                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16061
16062         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16063                 DRM_ERROR("failed to write control word\n");
16064                 return -EIO;
16065         }
16066
16067         return 0;
16068 }
16069
16070 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16071
16072 struct intel_display_error_state {
16073
16074         u32 power_well_driver;
16075
16076         int num_transcoders;
16077
16078         struct intel_cursor_error_state {
16079                 u32 control;
16080                 u32 position;
16081                 u32 base;
16082                 u32 size;
16083         } cursor[I915_MAX_PIPES];
16084
16085         struct intel_pipe_error_state {
16086                 bool power_domain_on;
16087                 u32 source;
16088                 u32 stat;
16089         } pipe[I915_MAX_PIPES];
16090
16091         struct intel_plane_error_state {
16092                 u32 control;
16093                 u32 stride;
16094                 u32 size;
16095                 u32 pos;
16096                 u32 addr;
16097                 u32 surface;
16098                 u32 tile_offset;
16099         } plane[I915_MAX_PIPES];
16100
16101         struct intel_transcoder_error_state {
16102                 bool power_domain_on;
16103                 enum transcoder cpu_transcoder;
16104
16105                 u32 conf;
16106
16107                 u32 htotal;
16108                 u32 hblank;
16109                 u32 hsync;
16110                 u32 vtotal;
16111                 u32 vblank;
16112                 u32 vsync;
16113         } transcoder[4];
16114 };
16115
16116 struct intel_display_error_state *
16117 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16118 {
16119         struct intel_display_error_state *error;
16120         int transcoders[] = {
16121                 TRANSCODER_A,
16122                 TRANSCODER_B,
16123                 TRANSCODER_C,
16124                 TRANSCODER_EDP,
16125         };
16126         int i;
16127
16128         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16129                 return NULL;
16130
16131         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16132         if (error == NULL)
16133                 return NULL;
16134
16135         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16136                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16137
16138         for_each_pipe(dev_priv, i) {
16139                 error->pipe[i].power_domain_on =
16140                         __intel_display_power_is_enabled(dev_priv,
16141                                                          POWER_DOMAIN_PIPE(i));
16142                 if (!error->pipe[i].power_domain_on)
16143                         continue;
16144
16145                 error->cursor[i].control = I915_READ(CURCNTR(i));
16146                 error->cursor[i].position = I915_READ(CURPOS(i));
16147                 error->cursor[i].base = I915_READ(CURBASE(i));
16148
16149                 error->plane[i].control = I915_READ(DSPCNTR(i));
16150                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16151                 if (INTEL_GEN(dev_priv) <= 3) {
16152                         error->plane[i].size = I915_READ(DSPSIZE(i));
16153                         error->plane[i].pos = I915_READ(DSPPOS(i));
16154                 }
16155                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16156                         error->plane[i].addr = I915_READ(DSPADDR(i));
16157                 if (INTEL_GEN(dev_priv) >= 4) {
16158                         error->plane[i].surface = I915_READ(DSPSURF(i));
16159                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16160                 }
16161
16162                 error->pipe[i].source = I915_READ(PIPESRC(i));
16163
16164                 if (HAS_GMCH_DISPLAY(dev_priv))
16165                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16166         }
16167
16168         /* Note: this does not include DSI transcoders. */
16169         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16170         if (HAS_DDI(dev_priv))
16171                 error->num_transcoders++; /* Account for eDP. */
16172
16173         for (i = 0; i < error->num_transcoders; i++) {
16174                 enum transcoder cpu_transcoder = transcoders[i];
16175
16176                 error->transcoder[i].power_domain_on =
16177                         __intel_display_power_is_enabled(dev_priv,
16178                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16179                 if (!error->transcoder[i].power_domain_on)
16180                         continue;
16181
16182                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16183
16184                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16185                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16186                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16187                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16188                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16189                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16190                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16191         }
16192
16193         return error;
16194 }
16195
16196 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16197
16198 void
16199 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16200                                 struct intel_display_error_state *error)
16201 {
16202         struct drm_i915_private *dev_priv = m->i915;
16203         int i;
16204
16205         if (!error)
16206                 return;
16207
16208         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16209         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16210                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16211                            error->power_well_driver);
16212         for_each_pipe(dev_priv, i) {
16213                 err_printf(m, "Pipe [%d]:\n", i);
16214                 err_printf(m, "  Power: %s\n",
16215                            onoff(error->pipe[i].power_domain_on));
16216                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16217                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16218
16219                 err_printf(m, "Plane [%d]:\n", i);
16220                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16221                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16222                 if (INTEL_GEN(dev_priv) <= 3) {
16223                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16224                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16225                 }
16226                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16227                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16228                 if (INTEL_GEN(dev_priv) >= 4) {
16229                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16230                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16231                 }
16232
16233                 err_printf(m, "Cursor [%d]:\n", i);
16234                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16235                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16236                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16237         }
16238
16239         for (i = 0; i < error->num_transcoders; i++) {
16240                 err_printf(m, "CPU transcoder: %s\n",
16241                            transcoder_name(error->transcoder[i].cpu_transcoder));
16242                 err_printf(m, "  Power: %s\n",
16243                            onoff(error->transcoder[i].power_domain_on));
16244                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16245                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16246                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16247                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16248                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16249                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16250                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16251         }
16252 }
16253
16254 #endif
This page took 1.019083 seconds and 4 git commands to generate.