44fcff0343f2e42b67ea2aa4c7a2a608cb8ab967
[cascardo/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 <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include <drm/drm_atomic.h>
41 #include <drm/drm_atomic_helper.h>
42 #include <drm/drm_dp_helper.h>
43 #include <drm/drm_crtc_helper.h>
44 #include <drm/drm_plane_helper.h>
45 #include <drm/drm_rect.h>
46 #include <linux/dma_remapping.h>
47 #include <linux/reservation.h>
48 #include <linux/dma-buf.h>
49
50 /* Primary plane formats for gen <= 3 */
51 static const uint32_t i8xx_primary_formats[] = {
52         DRM_FORMAT_C8,
53         DRM_FORMAT_RGB565,
54         DRM_FORMAT_XRGB1555,
55         DRM_FORMAT_XRGB8888,
56 };
57
58 /* Primary plane formats for gen >= 4 */
59 static const uint32_t i965_primary_formats[] = {
60         DRM_FORMAT_C8,
61         DRM_FORMAT_RGB565,
62         DRM_FORMAT_XRGB8888,
63         DRM_FORMAT_XBGR8888,
64         DRM_FORMAT_XRGB2101010,
65         DRM_FORMAT_XBGR2101010,
66 };
67
68 static const uint32_t skl_primary_formats[] = {
69         DRM_FORMAT_C8,
70         DRM_FORMAT_RGB565,
71         DRM_FORMAT_XRGB8888,
72         DRM_FORMAT_XBGR8888,
73         DRM_FORMAT_ARGB8888,
74         DRM_FORMAT_ABGR8888,
75         DRM_FORMAT_XRGB2101010,
76         DRM_FORMAT_XBGR2101010,
77         DRM_FORMAT_YUYV,
78         DRM_FORMAT_YVYU,
79         DRM_FORMAT_UYVY,
80         DRM_FORMAT_VYUY,
81 };
82
83 /* Cursor formats */
84 static const uint32_t intel_cursor_formats[] = {
85         DRM_FORMAT_ARGB8888,
86 };
87
88 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
89                                 struct intel_crtc_state *pipe_config);
90 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
91                                    struct intel_crtc_state *pipe_config);
92
93 static int intel_framebuffer_init(struct drm_device *dev,
94                                   struct intel_framebuffer *ifb,
95                                   struct drm_mode_fb_cmd2 *mode_cmd,
96                                   struct drm_i915_gem_object *obj);
97 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
98 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
99 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
100                                          struct intel_link_m_n *m_n,
101                                          struct intel_link_m_n *m2_n2);
102 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
103 static void haswell_set_pipeconf(struct drm_crtc *crtc);
104 static void intel_set_pipe_csc(struct drm_crtc *crtc);
105 static void vlv_prepare_pll(struct intel_crtc *crtc,
106                             const struct intel_crtc_state *pipe_config);
107 static void chv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
110 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
111 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
112         struct intel_crtc_state *crtc_state);
113 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
114                            int num_connectors);
115 static void skylake_pfit_enable(struct intel_crtc *crtc);
116 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
117 static void ironlake_pfit_enable(struct intel_crtc *crtc);
118 static void intel_modeset_setup_hw_state(struct drm_device *dev);
119 static void intel_pre_disable_primary(struct drm_crtc *crtc);
120
121 typedef struct {
122         int     min, max;
123 } intel_range_t;
124
125 typedef struct {
126         int     dot_limit;
127         int     p2_slow, p2_fast;
128 } intel_p2_t;
129
130 typedef struct intel_limit intel_limit_t;
131 struct intel_limit {
132         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
133         intel_p2_t          p2;
134 };
135
136 /* returns HPLL frequency in kHz */
137 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
138 {
139         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
140
141         /* Obtain SKU information */
142         mutex_lock(&dev_priv->sb_lock);
143         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
144                 CCK_FUSE_HPLL_FREQ_MASK;
145         mutex_unlock(&dev_priv->sb_lock);
146
147         return vco_freq[hpll_freq] * 1000;
148 }
149
150 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
151                                   const char *name, u32 reg)
152 {
153         u32 val;
154         int divider;
155
156         if (dev_priv->hpll_freq == 0)
157                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
158
159         mutex_lock(&dev_priv->sb_lock);
160         val = vlv_cck_read(dev_priv, reg);
161         mutex_unlock(&dev_priv->sb_lock);
162
163         divider = val & CCK_FREQUENCY_VALUES;
164
165         WARN((val & CCK_FREQUENCY_STATUS) !=
166              (divider << CCK_FREQUENCY_STATUS_SHIFT),
167              "%s change in progress\n", name);
168
169         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
170 }
171
172 int
173 intel_pch_rawclk(struct drm_device *dev)
174 {
175         struct drm_i915_private *dev_priv = dev->dev_private;
176
177         WARN_ON(!HAS_PCH_SPLIT(dev));
178
179         return I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK;
180 }
181
182 /* hrawclock is 1/4 the FSB frequency */
183 int intel_hrawclk(struct drm_device *dev)
184 {
185         struct drm_i915_private *dev_priv = dev->dev_private;
186         uint32_t clkcfg;
187
188         /* There is no CLKCFG reg in Valleyview. VLV hrawclk is 200 MHz */
189         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
190                 return 200;
191
192         clkcfg = I915_READ(CLKCFG);
193         switch (clkcfg & CLKCFG_FSB_MASK) {
194         case CLKCFG_FSB_400:
195                 return 100;
196         case CLKCFG_FSB_533:
197                 return 133;
198         case CLKCFG_FSB_667:
199                 return 166;
200         case CLKCFG_FSB_800:
201                 return 200;
202         case CLKCFG_FSB_1067:
203                 return 266;
204         case CLKCFG_FSB_1333:
205                 return 333;
206         /* these two are just a guess; one of them might be right */
207         case CLKCFG_FSB_1600:
208         case CLKCFG_FSB_1600_ALT:
209                 return 400;
210         default:
211                 return 133;
212         }
213 }
214
215 static void intel_update_czclk(struct drm_i915_private *dev_priv)
216 {
217         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
218                 return;
219
220         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
221                                                       CCK_CZ_CLOCK_CONTROL);
222
223         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
224 }
225
226 static inline u32 /* units of 100MHz */
227 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
228                     const struct intel_crtc_state *pipe_config)
229 {
230         if (HAS_DDI(dev_priv))
231                 return pipe_config->port_clock; /* SPLL */
232         else if (IS_GEN5(dev_priv))
233                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
234         else
235                 return 270000;
236 }
237
238 static const intel_limit_t intel_limits_i8xx_dac = {
239         .dot = { .min = 25000, .max = 350000 },
240         .vco = { .min = 908000, .max = 1512000 },
241         .n = { .min = 2, .max = 16 },
242         .m = { .min = 96, .max = 140 },
243         .m1 = { .min = 18, .max = 26 },
244         .m2 = { .min = 6, .max = 16 },
245         .p = { .min = 4, .max = 128 },
246         .p1 = { .min = 2, .max = 33 },
247         .p2 = { .dot_limit = 165000,
248                 .p2_slow = 4, .p2_fast = 2 },
249 };
250
251 static const intel_limit_t intel_limits_i8xx_dvo = {
252         .dot = { .min = 25000, .max = 350000 },
253         .vco = { .min = 908000, .max = 1512000 },
254         .n = { .min = 2, .max = 16 },
255         .m = { .min = 96, .max = 140 },
256         .m1 = { .min = 18, .max = 26 },
257         .m2 = { .min = 6, .max = 16 },
258         .p = { .min = 4, .max = 128 },
259         .p1 = { .min = 2, .max = 33 },
260         .p2 = { .dot_limit = 165000,
261                 .p2_slow = 4, .p2_fast = 4 },
262 };
263
264 static const intel_limit_t intel_limits_i8xx_lvds = {
265         .dot = { .min = 25000, .max = 350000 },
266         .vco = { .min = 908000, .max = 1512000 },
267         .n = { .min = 2, .max = 16 },
268         .m = { .min = 96, .max = 140 },
269         .m1 = { .min = 18, .max = 26 },
270         .m2 = { .min = 6, .max = 16 },
271         .p = { .min = 4, .max = 128 },
272         .p1 = { .min = 1, .max = 6 },
273         .p2 = { .dot_limit = 165000,
274                 .p2_slow = 14, .p2_fast = 7 },
275 };
276
277 static const intel_limit_t intel_limits_i9xx_sdvo = {
278         .dot = { .min = 20000, .max = 400000 },
279         .vco = { .min = 1400000, .max = 2800000 },
280         .n = { .min = 1, .max = 6 },
281         .m = { .min = 70, .max = 120 },
282         .m1 = { .min = 8, .max = 18 },
283         .m2 = { .min = 3, .max = 7 },
284         .p = { .min = 5, .max = 80 },
285         .p1 = { .min = 1, .max = 8 },
286         .p2 = { .dot_limit = 200000,
287                 .p2_slow = 10, .p2_fast = 5 },
288 };
289
290 static const intel_limit_t intel_limits_i9xx_lvds = {
291         .dot = { .min = 20000, .max = 400000 },
292         .vco = { .min = 1400000, .max = 2800000 },
293         .n = { .min = 1, .max = 6 },
294         .m = { .min = 70, .max = 120 },
295         .m1 = { .min = 8, .max = 18 },
296         .m2 = { .min = 3, .max = 7 },
297         .p = { .min = 7, .max = 98 },
298         .p1 = { .min = 1, .max = 8 },
299         .p2 = { .dot_limit = 112000,
300                 .p2_slow = 14, .p2_fast = 7 },
301 };
302
303
304 static const intel_limit_t intel_limits_g4x_sdvo = {
305         .dot = { .min = 25000, .max = 270000 },
306         .vco = { .min = 1750000, .max = 3500000},
307         .n = { .min = 1, .max = 4 },
308         .m = { .min = 104, .max = 138 },
309         .m1 = { .min = 17, .max = 23 },
310         .m2 = { .min = 5, .max = 11 },
311         .p = { .min = 10, .max = 30 },
312         .p1 = { .min = 1, .max = 3},
313         .p2 = { .dot_limit = 270000,
314                 .p2_slow = 10,
315                 .p2_fast = 10
316         },
317 };
318
319 static const intel_limit_t intel_limits_g4x_hdmi = {
320         .dot = { .min = 22000, .max = 400000 },
321         .vco = { .min = 1750000, .max = 3500000},
322         .n = { .min = 1, .max = 4 },
323         .m = { .min = 104, .max = 138 },
324         .m1 = { .min = 16, .max = 23 },
325         .m2 = { .min = 5, .max = 11 },
326         .p = { .min = 5, .max = 80 },
327         .p1 = { .min = 1, .max = 8},
328         .p2 = { .dot_limit = 165000,
329                 .p2_slow = 10, .p2_fast = 5 },
330 };
331
332 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
333         .dot = { .min = 20000, .max = 115000 },
334         .vco = { .min = 1750000, .max = 3500000 },
335         .n = { .min = 1, .max = 3 },
336         .m = { .min = 104, .max = 138 },
337         .m1 = { .min = 17, .max = 23 },
338         .m2 = { .min = 5, .max = 11 },
339         .p = { .min = 28, .max = 112 },
340         .p1 = { .min = 2, .max = 8 },
341         .p2 = { .dot_limit = 0,
342                 .p2_slow = 14, .p2_fast = 14
343         },
344 };
345
346 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
347         .dot = { .min = 80000, .max = 224000 },
348         .vco = { .min = 1750000, .max = 3500000 },
349         .n = { .min = 1, .max = 3 },
350         .m = { .min = 104, .max = 138 },
351         .m1 = { .min = 17, .max = 23 },
352         .m2 = { .min = 5, .max = 11 },
353         .p = { .min = 14, .max = 42 },
354         .p1 = { .min = 2, .max = 6 },
355         .p2 = { .dot_limit = 0,
356                 .p2_slow = 7, .p2_fast = 7
357         },
358 };
359
360 static const intel_limit_t intel_limits_pineview_sdvo = {
361         .dot = { .min = 20000, .max = 400000},
362         .vco = { .min = 1700000, .max = 3500000 },
363         /* Pineview's Ncounter is a ring counter */
364         .n = { .min = 3, .max = 6 },
365         .m = { .min = 2, .max = 256 },
366         /* Pineview only has one combined m divider, which we treat as m2. */
367         .m1 = { .min = 0, .max = 0 },
368         .m2 = { .min = 0, .max = 254 },
369         .p = { .min = 5, .max = 80 },
370         .p1 = { .min = 1, .max = 8 },
371         .p2 = { .dot_limit = 200000,
372                 .p2_slow = 10, .p2_fast = 5 },
373 };
374
375 static const intel_limit_t intel_limits_pineview_lvds = {
376         .dot = { .min = 20000, .max = 400000 },
377         .vco = { .min = 1700000, .max = 3500000 },
378         .n = { .min = 3, .max = 6 },
379         .m = { .min = 2, .max = 256 },
380         .m1 = { .min = 0, .max = 0 },
381         .m2 = { .min = 0, .max = 254 },
382         .p = { .min = 7, .max = 112 },
383         .p1 = { .min = 1, .max = 8 },
384         .p2 = { .dot_limit = 112000,
385                 .p2_slow = 14, .p2_fast = 14 },
386 };
387
388 /* Ironlake / Sandybridge
389  *
390  * We calculate clock using (register_value + 2) for N/M1/M2, so here
391  * the range value for them is (actual_value - 2).
392  */
393 static const intel_limit_t intel_limits_ironlake_dac = {
394         .dot = { .min = 25000, .max = 350000 },
395         .vco = { .min = 1760000, .max = 3510000 },
396         .n = { .min = 1, .max = 5 },
397         .m = { .min = 79, .max = 127 },
398         .m1 = { .min = 12, .max = 22 },
399         .m2 = { .min = 5, .max = 9 },
400         .p = { .min = 5, .max = 80 },
401         .p1 = { .min = 1, .max = 8 },
402         .p2 = { .dot_limit = 225000,
403                 .p2_slow = 10, .p2_fast = 5 },
404 };
405
406 static const intel_limit_t intel_limits_ironlake_single_lvds = {
407         .dot = { .min = 25000, .max = 350000 },
408         .vco = { .min = 1760000, .max = 3510000 },
409         .n = { .min = 1, .max = 3 },
410         .m = { .min = 79, .max = 118 },
411         .m1 = { .min = 12, .max = 22 },
412         .m2 = { .min = 5, .max = 9 },
413         .p = { .min = 28, .max = 112 },
414         .p1 = { .min = 2, .max = 8 },
415         .p2 = { .dot_limit = 225000,
416                 .p2_slow = 14, .p2_fast = 14 },
417 };
418
419 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
420         .dot = { .min = 25000, .max = 350000 },
421         .vco = { .min = 1760000, .max = 3510000 },
422         .n = { .min = 1, .max = 3 },
423         .m = { .min = 79, .max = 127 },
424         .m1 = { .min = 12, .max = 22 },
425         .m2 = { .min = 5, .max = 9 },
426         .p = { .min = 14, .max = 56 },
427         .p1 = { .min = 2, .max = 8 },
428         .p2 = { .dot_limit = 225000,
429                 .p2_slow = 7, .p2_fast = 7 },
430 };
431
432 /* LVDS 100mhz refclk limits. */
433 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
434         .dot = { .min = 25000, .max = 350000 },
435         .vco = { .min = 1760000, .max = 3510000 },
436         .n = { .min = 1, .max = 2 },
437         .m = { .min = 79, .max = 126 },
438         .m1 = { .min = 12, .max = 22 },
439         .m2 = { .min = 5, .max = 9 },
440         .p = { .min = 28, .max = 112 },
441         .p1 = { .min = 2, .max = 8 },
442         .p2 = { .dot_limit = 225000,
443                 .p2_slow = 14, .p2_fast = 14 },
444 };
445
446 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
447         .dot = { .min = 25000, .max = 350000 },
448         .vco = { .min = 1760000, .max = 3510000 },
449         .n = { .min = 1, .max = 3 },
450         .m = { .min = 79, .max = 126 },
451         .m1 = { .min = 12, .max = 22 },
452         .m2 = { .min = 5, .max = 9 },
453         .p = { .min = 14, .max = 42 },
454         .p1 = { .min = 2, .max = 6 },
455         .p2 = { .dot_limit = 225000,
456                 .p2_slow = 7, .p2_fast = 7 },
457 };
458
459 static const intel_limit_t intel_limits_vlv = {
460          /*
461           * These are the data rate limits (measured in fast clocks)
462           * since those are the strictest limits we have. The fast
463           * clock and actual rate limits are more relaxed, so checking
464           * them would make no difference.
465           */
466         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
467         .vco = { .min = 4000000, .max = 6000000 },
468         .n = { .min = 1, .max = 7 },
469         .m1 = { .min = 2, .max = 3 },
470         .m2 = { .min = 11, .max = 156 },
471         .p1 = { .min = 2, .max = 3 },
472         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
473 };
474
475 static const intel_limit_t intel_limits_chv = {
476         /*
477          * These are the data rate limits (measured in fast clocks)
478          * since those are the strictest limits we have.  The fast
479          * clock and actual rate limits are more relaxed, so checking
480          * them would make no difference.
481          */
482         .dot = { .min = 25000 * 5, .max = 540000 * 5},
483         .vco = { .min = 4800000, .max = 6480000 },
484         .n = { .min = 1, .max = 1 },
485         .m1 = { .min = 2, .max = 2 },
486         .m2 = { .min = 24 << 22, .max = 175 << 22 },
487         .p1 = { .min = 2, .max = 4 },
488         .p2 = { .p2_slow = 1, .p2_fast = 14 },
489 };
490
491 static const intel_limit_t intel_limits_bxt = {
492         /* FIXME: find real dot limits */
493         .dot = { .min = 0, .max = INT_MAX },
494         .vco = { .min = 4800000, .max = 6700000 },
495         .n = { .min = 1, .max = 1 },
496         .m1 = { .min = 2, .max = 2 },
497         /* FIXME: find real m2 limits */
498         .m2 = { .min = 2 << 22, .max = 255 << 22 },
499         .p1 = { .min = 2, .max = 4 },
500         .p2 = { .p2_slow = 1, .p2_fast = 20 },
501 };
502
503 static bool
504 needs_modeset(struct drm_crtc_state *state)
505 {
506         return drm_atomic_crtc_needs_modeset(state);
507 }
508
509 /**
510  * Returns whether any output on the specified pipe is of the specified type
511  */
512 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
513 {
514         struct drm_device *dev = crtc->base.dev;
515         struct intel_encoder *encoder;
516
517         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
518                 if (encoder->type == type)
519                         return true;
520
521         return false;
522 }
523
524 /**
525  * Returns whether any output on the specified pipe will have the specified
526  * type after a staged modeset is complete, i.e., the same as
527  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
528  * encoder->crtc.
529  */
530 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
531                                       int type)
532 {
533         struct drm_atomic_state *state = crtc_state->base.state;
534         struct drm_connector *connector;
535         struct drm_connector_state *connector_state;
536         struct intel_encoder *encoder;
537         int i, num_connectors = 0;
538
539         for_each_connector_in_state(state, connector, connector_state, i) {
540                 if (connector_state->crtc != crtc_state->base.crtc)
541                         continue;
542
543                 num_connectors++;
544
545                 encoder = to_intel_encoder(connector_state->best_encoder);
546                 if (encoder->type == type)
547                         return true;
548         }
549
550         WARN_ON(num_connectors == 0);
551
552         return false;
553 }
554
555 static const intel_limit_t *
556 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
557 {
558         struct drm_device *dev = crtc_state->base.crtc->dev;
559         const intel_limit_t *limit;
560
561         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
562                 if (intel_is_dual_link_lvds(dev)) {
563                         if (refclk == 100000)
564                                 limit = &intel_limits_ironlake_dual_lvds_100m;
565                         else
566                                 limit = &intel_limits_ironlake_dual_lvds;
567                 } else {
568                         if (refclk == 100000)
569                                 limit = &intel_limits_ironlake_single_lvds_100m;
570                         else
571                                 limit = &intel_limits_ironlake_single_lvds;
572                 }
573         } else
574                 limit = &intel_limits_ironlake_dac;
575
576         return limit;
577 }
578
579 static const intel_limit_t *
580 intel_g4x_limit(struct intel_crtc_state *crtc_state)
581 {
582         struct drm_device *dev = crtc_state->base.crtc->dev;
583         const intel_limit_t *limit;
584
585         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
586                 if (intel_is_dual_link_lvds(dev))
587                         limit = &intel_limits_g4x_dual_channel_lvds;
588                 else
589                         limit = &intel_limits_g4x_single_channel_lvds;
590         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
591                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
592                 limit = &intel_limits_g4x_hdmi;
593         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
594                 limit = &intel_limits_g4x_sdvo;
595         } else /* The option is for other outputs */
596                 limit = &intel_limits_i9xx_sdvo;
597
598         return limit;
599 }
600
601 static const intel_limit_t *
602 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
603 {
604         struct drm_device *dev = crtc_state->base.crtc->dev;
605         const intel_limit_t *limit;
606
607         if (IS_BROXTON(dev))
608                 limit = &intel_limits_bxt;
609         else if (HAS_PCH_SPLIT(dev))
610                 limit = intel_ironlake_limit(crtc_state, refclk);
611         else if (IS_G4X(dev)) {
612                 limit = intel_g4x_limit(crtc_state);
613         } else if (IS_PINEVIEW(dev)) {
614                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
615                         limit = &intel_limits_pineview_lvds;
616                 else
617                         limit = &intel_limits_pineview_sdvo;
618         } else if (IS_CHERRYVIEW(dev)) {
619                 limit = &intel_limits_chv;
620         } else if (IS_VALLEYVIEW(dev)) {
621                 limit = &intel_limits_vlv;
622         } else if (!IS_GEN2(dev)) {
623                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
624                         limit = &intel_limits_i9xx_lvds;
625                 else
626                         limit = &intel_limits_i9xx_sdvo;
627         } else {
628                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
629                         limit = &intel_limits_i8xx_lvds;
630                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
631                         limit = &intel_limits_i8xx_dvo;
632                 else
633                         limit = &intel_limits_i8xx_dac;
634         }
635         return limit;
636 }
637
638 /*
639  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
640  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
641  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
642  * The helpers' return value is the rate of the clock that is fed to the
643  * display engine's pipe which can be the above fast dot clock rate or a
644  * divided-down version of it.
645  */
646 /* m1 is reserved as 0 in Pineview, n is a ring counter */
647 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
648 {
649         clock->m = clock->m2 + 2;
650         clock->p = clock->p1 * clock->p2;
651         if (WARN_ON(clock->n == 0 || clock->p == 0))
652                 return 0;
653         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
654         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
655
656         return clock->dot;
657 }
658
659 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
660 {
661         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
662 }
663
664 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
665 {
666         clock->m = i9xx_dpll_compute_m(clock);
667         clock->p = clock->p1 * clock->p2;
668         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
669                 return 0;
670         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
671         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
672
673         return clock->dot;
674 }
675
676 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
677 {
678         clock->m = clock->m1 * clock->m2;
679         clock->p = clock->p1 * clock->p2;
680         if (WARN_ON(clock->n == 0 || clock->p == 0))
681                 return 0;
682         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
683         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
684
685         return clock->dot / 5;
686 }
687
688 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
689 {
690         clock->m = clock->m1 * clock->m2;
691         clock->p = clock->p1 * clock->p2;
692         if (WARN_ON(clock->n == 0 || clock->p == 0))
693                 return 0;
694         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
695                         clock->n << 22);
696         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
697
698         return clock->dot / 5;
699 }
700
701 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
702 /**
703  * Returns whether the given set of divisors are valid for a given refclk with
704  * the given connectors.
705  */
706
707 static bool intel_PLL_is_valid(struct drm_device *dev,
708                                const intel_limit_t *limit,
709                                const intel_clock_t *clock)
710 {
711         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
712                 INTELPllInvalid("n out of range\n");
713         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
714                 INTELPllInvalid("p1 out of range\n");
715         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
716                 INTELPllInvalid("m2 out of range\n");
717         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
718                 INTELPllInvalid("m1 out of range\n");
719
720         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
721             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
722                 if (clock->m1 <= clock->m2)
723                         INTELPllInvalid("m1 <= m2\n");
724
725         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
726                 if (clock->p < limit->p.min || limit->p.max < clock->p)
727                         INTELPllInvalid("p out of range\n");
728                 if (clock->m < limit->m.min || limit->m.max < clock->m)
729                         INTELPllInvalid("m out of range\n");
730         }
731
732         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
733                 INTELPllInvalid("vco out of range\n");
734         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
735          * connector, etc., rather than just a single range.
736          */
737         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
738                 INTELPllInvalid("dot out of range\n");
739
740         return true;
741 }
742
743 static int
744 i9xx_select_p2_div(const intel_limit_t *limit,
745                    const struct intel_crtc_state *crtc_state,
746                    int target)
747 {
748         struct drm_device *dev = crtc_state->base.crtc->dev;
749
750         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
751                 /*
752                  * For LVDS just rely on its current settings for dual-channel.
753                  * We haven't figured out how to reliably set up different
754                  * single/dual channel state, if we even can.
755                  */
756                 if (intel_is_dual_link_lvds(dev))
757                         return limit->p2.p2_fast;
758                 else
759                         return limit->p2.p2_slow;
760         } else {
761                 if (target < limit->p2.dot_limit)
762                         return limit->p2.p2_slow;
763                 else
764                         return limit->p2.p2_fast;
765         }
766 }
767
768 static bool
769 i9xx_find_best_dpll(const intel_limit_t *limit,
770                     struct intel_crtc_state *crtc_state,
771                     int target, int refclk, intel_clock_t *match_clock,
772                     intel_clock_t *best_clock)
773 {
774         struct drm_device *dev = crtc_state->base.crtc->dev;
775         intel_clock_t clock;
776         int err = target;
777
778         memset(best_clock, 0, sizeof(*best_clock));
779
780         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
781
782         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
783              clock.m1++) {
784                 for (clock.m2 = limit->m2.min;
785                      clock.m2 <= limit->m2.max; clock.m2++) {
786                         if (clock.m2 >= clock.m1)
787                                 break;
788                         for (clock.n = limit->n.min;
789                              clock.n <= limit->n.max; clock.n++) {
790                                 for (clock.p1 = limit->p1.min;
791                                         clock.p1 <= limit->p1.max; clock.p1++) {
792                                         int this_err;
793
794                                         i9xx_calc_dpll_params(refclk, &clock);
795                                         if (!intel_PLL_is_valid(dev, limit,
796                                                                 &clock))
797                                                 continue;
798                                         if (match_clock &&
799                                             clock.p != match_clock->p)
800                                                 continue;
801
802                                         this_err = abs(clock.dot - target);
803                                         if (this_err < err) {
804                                                 *best_clock = clock;
805                                                 err = this_err;
806                                         }
807                                 }
808                         }
809                 }
810         }
811
812         return (err != target);
813 }
814
815 static bool
816 pnv_find_best_dpll(const intel_limit_t *limit,
817                    struct intel_crtc_state *crtc_state,
818                    int target, int refclk, intel_clock_t *match_clock,
819                    intel_clock_t *best_clock)
820 {
821         struct drm_device *dev = crtc_state->base.crtc->dev;
822         intel_clock_t clock;
823         int err = target;
824
825         memset(best_clock, 0, sizeof(*best_clock));
826
827         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
828
829         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
830              clock.m1++) {
831                 for (clock.m2 = limit->m2.min;
832                      clock.m2 <= limit->m2.max; clock.m2++) {
833                         for (clock.n = limit->n.min;
834                              clock.n <= limit->n.max; clock.n++) {
835                                 for (clock.p1 = limit->p1.min;
836                                         clock.p1 <= limit->p1.max; clock.p1++) {
837                                         int this_err;
838
839                                         pnv_calc_dpll_params(refclk, &clock);
840                                         if (!intel_PLL_is_valid(dev, limit,
841                                                                 &clock))
842                                                 continue;
843                                         if (match_clock &&
844                                             clock.p != match_clock->p)
845                                                 continue;
846
847                                         this_err = abs(clock.dot - target);
848                                         if (this_err < err) {
849                                                 *best_clock = clock;
850                                                 err = this_err;
851                                         }
852                                 }
853                         }
854                 }
855         }
856
857         return (err != target);
858 }
859
860 static bool
861 g4x_find_best_dpll(const intel_limit_t *limit,
862                    struct intel_crtc_state *crtc_state,
863                    int target, int refclk, intel_clock_t *match_clock,
864                    intel_clock_t *best_clock)
865 {
866         struct drm_device *dev = crtc_state->base.crtc->dev;
867         intel_clock_t clock;
868         int max_n;
869         bool found = false;
870         /* approximately equals target * 0.00585 */
871         int err_most = (target >> 8) + (target >> 9);
872
873         memset(best_clock, 0, sizeof(*best_clock));
874
875         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
876
877         max_n = limit->n.max;
878         /* based on hardware requirement, prefer smaller n to precision */
879         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
880                 /* based on hardware requirement, prefere larger m1,m2 */
881                 for (clock.m1 = limit->m1.max;
882                      clock.m1 >= limit->m1.min; clock.m1--) {
883                         for (clock.m2 = limit->m2.max;
884                              clock.m2 >= limit->m2.min; clock.m2--) {
885                                 for (clock.p1 = limit->p1.max;
886                                      clock.p1 >= limit->p1.min; clock.p1--) {
887                                         int this_err;
888
889                                         i9xx_calc_dpll_params(refclk, &clock);
890                                         if (!intel_PLL_is_valid(dev, limit,
891                                                                 &clock))
892                                                 continue;
893
894                                         this_err = abs(clock.dot - target);
895                                         if (this_err < err_most) {
896                                                 *best_clock = clock;
897                                                 err_most = this_err;
898                                                 max_n = clock.n;
899                                                 found = true;
900                                         }
901                                 }
902                         }
903                 }
904         }
905         return found;
906 }
907
908 /*
909  * Check if the calculated PLL configuration is more optimal compared to the
910  * best configuration and error found so far. Return the calculated error.
911  */
912 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
913                                const intel_clock_t *calculated_clock,
914                                const intel_clock_t *best_clock,
915                                unsigned int best_error_ppm,
916                                unsigned int *error_ppm)
917 {
918         /*
919          * For CHV ignore the error and consider only the P value.
920          * Prefer a bigger P value based on HW requirements.
921          */
922         if (IS_CHERRYVIEW(dev)) {
923                 *error_ppm = 0;
924
925                 return calculated_clock->p > best_clock->p;
926         }
927
928         if (WARN_ON_ONCE(!target_freq))
929                 return false;
930
931         *error_ppm = div_u64(1000000ULL *
932                                 abs(target_freq - calculated_clock->dot),
933                              target_freq);
934         /*
935          * Prefer a better P value over a better (smaller) error if the error
936          * is small. Ensure this preference for future configurations too by
937          * setting the error to 0.
938          */
939         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
940                 *error_ppm = 0;
941
942                 return true;
943         }
944
945         return *error_ppm + 10 < best_error_ppm;
946 }
947
948 static bool
949 vlv_find_best_dpll(const intel_limit_t *limit,
950                    struct intel_crtc_state *crtc_state,
951                    int target, int refclk, intel_clock_t *match_clock,
952                    intel_clock_t *best_clock)
953 {
954         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
955         struct drm_device *dev = crtc->base.dev;
956         intel_clock_t clock;
957         unsigned int bestppm = 1000000;
958         /* min update 19.2 MHz */
959         int max_n = min(limit->n.max, refclk / 19200);
960         bool found = false;
961
962         target *= 5; /* fast clock */
963
964         memset(best_clock, 0, sizeof(*best_clock));
965
966         /* based on hardware requirement, prefer smaller n to precision */
967         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
968                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
969                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
970                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
971                                 clock.p = clock.p1 * clock.p2;
972                                 /* based on hardware requirement, prefer bigger m1,m2 values */
973                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
974                                         unsigned int ppm;
975
976                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
977                                                                      refclk * clock.m1);
978
979                                         vlv_calc_dpll_params(refclk, &clock);
980
981                                         if (!intel_PLL_is_valid(dev, limit,
982                                                                 &clock))
983                                                 continue;
984
985                                         if (!vlv_PLL_is_optimal(dev, target,
986                                                                 &clock,
987                                                                 best_clock,
988                                                                 bestppm, &ppm))
989                                                 continue;
990
991                                         *best_clock = clock;
992                                         bestppm = ppm;
993                                         found = true;
994                                 }
995                         }
996                 }
997         }
998
999         return found;
1000 }
1001
1002 static bool
1003 chv_find_best_dpll(const intel_limit_t *limit,
1004                    struct intel_crtc_state *crtc_state,
1005                    int target, int refclk, intel_clock_t *match_clock,
1006                    intel_clock_t *best_clock)
1007 {
1008         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1009         struct drm_device *dev = crtc->base.dev;
1010         unsigned int best_error_ppm;
1011         intel_clock_t clock;
1012         uint64_t m2;
1013         int found = false;
1014
1015         memset(best_clock, 0, sizeof(*best_clock));
1016         best_error_ppm = 1000000;
1017
1018         /*
1019          * Based on hardware doc, the n always set to 1, and m1 always
1020          * set to 2.  If requires to support 200Mhz refclk, we need to
1021          * revisit this because n may not 1 anymore.
1022          */
1023         clock.n = 1, clock.m1 = 2;
1024         target *= 5;    /* fast clock */
1025
1026         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
1027                 for (clock.p2 = limit->p2.p2_fast;
1028                                 clock.p2 >= limit->p2.p2_slow;
1029                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1030                         unsigned int error_ppm;
1031
1032                         clock.p = clock.p1 * clock.p2;
1033
1034                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1035                                         clock.n) << 22, refclk * clock.m1);
1036
1037                         if (m2 > INT_MAX/clock.m1)
1038                                 continue;
1039
1040                         clock.m2 = m2;
1041
1042                         chv_calc_dpll_params(refclk, &clock);
1043
1044                         if (!intel_PLL_is_valid(dev, limit, &clock))
1045                                 continue;
1046
1047                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1048                                                 best_error_ppm, &error_ppm))
1049                                 continue;
1050
1051                         *best_clock = clock;
1052                         best_error_ppm = error_ppm;
1053                         found = true;
1054                 }
1055         }
1056
1057         return found;
1058 }
1059
1060 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1061                         intel_clock_t *best_clock)
1062 {
1063         int refclk = i9xx_get_refclk(crtc_state, 0);
1064
1065         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
1066                                   target_clock, refclk, NULL, best_clock);
1067 }
1068
1069 bool intel_crtc_active(struct drm_crtc *crtc)
1070 {
1071         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1072
1073         /* Be paranoid as we can arrive here with only partial
1074          * state retrieved from the hardware during setup.
1075          *
1076          * We can ditch the adjusted_mode.crtc_clock check as soon
1077          * as Haswell has gained clock readout/fastboot support.
1078          *
1079          * We can ditch the crtc->primary->fb check as soon as we can
1080          * properly reconstruct framebuffers.
1081          *
1082          * FIXME: The intel_crtc->active here should be switched to
1083          * crtc->state->active once we have proper CRTC states wired up
1084          * for atomic.
1085          */
1086         return intel_crtc->active && crtc->primary->state->fb &&
1087                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1088 }
1089
1090 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1091                                              enum pipe pipe)
1092 {
1093         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1094         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1095
1096         return intel_crtc->config->cpu_transcoder;
1097 }
1098
1099 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1100 {
1101         struct drm_i915_private *dev_priv = dev->dev_private;
1102         i915_reg_t reg = PIPEDSL(pipe);
1103         u32 line1, line2;
1104         u32 line_mask;
1105
1106         if (IS_GEN2(dev))
1107                 line_mask = DSL_LINEMASK_GEN2;
1108         else
1109                 line_mask = DSL_LINEMASK_GEN3;
1110
1111         line1 = I915_READ(reg) & line_mask;
1112         msleep(5);
1113         line2 = I915_READ(reg) & line_mask;
1114
1115         return line1 == line2;
1116 }
1117
1118 /*
1119  * intel_wait_for_pipe_off - wait for pipe to turn off
1120  * @crtc: crtc whose pipe to wait for
1121  *
1122  * After disabling a pipe, we can't wait for vblank in the usual way,
1123  * spinning on the vblank interrupt status bit, since we won't actually
1124  * see an interrupt when the pipe is disabled.
1125  *
1126  * On Gen4 and above:
1127  *   wait for the pipe register state bit to turn off
1128  *
1129  * Otherwise:
1130  *   wait for the display line value to settle (it usually
1131  *   ends up stopping at the start of the next frame).
1132  *
1133  */
1134 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1135 {
1136         struct drm_device *dev = crtc->base.dev;
1137         struct drm_i915_private *dev_priv = dev->dev_private;
1138         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1139         enum pipe pipe = crtc->pipe;
1140
1141         if (INTEL_INFO(dev)->gen >= 4) {
1142                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1143
1144                 /* Wait for the Pipe State to go off */
1145                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1146                              100))
1147                         WARN(1, "pipe_off wait timed out\n");
1148         } else {
1149                 /* Wait for the display line to settle */
1150                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1151                         WARN(1, "pipe_off wait timed out\n");
1152         }
1153 }
1154
1155 /* Only for pre-ILK configs */
1156 void assert_pll(struct drm_i915_private *dev_priv,
1157                 enum pipe pipe, bool state)
1158 {
1159         u32 val;
1160         bool cur_state;
1161
1162         val = I915_READ(DPLL(pipe));
1163         cur_state = !!(val & DPLL_VCO_ENABLE);
1164         I915_STATE_WARN(cur_state != state,
1165              "PLL state assertion failure (expected %s, current %s)\n",
1166                         onoff(state), onoff(cur_state));
1167 }
1168
1169 /* XXX: the dsi pll is shared between MIPI DSI ports */
1170 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1171 {
1172         u32 val;
1173         bool cur_state;
1174
1175         mutex_lock(&dev_priv->sb_lock);
1176         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1177         mutex_unlock(&dev_priv->sb_lock);
1178
1179         cur_state = val & DSI_PLL_VCO_EN;
1180         I915_STATE_WARN(cur_state != state,
1181              "DSI PLL state assertion failure (expected %s, current %s)\n",
1182                         onoff(state), onoff(cur_state));
1183 }
1184 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1185 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1186
1187 struct intel_shared_dpll *
1188 intel_crtc_to_shared_dpll(struct intel_crtc *crtc)
1189 {
1190         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
1191
1192         if (crtc->config->shared_dpll < 0)
1193                 return NULL;
1194
1195         return &dev_priv->shared_dplls[crtc->config->shared_dpll];
1196 }
1197
1198 /* For ILK+ */
1199 void assert_shared_dpll(struct drm_i915_private *dev_priv,
1200                         struct intel_shared_dpll *pll,
1201                         bool state)
1202 {
1203         bool cur_state;
1204         struct intel_dpll_hw_state hw_state;
1205
1206         if (WARN(!pll, "asserting DPLL %s with no DPLL\n", onoff(state)))
1207                 return;
1208
1209         cur_state = pll->get_hw_state(dev_priv, pll, &hw_state);
1210         I915_STATE_WARN(cur_state != state,
1211              "%s assertion failure (expected %s, current %s)\n",
1212                         pll->name, onoff(state), onoff(cur_state));
1213 }
1214
1215 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1216                           enum pipe pipe, bool state)
1217 {
1218         bool cur_state;
1219         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1220                                                                       pipe);
1221
1222         if (HAS_DDI(dev_priv->dev)) {
1223                 /* DDI does not have a specific FDI_TX register */
1224                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1225                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1226         } else {
1227                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1228                 cur_state = !!(val & FDI_TX_ENABLE);
1229         }
1230         I915_STATE_WARN(cur_state != state,
1231              "FDI TX state assertion failure (expected %s, current %s)\n",
1232                         onoff(state), onoff(cur_state));
1233 }
1234 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1235 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1236
1237 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1238                           enum pipe pipe, bool state)
1239 {
1240         u32 val;
1241         bool cur_state;
1242
1243         val = I915_READ(FDI_RX_CTL(pipe));
1244         cur_state = !!(val & FDI_RX_ENABLE);
1245         I915_STATE_WARN(cur_state != state,
1246              "FDI RX state assertion failure (expected %s, current %s)\n",
1247                         onoff(state), onoff(cur_state));
1248 }
1249 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1250 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1251
1252 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1253                                       enum pipe pipe)
1254 {
1255         u32 val;
1256
1257         /* ILK FDI PLL is always enabled */
1258         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1259                 return;
1260
1261         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1262         if (HAS_DDI(dev_priv->dev))
1263                 return;
1264
1265         val = I915_READ(FDI_TX_CTL(pipe));
1266         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1267 }
1268
1269 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1270                        enum pipe pipe, bool state)
1271 {
1272         u32 val;
1273         bool cur_state;
1274
1275         val = I915_READ(FDI_RX_CTL(pipe));
1276         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1277         I915_STATE_WARN(cur_state != state,
1278              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1279                         onoff(state), onoff(cur_state));
1280 }
1281
1282 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1283                            enum pipe pipe)
1284 {
1285         struct drm_device *dev = dev_priv->dev;
1286         i915_reg_t pp_reg;
1287         u32 val;
1288         enum pipe panel_pipe = PIPE_A;
1289         bool locked = true;
1290
1291         if (WARN_ON(HAS_DDI(dev)))
1292                 return;
1293
1294         if (HAS_PCH_SPLIT(dev)) {
1295                 u32 port_sel;
1296
1297                 pp_reg = PCH_PP_CONTROL;
1298                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1299
1300                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1301                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1302                         panel_pipe = PIPE_B;
1303                 /* XXX: else fix for eDP */
1304         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1305                 /* presumably write lock depends on pipe, not port select */
1306                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1307                 panel_pipe = pipe;
1308         } else {
1309                 pp_reg = PP_CONTROL;
1310                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1311                         panel_pipe = PIPE_B;
1312         }
1313
1314         val = I915_READ(pp_reg);
1315         if (!(val & PANEL_POWER_ON) ||
1316             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1317                 locked = false;
1318
1319         I915_STATE_WARN(panel_pipe == pipe && locked,
1320              "panel assertion failure, pipe %c regs locked\n",
1321              pipe_name(pipe));
1322 }
1323
1324 static void assert_cursor(struct drm_i915_private *dev_priv,
1325                           enum pipe pipe, bool state)
1326 {
1327         struct drm_device *dev = dev_priv->dev;
1328         bool cur_state;
1329
1330         if (IS_845G(dev) || IS_I865G(dev))
1331                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1332         else
1333                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1334
1335         I915_STATE_WARN(cur_state != state,
1336              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1337                         pipe_name(pipe), onoff(state), onoff(cur_state));
1338 }
1339 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1340 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1341
1342 void assert_pipe(struct drm_i915_private *dev_priv,
1343                  enum pipe pipe, bool state)
1344 {
1345         bool cur_state;
1346         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1347                                                                       pipe);
1348         enum intel_display_power_domain power_domain;
1349
1350         /* if we need the pipe quirk it must be always on */
1351         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1352             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1353                 state = true;
1354
1355         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1356         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1357                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1358                 cur_state = !!(val & PIPECONF_ENABLE);
1359
1360                 intel_display_power_put(dev_priv, power_domain);
1361         } else {
1362                 cur_state = false;
1363         }
1364
1365         I915_STATE_WARN(cur_state != state,
1366              "pipe %c assertion failure (expected %s, current %s)\n",
1367                         pipe_name(pipe), onoff(state), onoff(cur_state));
1368 }
1369
1370 static void assert_plane(struct drm_i915_private *dev_priv,
1371                          enum plane plane, bool state)
1372 {
1373         u32 val;
1374         bool cur_state;
1375
1376         val = I915_READ(DSPCNTR(plane));
1377         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1378         I915_STATE_WARN(cur_state != state,
1379              "plane %c assertion failure (expected %s, current %s)\n",
1380                         plane_name(plane), onoff(state), onoff(cur_state));
1381 }
1382
1383 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1384 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1385
1386 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1387                                    enum pipe pipe)
1388 {
1389         struct drm_device *dev = dev_priv->dev;
1390         int i;
1391
1392         /* Primary planes are fixed to pipes on gen4+ */
1393         if (INTEL_INFO(dev)->gen >= 4) {
1394                 u32 val = I915_READ(DSPCNTR(pipe));
1395                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1396                      "plane %c assertion failure, should be disabled but not\n",
1397                      plane_name(pipe));
1398                 return;
1399         }
1400
1401         /* Need to check both planes against the pipe */
1402         for_each_pipe(dev_priv, i) {
1403                 u32 val = I915_READ(DSPCNTR(i));
1404                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1405                         DISPPLANE_SEL_PIPE_SHIFT;
1406                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1407                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1408                      plane_name(i), pipe_name(pipe));
1409         }
1410 }
1411
1412 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1413                                     enum pipe pipe)
1414 {
1415         struct drm_device *dev = dev_priv->dev;
1416         int sprite;
1417
1418         if (INTEL_INFO(dev)->gen >= 9) {
1419                 for_each_sprite(dev_priv, pipe, sprite) {
1420                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1421                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1422                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1423                              sprite, pipe_name(pipe));
1424                 }
1425         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1426                 for_each_sprite(dev_priv, pipe, sprite) {
1427                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1428                         I915_STATE_WARN(val & SP_ENABLE,
1429                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1430                              sprite_name(pipe, sprite), pipe_name(pipe));
1431                 }
1432         } else if (INTEL_INFO(dev)->gen >= 7) {
1433                 u32 val = I915_READ(SPRCTL(pipe));
1434                 I915_STATE_WARN(val & SPRITE_ENABLE,
1435                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1436                      plane_name(pipe), pipe_name(pipe));
1437         } else if (INTEL_INFO(dev)->gen >= 5) {
1438                 u32 val = I915_READ(DVSCNTR(pipe));
1439                 I915_STATE_WARN(val & DVS_ENABLE,
1440                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1441                      plane_name(pipe), pipe_name(pipe));
1442         }
1443 }
1444
1445 static void assert_vblank_disabled(struct drm_crtc *crtc)
1446 {
1447         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1448                 drm_crtc_vblank_put(crtc);
1449 }
1450
1451 static void ibx_assert_pch_refclk_enabled(struct drm_i915_private *dev_priv)
1452 {
1453         u32 val;
1454         bool enabled;
1455
1456         I915_STATE_WARN_ON(!(HAS_PCH_IBX(dev_priv->dev) || HAS_PCH_CPT(dev_priv->dev)));
1457
1458         val = I915_READ(PCH_DREF_CONTROL);
1459         enabled = !!(val & (DREF_SSC_SOURCE_MASK | DREF_NONSPREAD_SOURCE_MASK |
1460                             DREF_SUPERSPREAD_SOURCE_MASK));
1461         I915_STATE_WARN(!enabled, "PCH refclk assertion failure, should be active but is disabled\n");
1462 }
1463
1464 static void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1465                                            enum pipe pipe)
1466 {
1467         u32 val;
1468         bool enabled;
1469
1470         val = I915_READ(PCH_TRANSCONF(pipe));
1471         enabled = !!(val & TRANS_ENABLE);
1472         I915_STATE_WARN(enabled,
1473              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1474              pipe_name(pipe));
1475 }
1476
1477 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1478                             enum pipe pipe, u32 port_sel, u32 val)
1479 {
1480         if ((val & DP_PORT_EN) == 0)
1481                 return false;
1482
1483         if (HAS_PCH_CPT(dev_priv->dev)) {
1484                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1485                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1486                         return false;
1487         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1488                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1489                         return false;
1490         } else {
1491                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1492                         return false;
1493         }
1494         return true;
1495 }
1496
1497 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1498                               enum pipe pipe, u32 val)
1499 {
1500         if ((val & SDVO_ENABLE) == 0)
1501                 return false;
1502
1503         if (HAS_PCH_CPT(dev_priv->dev)) {
1504                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1505                         return false;
1506         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1507                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1508                         return false;
1509         } else {
1510                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1511                         return false;
1512         }
1513         return true;
1514 }
1515
1516 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1517                               enum pipe pipe, u32 val)
1518 {
1519         if ((val & LVDS_PORT_EN) == 0)
1520                 return false;
1521
1522         if (HAS_PCH_CPT(dev_priv->dev)) {
1523                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1524                         return false;
1525         } else {
1526                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1527                         return false;
1528         }
1529         return true;
1530 }
1531
1532 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1533                               enum pipe pipe, u32 val)
1534 {
1535         if ((val & ADPA_DAC_ENABLE) == 0)
1536                 return false;
1537         if (HAS_PCH_CPT(dev_priv->dev)) {
1538                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1539                         return false;
1540         } else {
1541                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1542                         return false;
1543         }
1544         return true;
1545 }
1546
1547 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1548                                    enum pipe pipe, i915_reg_t reg,
1549                                    u32 port_sel)
1550 {
1551         u32 val = I915_READ(reg);
1552         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1553              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1554              i915_mmio_reg_offset(reg), pipe_name(pipe));
1555
1556         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1557              && (val & DP_PIPEB_SELECT),
1558              "IBX PCH dp port still using transcoder B\n");
1559 }
1560
1561 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1562                                      enum pipe pipe, i915_reg_t reg)
1563 {
1564         u32 val = I915_READ(reg);
1565         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1566              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1567              i915_mmio_reg_offset(reg), pipe_name(pipe));
1568
1569         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1570              && (val & SDVO_PIPE_B_SELECT),
1571              "IBX PCH hdmi port still using transcoder B\n");
1572 }
1573
1574 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1575                                       enum pipe pipe)
1576 {
1577         u32 val;
1578
1579         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1580         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1581         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1582
1583         val = I915_READ(PCH_ADPA);
1584         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1585              "PCH VGA enabled on transcoder %c, should be disabled\n",
1586              pipe_name(pipe));
1587
1588         val = I915_READ(PCH_LVDS);
1589         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1590              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1591              pipe_name(pipe));
1592
1593         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1594         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1595         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1596 }
1597
1598 static void vlv_enable_pll(struct intel_crtc *crtc,
1599                            const struct intel_crtc_state *pipe_config)
1600 {
1601         struct drm_device *dev = crtc->base.dev;
1602         struct drm_i915_private *dev_priv = dev->dev_private;
1603         i915_reg_t reg = DPLL(crtc->pipe);
1604         u32 dpll = pipe_config->dpll_hw_state.dpll;
1605
1606         assert_pipe_disabled(dev_priv, crtc->pipe);
1607
1608         /* PLL is protected by panel, make sure we can write it */
1609         if (IS_MOBILE(dev_priv->dev))
1610                 assert_panel_unlocked(dev_priv, crtc->pipe);
1611
1612         I915_WRITE(reg, dpll);
1613         POSTING_READ(reg);
1614         udelay(150);
1615
1616         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1617                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1618
1619         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1620         POSTING_READ(DPLL_MD(crtc->pipe));
1621
1622         /* We do this three times for luck */
1623         I915_WRITE(reg, dpll);
1624         POSTING_READ(reg);
1625         udelay(150); /* wait for warmup */
1626         I915_WRITE(reg, dpll);
1627         POSTING_READ(reg);
1628         udelay(150); /* wait for warmup */
1629         I915_WRITE(reg, dpll);
1630         POSTING_READ(reg);
1631         udelay(150); /* wait for warmup */
1632 }
1633
1634 static void chv_enable_pll(struct intel_crtc *crtc,
1635                            const struct intel_crtc_state *pipe_config)
1636 {
1637         struct drm_device *dev = crtc->base.dev;
1638         struct drm_i915_private *dev_priv = dev->dev_private;
1639         int pipe = crtc->pipe;
1640         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1641         u32 tmp;
1642
1643         assert_pipe_disabled(dev_priv, crtc->pipe);
1644
1645         mutex_lock(&dev_priv->sb_lock);
1646
1647         /* Enable back the 10bit clock to display controller */
1648         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1649         tmp |= DPIO_DCLKP_EN;
1650         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1651
1652         mutex_unlock(&dev_priv->sb_lock);
1653
1654         /*
1655          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1656          */
1657         udelay(1);
1658
1659         /* Enable PLL */
1660         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1661
1662         /* Check PLL is locked */
1663         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1664                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1665
1666         /* not sure when this should be written */
1667         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1668         POSTING_READ(DPLL_MD(pipe));
1669 }
1670
1671 static int intel_num_dvo_pipes(struct drm_device *dev)
1672 {
1673         struct intel_crtc *crtc;
1674         int count = 0;
1675
1676         for_each_intel_crtc(dev, crtc)
1677                 count += crtc->base.state->active &&
1678                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1679
1680         return count;
1681 }
1682
1683 static void i9xx_enable_pll(struct intel_crtc *crtc)
1684 {
1685         struct drm_device *dev = crtc->base.dev;
1686         struct drm_i915_private *dev_priv = dev->dev_private;
1687         i915_reg_t reg = DPLL(crtc->pipe);
1688         u32 dpll = crtc->config->dpll_hw_state.dpll;
1689
1690         assert_pipe_disabled(dev_priv, crtc->pipe);
1691
1692         /* No really, not for ILK+ */
1693         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1694
1695         /* PLL is protected by panel, make sure we can write it */
1696         if (IS_MOBILE(dev) && !IS_I830(dev))
1697                 assert_panel_unlocked(dev_priv, crtc->pipe);
1698
1699         /* Enable DVO 2x clock on both PLLs if necessary */
1700         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1701                 /*
1702                  * It appears to be important that we don't enable this
1703                  * for the current pipe before otherwise configuring the
1704                  * PLL. No idea how this should be handled if multiple
1705                  * DVO outputs are enabled simultaneosly.
1706                  */
1707                 dpll |= DPLL_DVO_2X_MODE;
1708                 I915_WRITE(DPLL(!crtc->pipe),
1709                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1710         }
1711
1712         /*
1713          * Apparently we need to have VGA mode enabled prior to changing
1714          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1715          * dividers, even though the register value does change.
1716          */
1717         I915_WRITE(reg, 0);
1718
1719         I915_WRITE(reg, dpll);
1720
1721         /* Wait for the clocks to stabilize. */
1722         POSTING_READ(reg);
1723         udelay(150);
1724
1725         if (INTEL_INFO(dev)->gen >= 4) {
1726                 I915_WRITE(DPLL_MD(crtc->pipe),
1727                            crtc->config->dpll_hw_state.dpll_md);
1728         } else {
1729                 /* The pixel multiplier can only be updated once the
1730                  * DPLL is enabled and the clocks are stable.
1731                  *
1732                  * So write it again.
1733                  */
1734                 I915_WRITE(reg, dpll);
1735         }
1736
1737         /* We do this three times for luck */
1738         I915_WRITE(reg, dpll);
1739         POSTING_READ(reg);
1740         udelay(150); /* wait for warmup */
1741         I915_WRITE(reg, dpll);
1742         POSTING_READ(reg);
1743         udelay(150); /* wait for warmup */
1744         I915_WRITE(reg, dpll);
1745         POSTING_READ(reg);
1746         udelay(150); /* wait for warmup */
1747 }
1748
1749 /**
1750  * i9xx_disable_pll - disable a PLL
1751  * @dev_priv: i915 private structure
1752  * @pipe: pipe PLL to disable
1753  *
1754  * Disable the PLL for @pipe, making sure the pipe is off first.
1755  *
1756  * Note!  This is for pre-ILK only.
1757  */
1758 static void i9xx_disable_pll(struct intel_crtc *crtc)
1759 {
1760         struct drm_device *dev = crtc->base.dev;
1761         struct drm_i915_private *dev_priv = dev->dev_private;
1762         enum pipe pipe = crtc->pipe;
1763
1764         /* Disable DVO 2x clock on both PLLs if necessary */
1765         if (IS_I830(dev) &&
1766             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1767             !intel_num_dvo_pipes(dev)) {
1768                 I915_WRITE(DPLL(PIPE_B),
1769                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1770                 I915_WRITE(DPLL(PIPE_A),
1771                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1772         }
1773
1774         /* Don't disable pipe or pipe PLLs if needed */
1775         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1776             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1777                 return;
1778
1779         /* Make sure the pipe isn't still relying on us */
1780         assert_pipe_disabled(dev_priv, pipe);
1781
1782         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1783         POSTING_READ(DPLL(pipe));
1784 }
1785
1786 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1787 {
1788         u32 val;
1789
1790         /* Make sure the pipe isn't still relying on us */
1791         assert_pipe_disabled(dev_priv, pipe);
1792
1793         /*
1794          * Leave integrated clock source and reference clock enabled for pipe B.
1795          * The latter is needed for VGA hotplug / manual detection.
1796          */
1797         val = DPLL_VGA_MODE_DIS;
1798         if (pipe == PIPE_B)
1799                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1800         I915_WRITE(DPLL(pipe), val);
1801         POSTING_READ(DPLL(pipe));
1802
1803 }
1804
1805 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1806 {
1807         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1808         u32 val;
1809
1810         /* Make sure the pipe isn't still relying on us */
1811         assert_pipe_disabled(dev_priv, pipe);
1812
1813         /* Set PLL en = 0 */
1814         val = DPLL_SSC_REF_CLK_CHV |
1815                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1816         if (pipe != PIPE_A)
1817                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1818         I915_WRITE(DPLL(pipe), val);
1819         POSTING_READ(DPLL(pipe));
1820
1821         mutex_lock(&dev_priv->sb_lock);
1822
1823         /* Disable 10bit clock to display controller */
1824         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1825         val &= ~DPIO_DCLKP_EN;
1826         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1827
1828         mutex_unlock(&dev_priv->sb_lock);
1829 }
1830
1831 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1832                          struct intel_digital_port *dport,
1833                          unsigned int expected_mask)
1834 {
1835         u32 port_mask;
1836         i915_reg_t dpll_reg;
1837
1838         switch (dport->port) {
1839         case PORT_B:
1840                 port_mask = DPLL_PORTB_READY_MASK;
1841                 dpll_reg = DPLL(0);
1842                 break;
1843         case PORT_C:
1844                 port_mask = DPLL_PORTC_READY_MASK;
1845                 dpll_reg = DPLL(0);
1846                 expected_mask <<= 4;
1847                 break;
1848         case PORT_D:
1849                 port_mask = DPLL_PORTD_READY_MASK;
1850                 dpll_reg = DPIO_PHY_STATUS;
1851                 break;
1852         default:
1853                 BUG();
1854         }
1855
1856         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1857                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1858                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1859 }
1860
1861 static void intel_prepare_shared_dpll(struct intel_crtc *crtc)
1862 {
1863         struct drm_device *dev = crtc->base.dev;
1864         struct drm_i915_private *dev_priv = dev->dev_private;
1865         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1866
1867         if (WARN_ON(pll == NULL))
1868                 return;
1869
1870         WARN_ON(!pll->config.crtc_mask);
1871         if (pll->active == 0) {
1872                 DRM_DEBUG_DRIVER("setting up %s\n", pll->name);
1873                 WARN_ON(pll->on);
1874                 assert_shared_dpll_disabled(dev_priv, pll);
1875
1876                 pll->mode_set(dev_priv, pll);
1877         }
1878 }
1879
1880 /**
1881  * intel_enable_shared_dpll - enable PCH PLL
1882  * @dev_priv: i915 private structure
1883  * @pipe: pipe PLL to enable
1884  *
1885  * The PCH PLL needs to be enabled before the PCH transcoder, since it
1886  * drives the transcoder clock.
1887  */
1888 static void intel_enable_shared_dpll(struct intel_crtc *crtc)
1889 {
1890         struct drm_device *dev = crtc->base.dev;
1891         struct drm_i915_private *dev_priv = dev->dev_private;
1892         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1893
1894         if (WARN_ON(pll == NULL))
1895                 return;
1896
1897         if (WARN_ON(pll->config.crtc_mask == 0))
1898                 return;
1899
1900         DRM_DEBUG_KMS("enable %s (active %d, on? %d) for crtc %d\n",
1901                       pll->name, pll->active, pll->on,
1902                       crtc->base.base.id);
1903
1904         if (pll->active++) {
1905                 WARN_ON(!pll->on);
1906                 assert_shared_dpll_enabled(dev_priv, pll);
1907                 return;
1908         }
1909         WARN_ON(pll->on);
1910
1911         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
1912
1913         DRM_DEBUG_KMS("enabling %s\n", pll->name);
1914         pll->enable(dev_priv, pll);
1915         pll->on = true;
1916 }
1917
1918 static void intel_disable_shared_dpll(struct intel_crtc *crtc)
1919 {
1920         struct drm_device *dev = crtc->base.dev;
1921         struct drm_i915_private *dev_priv = dev->dev_private;
1922         struct intel_shared_dpll *pll = intel_crtc_to_shared_dpll(crtc);
1923
1924         /* PCH only available on ILK+ */
1925         if (INTEL_INFO(dev)->gen < 5)
1926                 return;
1927
1928         if (pll == NULL)
1929                 return;
1930
1931         if (WARN_ON(!(pll->config.crtc_mask & (1 << drm_crtc_index(&crtc->base)))))
1932                 return;
1933
1934         DRM_DEBUG_KMS("disable %s (active %d, on? %d) for crtc %d\n",
1935                       pll->name, pll->active, pll->on,
1936                       crtc->base.base.id);
1937
1938         if (WARN_ON(pll->active == 0)) {
1939                 assert_shared_dpll_disabled(dev_priv, pll);
1940                 return;
1941         }
1942
1943         assert_shared_dpll_enabled(dev_priv, pll);
1944         WARN_ON(!pll->on);
1945         if (--pll->active)
1946                 return;
1947
1948         DRM_DEBUG_KMS("disabling %s\n", pll->name);
1949         pll->disable(dev_priv, pll);
1950         pll->on = false;
1951
1952         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
1953 }
1954
1955 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1956                                            enum pipe pipe)
1957 {
1958         struct drm_device *dev = dev_priv->dev;
1959         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1960         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1961         i915_reg_t reg;
1962         uint32_t val, pipeconf_val;
1963
1964         /* PCH only available on ILK+ */
1965         BUG_ON(!HAS_PCH_SPLIT(dev));
1966
1967         /* Make sure PCH DPLL is enabled */
1968         assert_shared_dpll_enabled(dev_priv,
1969                                    intel_crtc_to_shared_dpll(intel_crtc));
1970
1971         /* FDI must be feeding us bits for PCH ports */
1972         assert_fdi_tx_enabled(dev_priv, pipe);
1973         assert_fdi_rx_enabled(dev_priv, pipe);
1974
1975         if (HAS_PCH_CPT(dev)) {
1976                 /* Workaround: Set the timing override bit before enabling the
1977                  * pch transcoder. */
1978                 reg = TRANS_CHICKEN2(pipe);
1979                 val = I915_READ(reg);
1980                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1981                 I915_WRITE(reg, val);
1982         }
1983
1984         reg = PCH_TRANSCONF(pipe);
1985         val = I915_READ(reg);
1986         pipeconf_val = I915_READ(PIPECONF(pipe));
1987
1988         if (HAS_PCH_IBX(dev_priv->dev)) {
1989                 /*
1990                  * Make the BPC in transcoder be consistent with
1991                  * that in pipeconf reg. For HDMI we must use 8bpc
1992                  * here for both 8bpc and 12bpc.
1993                  */
1994                 val &= ~PIPECONF_BPC_MASK;
1995                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1996                         val |= PIPECONF_8BPC;
1997                 else
1998                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1999         }
2000
2001         val &= ~TRANS_INTERLACE_MASK;
2002         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
2003                 if (HAS_PCH_IBX(dev_priv->dev) &&
2004                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
2005                         val |= TRANS_LEGACY_INTERLACED_ILK;
2006                 else
2007                         val |= TRANS_INTERLACED;
2008         else
2009                 val |= TRANS_PROGRESSIVE;
2010
2011         I915_WRITE(reg, val | TRANS_ENABLE);
2012         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
2013                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
2014 }
2015
2016 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
2017                                       enum transcoder cpu_transcoder)
2018 {
2019         u32 val, pipeconf_val;
2020
2021         /* PCH only available on ILK+ */
2022         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
2023
2024         /* FDI must be feeding us bits for PCH ports */
2025         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
2026         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
2027
2028         /* Workaround: set timing override bit. */
2029         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
2030         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
2031         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
2032
2033         val = TRANS_ENABLE;
2034         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
2035
2036         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
2037             PIPECONF_INTERLACED_ILK)
2038                 val |= TRANS_INTERLACED;
2039         else
2040                 val |= TRANS_PROGRESSIVE;
2041
2042         I915_WRITE(LPT_TRANSCONF, val);
2043         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
2044                 DRM_ERROR("Failed to enable PCH transcoder\n");
2045 }
2046
2047 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
2048                                             enum pipe pipe)
2049 {
2050         struct drm_device *dev = dev_priv->dev;
2051         i915_reg_t reg;
2052         uint32_t val;
2053
2054         /* FDI relies on the transcoder */
2055         assert_fdi_tx_disabled(dev_priv, pipe);
2056         assert_fdi_rx_disabled(dev_priv, pipe);
2057
2058         /* Ports must be off as well */
2059         assert_pch_ports_disabled(dev_priv, pipe);
2060
2061         reg = PCH_TRANSCONF(pipe);
2062         val = I915_READ(reg);
2063         val &= ~TRANS_ENABLE;
2064         I915_WRITE(reg, val);
2065         /* wait for PCH transcoder off, transcoder state */
2066         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
2067                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
2068
2069         if (HAS_PCH_CPT(dev)) {
2070                 /* Workaround: Clear the timing override chicken bit again. */
2071                 reg = TRANS_CHICKEN2(pipe);
2072                 val = I915_READ(reg);
2073                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2074                 I915_WRITE(reg, val);
2075         }
2076 }
2077
2078 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
2079 {
2080         u32 val;
2081
2082         val = I915_READ(LPT_TRANSCONF);
2083         val &= ~TRANS_ENABLE;
2084         I915_WRITE(LPT_TRANSCONF, val);
2085         /* wait for PCH transcoder off, transcoder state */
2086         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
2087                 DRM_ERROR("Failed to disable PCH transcoder\n");
2088
2089         /* Workaround: clear timing override bit. */
2090         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
2091         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
2092         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
2093 }
2094
2095 /**
2096  * intel_enable_pipe - enable a pipe, asserting requirements
2097  * @crtc: crtc responsible for the pipe
2098  *
2099  * Enable @crtc's pipe, making sure that various hardware specific requirements
2100  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
2101  */
2102 static void intel_enable_pipe(struct intel_crtc *crtc)
2103 {
2104         struct drm_device *dev = crtc->base.dev;
2105         struct drm_i915_private *dev_priv = dev->dev_private;
2106         enum pipe pipe = crtc->pipe;
2107         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2108         enum pipe pch_transcoder;
2109         i915_reg_t reg;
2110         u32 val;
2111
2112         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
2113
2114         assert_planes_disabled(dev_priv, pipe);
2115         assert_cursor_disabled(dev_priv, pipe);
2116         assert_sprites_disabled(dev_priv, pipe);
2117
2118         if (HAS_PCH_LPT(dev_priv->dev))
2119                 pch_transcoder = TRANSCODER_A;
2120         else
2121                 pch_transcoder = pipe;
2122
2123         /*
2124          * A pipe without a PLL won't actually be able to drive bits from
2125          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2126          * need the check.
2127          */
2128         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2129                 if (crtc->config->has_dsi_encoder)
2130                         assert_dsi_pll_enabled(dev_priv);
2131                 else
2132                         assert_pll_enabled(dev_priv, pipe);
2133         else {
2134                 if (crtc->config->has_pch_encoder) {
2135                         /* if driving the PCH, we need FDI enabled */
2136                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2137                         assert_fdi_tx_pll_enabled(dev_priv,
2138                                                   (enum pipe) cpu_transcoder);
2139                 }
2140                 /* FIXME: assert CPU port conditions for SNB+ */
2141         }
2142
2143         reg = PIPECONF(cpu_transcoder);
2144         val = I915_READ(reg);
2145         if (val & PIPECONF_ENABLE) {
2146                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2147                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2148                 return;
2149         }
2150
2151         I915_WRITE(reg, val | PIPECONF_ENABLE);
2152         POSTING_READ(reg);
2153
2154         /*
2155          * Until the pipe starts DSL will read as 0, which would cause
2156          * an apparent vblank timestamp jump, which messes up also the
2157          * frame count when it's derived from the timestamps. So let's
2158          * wait for the pipe to start properly before we call
2159          * drm_crtc_vblank_on()
2160          */
2161         if (dev->max_vblank_count == 0 &&
2162             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2163                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2164 }
2165
2166 /**
2167  * intel_disable_pipe - disable a pipe, asserting requirements
2168  * @crtc: crtc whose pipes is to be disabled
2169  *
2170  * Disable the pipe of @crtc, making sure that various hardware
2171  * specific requirements are met, if applicable, e.g. plane
2172  * disabled, panel fitter off, etc.
2173  *
2174  * Will wait until the pipe has shut down before returning.
2175  */
2176 static void intel_disable_pipe(struct intel_crtc *crtc)
2177 {
2178         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2179         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2180         enum pipe pipe = crtc->pipe;
2181         i915_reg_t reg;
2182         u32 val;
2183
2184         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2185
2186         /*
2187          * Make sure planes won't keep trying to pump pixels to us,
2188          * or we might hang the display.
2189          */
2190         assert_planes_disabled(dev_priv, pipe);
2191         assert_cursor_disabled(dev_priv, pipe);
2192         assert_sprites_disabled(dev_priv, pipe);
2193
2194         reg = PIPECONF(cpu_transcoder);
2195         val = I915_READ(reg);
2196         if ((val & PIPECONF_ENABLE) == 0)
2197                 return;
2198
2199         /*
2200          * Double wide has implications for planes
2201          * so best keep it disabled when not needed.
2202          */
2203         if (crtc->config->double_wide)
2204                 val &= ~PIPECONF_DOUBLE_WIDE;
2205
2206         /* Don't disable pipe or pipe PLLs if needed */
2207         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2208             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2209                 val &= ~PIPECONF_ENABLE;
2210
2211         I915_WRITE(reg, val);
2212         if ((val & PIPECONF_ENABLE) == 0)
2213                 intel_wait_for_pipe_off(crtc);
2214 }
2215
2216 static bool need_vtd_wa(struct drm_device *dev)
2217 {
2218 #ifdef CONFIG_INTEL_IOMMU
2219         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2220                 return true;
2221 #endif
2222         return false;
2223 }
2224
2225 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2226 {
2227         return IS_GEN2(dev_priv) ? 2048 : 4096;
2228 }
2229
2230 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2231                                            uint64_t fb_modifier, unsigned int cpp)
2232 {
2233         switch (fb_modifier) {
2234         case DRM_FORMAT_MOD_NONE:
2235                 return cpp;
2236         case I915_FORMAT_MOD_X_TILED:
2237                 if (IS_GEN2(dev_priv))
2238                         return 128;
2239                 else
2240                         return 512;
2241         case I915_FORMAT_MOD_Y_TILED:
2242                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2243                         return 128;
2244                 else
2245                         return 512;
2246         case I915_FORMAT_MOD_Yf_TILED:
2247                 switch (cpp) {
2248                 case 1:
2249                         return 64;
2250                 case 2:
2251                 case 4:
2252                         return 128;
2253                 case 8:
2254                 case 16:
2255                         return 256;
2256                 default:
2257                         MISSING_CASE(cpp);
2258                         return cpp;
2259                 }
2260                 break;
2261         default:
2262                 MISSING_CASE(fb_modifier);
2263                 return cpp;
2264         }
2265 }
2266
2267 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2268                                uint64_t fb_modifier, unsigned int cpp)
2269 {
2270         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2271                 return 1;
2272         else
2273                 return intel_tile_size(dev_priv) /
2274                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2275 }
2276
2277 /* Return the tile dimensions in pixel units */
2278 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2279                             unsigned int *tile_width,
2280                             unsigned int *tile_height,
2281                             uint64_t fb_modifier,
2282                             unsigned int cpp)
2283 {
2284         unsigned int tile_width_bytes =
2285                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2286
2287         *tile_width = tile_width_bytes / cpp;
2288         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2289 }
2290
2291 unsigned int
2292 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2293                       uint32_t pixel_format, uint64_t fb_modifier)
2294 {
2295         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2296         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2297
2298         return ALIGN(height, tile_height);
2299 }
2300
2301 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2302 {
2303         unsigned int size = 0;
2304         int i;
2305
2306         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2307                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2308
2309         return size;
2310 }
2311
2312 static void
2313 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2314                         const struct drm_framebuffer *fb,
2315                         unsigned int rotation)
2316 {
2317         if (intel_rotation_90_or_270(rotation)) {
2318                 *view = i915_ggtt_view_rotated;
2319                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2320         } else {
2321                 *view = i915_ggtt_view_normal;
2322         }
2323 }
2324
2325 static void
2326 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2327                    struct drm_framebuffer *fb)
2328 {
2329         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2330         unsigned int tile_size, tile_width, tile_height, cpp;
2331
2332         tile_size = intel_tile_size(dev_priv);
2333
2334         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2335         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2336                         fb->modifier[0], cpp);
2337
2338         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2339         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2340
2341         if (info->pixel_format == DRM_FORMAT_NV12) {
2342                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2343                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2344                                 fb->modifier[1], cpp);
2345
2346                 info->uv_offset = fb->offsets[1];
2347                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2348                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2349         }
2350 }
2351
2352 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2353 {
2354         if (INTEL_INFO(dev_priv)->gen >= 9)
2355                 return 256 * 1024;
2356         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2357                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2358                 return 128 * 1024;
2359         else if (INTEL_INFO(dev_priv)->gen >= 4)
2360                 return 4 * 1024;
2361         else
2362                 return 0;
2363 }
2364
2365 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2366                                          uint64_t fb_modifier)
2367 {
2368         switch (fb_modifier) {
2369         case DRM_FORMAT_MOD_NONE:
2370                 return intel_linear_alignment(dev_priv);
2371         case I915_FORMAT_MOD_X_TILED:
2372                 if (INTEL_INFO(dev_priv)->gen >= 9)
2373                         return 256 * 1024;
2374                 return 0;
2375         case I915_FORMAT_MOD_Y_TILED:
2376         case I915_FORMAT_MOD_Yf_TILED:
2377                 return 1 * 1024 * 1024;
2378         default:
2379                 MISSING_CASE(fb_modifier);
2380                 return 0;
2381         }
2382 }
2383
2384 int
2385 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2386                            unsigned int rotation)
2387 {
2388         struct drm_device *dev = fb->dev;
2389         struct drm_i915_private *dev_priv = dev->dev_private;
2390         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2391         struct i915_ggtt_view view;
2392         u32 alignment;
2393         int ret;
2394
2395         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2396
2397         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2398
2399         intel_fill_fb_ggtt_view(&view, fb, rotation);
2400
2401         /* Note that the w/a also requires 64 PTE of padding following the
2402          * bo. We currently fill all unused PTE with the shadow page and so
2403          * we should always have valid PTE following the scanout preventing
2404          * the VT-d warning.
2405          */
2406         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2407                 alignment = 256 * 1024;
2408
2409         /*
2410          * Global gtt pte registers are special registers which actually forward
2411          * writes to a chunk of system memory. Which means that there is no risk
2412          * that the register values disappear as soon as we call
2413          * intel_runtime_pm_put(), so it is correct to wrap only the
2414          * pin/unpin/fence and not more.
2415          */
2416         intel_runtime_pm_get(dev_priv);
2417
2418         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2419                                                    &view);
2420         if (ret)
2421                 goto err_pm;
2422
2423         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2424          * fence, whereas 965+ only requires a fence if using
2425          * framebuffer compression.  For simplicity, we always install
2426          * a fence as the cost is not that onerous.
2427          */
2428         if (view.type == I915_GGTT_VIEW_NORMAL) {
2429                 ret = i915_gem_object_get_fence(obj);
2430                 if (ret == -EDEADLK) {
2431                         /*
2432                          * -EDEADLK means there are no free fences
2433                          * no pending flips.
2434                          *
2435                          * This is propagated to atomic, but it uses
2436                          * -EDEADLK to force a locking recovery, so
2437                          * change the returned error to -EBUSY.
2438                          */
2439                         ret = -EBUSY;
2440                         goto err_unpin;
2441                 } else if (ret)
2442                         goto err_unpin;
2443
2444                 i915_gem_object_pin_fence(obj);
2445         }
2446
2447         intel_runtime_pm_put(dev_priv);
2448         return 0;
2449
2450 err_unpin:
2451         i915_gem_object_unpin_from_display_plane(obj, &view);
2452 err_pm:
2453         intel_runtime_pm_put(dev_priv);
2454         return ret;
2455 }
2456
2457 static void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2458 {
2459         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2460         struct i915_ggtt_view view;
2461
2462         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2463
2464         intel_fill_fb_ggtt_view(&view, fb, rotation);
2465
2466         if (view.type == I915_GGTT_VIEW_NORMAL)
2467                 i915_gem_object_unpin_fence(obj);
2468
2469         i915_gem_object_unpin_from_display_plane(obj, &view);
2470 }
2471
2472 /*
2473  * Adjust the tile offset by moving the difference into
2474  * the x/y offsets.
2475  *
2476  * Input tile dimensions and pitch must already be
2477  * rotated to match x and y, and in pixel units.
2478  */
2479 static u32 intel_adjust_tile_offset(int *x, int *y,
2480                                     unsigned int tile_width,
2481                                     unsigned int tile_height,
2482                                     unsigned int tile_size,
2483                                     unsigned int pitch_tiles,
2484                                     u32 old_offset,
2485                                     u32 new_offset)
2486 {
2487         unsigned int tiles;
2488
2489         WARN_ON(old_offset & (tile_size - 1));
2490         WARN_ON(new_offset & (tile_size - 1));
2491         WARN_ON(new_offset > old_offset);
2492
2493         tiles = (old_offset - new_offset) / tile_size;
2494
2495         *y += tiles / pitch_tiles * tile_height;
2496         *x += tiles % pitch_tiles * tile_width;
2497
2498         return new_offset;
2499 }
2500
2501 /*
2502  * Computes the linear offset to the base tile and adjusts
2503  * x, y. bytes per pixel is assumed to be a power-of-two.
2504  *
2505  * In the 90/270 rotated case, x and y are assumed
2506  * to be already rotated to match the rotated GTT view, and
2507  * pitch is the tile_height aligned framebuffer height.
2508  */
2509 u32 intel_compute_tile_offset(int *x, int *y,
2510                               const struct drm_framebuffer *fb, int plane,
2511                               unsigned int pitch,
2512                               unsigned int rotation)
2513 {
2514         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2515         uint64_t fb_modifier = fb->modifier[plane];
2516         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2517         u32 offset, offset_aligned, alignment;
2518
2519         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2520         if (alignment)
2521                 alignment--;
2522
2523         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2524                 unsigned int tile_size, tile_width, tile_height;
2525                 unsigned int tile_rows, tiles, pitch_tiles;
2526
2527                 tile_size = intel_tile_size(dev_priv);
2528                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2529                                 fb_modifier, cpp);
2530
2531                 if (intel_rotation_90_or_270(rotation)) {
2532                         pitch_tiles = pitch / tile_height;
2533                         swap(tile_width, tile_height);
2534                 } else {
2535                         pitch_tiles = pitch / (tile_width * cpp);
2536                 }
2537
2538                 tile_rows = *y / tile_height;
2539                 *y %= tile_height;
2540
2541                 tiles = *x / tile_width;
2542                 *x %= tile_width;
2543
2544                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2545                 offset_aligned = offset & ~alignment;
2546
2547                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2548                                          tile_size, pitch_tiles,
2549                                          offset, offset_aligned);
2550         } else {
2551                 offset = *y * pitch + *x * cpp;
2552                 offset_aligned = offset & ~alignment;
2553
2554                 *y = (offset & alignment) / pitch;
2555                 *x = ((offset & alignment) - *y * pitch) / cpp;
2556         }
2557
2558         return offset_aligned;
2559 }
2560
2561 static int i9xx_format_to_fourcc(int format)
2562 {
2563         switch (format) {
2564         case DISPPLANE_8BPP:
2565                 return DRM_FORMAT_C8;
2566         case DISPPLANE_BGRX555:
2567                 return DRM_FORMAT_XRGB1555;
2568         case DISPPLANE_BGRX565:
2569                 return DRM_FORMAT_RGB565;
2570         default:
2571         case DISPPLANE_BGRX888:
2572                 return DRM_FORMAT_XRGB8888;
2573         case DISPPLANE_RGBX888:
2574                 return DRM_FORMAT_XBGR8888;
2575         case DISPPLANE_BGRX101010:
2576                 return DRM_FORMAT_XRGB2101010;
2577         case DISPPLANE_RGBX101010:
2578                 return DRM_FORMAT_XBGR2101010;
2579         }
2580 }
2581
2582 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2583 {
2584         switch (format) {
2585         case PLANE_CTL_FORMAT_RGB_565:
2586                 return DRM_FORMAT_RGB565;
2587         default:
2588         case PLANE_CTL_FORMAT_XRGB_8888:
2589                 if (rgb_order) {
2590                         if (alpha)
2591                                 return DRM_FORMAT_ABGR8888;
2592                         else
2593                                 return DRM_FORMAT_XBGR8888;
2594                 } else {
2595                         if (alpha)
2596                                 return DRM_FORMAT_ARGB8888;
2597                         else
2598                                 return DRM_FORMAT_XRGB8888;
2599                 }
2600         case PLANE_CTL_FORMAT_XRGB_2101010:
2601                 if (rgb_order)
2602                         return DRM_FORMAT_XBGR2101010;
2603                 else
2604                         return DRM_FORMAT_XRGB2101010;
2605         }
2606 }
2607
2608 static bool
2609 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2610                               struct intel_initial_plane_config *plane_config)
2611 {
2612         struct drm_device *dev = crtc->base.dev;
2613         struct drm_i915_private *dev_priv = to_i915(dev);
2614         struct drm_i915_gem_object *obj = NULL;
2615         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2616         struct drm_framebuffer *fb = &plane_config->fb->base;
2617         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2618         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2619                                     PAGE_SIZE);
2620
2621         size_aligned -= base_aligned;
2622
2623         if (plane_config->size == 0)
2624                 return false;
2625
2626         /* If the FB is too big, just don't use it since fbdev is not very
2627          * important and we should probably use that space with FBC or other
2628          * features. */
2629         if (size_aligned * 2 > dev_priv->gtt.stolen_usable_size)
2630                 return false;
2631
2632         mutex_lock(&dev->struct_mutex);
2633
2634         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2635                                                              base_aligned,
2636                                                              base_aligned,
2637                                                              size_aligned);
2638         if (!obj) {
2639                 mutex_unlock(&dev->struct_mutex);
2640                 return false;
2641         }
2642
2643         obj->tiling_mode = plane_config->tiling;
2644         if (obj->tiling_mode == I915_TILING_X)
2645                 obj->stride = fb->pitches[0];
2646
2647         mode_cmd.pixel_format = fb->pixel_format;
2648         mode_cmd.width = fb->width;
2649         mode_cmd.height = fb->height;
2650         mode_cmd.pitches[0] = fb->pitches[0];
2651         mode_cmd.modifier[0] = fb->modifier[0];
2652         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2653
2654         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2655                                    &mode_cmd, obj)) {
2656                 DRM_DEBUG_KMS("intel fb init failed\n");
2657                 goto out_unref_obj;
2658         }
2659
2660         mutex_unlock(&dev->struct_mutex);
2661
2662         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2663         return true;
2664
2665 out_unref_obj:
2666         drm_gem_object_unreference(&obj->base);
2667         mutex_unlock(&dev->struct_mutex);
2668         return false;
2669 }
2670
2671 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2672 static void
2673 update_state_fb(struct drm_plane *plane)
2674 {
2675         if (plane->fb == plane->state->fb)
2676                 return;
2677
2678         if (plane->state->fb)
2679                 drm_framebuffer_unreference(plane->state->fb);
2680         plane->state->fb = plane->fb;
2681         if (plane->state->fb)
2682                 drm_framebuffer_reference(plane->state->fb);
2683 }
2684
2685 static void
2686 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2687                              struct intel_initial_plane_config *plane_config)
2688 {
2689         struct drm_device *dev = intel_crtc->base.dev;
2690         struct drm_i915_private *dev_priv = dev->dev_private;
2691         struct drm_crtc *c;
2692         struct intel_crtc *i;
2693         struct drm_i915_gem_object *obj;
2694         struct drm_plane *primary = intel_crtc->base.primary;
2695         struct drm_plane_state *plane_state = primary->state;
2696         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2697         struct intel_plane *intel_plane = to_intel_plane(primary);
2698         struct intel_plane_state *intel_state =
2699                 to_intel_plane_state(plane_state);
2700         struct drm_framebuffer *fb;
2701
2702         if (!plane_config->fb)
2703                 return;
2704
2705         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2706                 fb = &plane_config->fb->base;
2707                 goto valid_fb;
2708         }
2709
2710         kfree(plane_config->fb);
2711
2712         /*
2713          * Failed to alloc the obj, check to see if we should share
2714          * an fb with another CRTC instead
2715          */
2716         for_each_crtc(dev, c) {
2717                 i = to_intel_crtc(c);
2718
2719                 if (c == &intel_crtc->base)
2720                         continue;
2721
2722                 if (!i->active)
2723                         continue;
2724
2725                 fb = c->primary->fb;
2726                 if (!fb)
2727                         continue;
2728
2729                 obj = intel_fb_obj(fb);
2730                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2731                         drm_framebuffer_reference(fb);
2732                         goto valid_fb;
2733                 }
2734         }
2735
2736         /*
2737          * We've failed to reconstruct the BIOS FB.  Current display state
2738          * indicates that the primary plane is visible, but has a NULL FB,
2739          * which will lead to problems later if we don't fix it up.  The
2740          * simplest solution is to just disable the primary plane now and
2741          * pretend the BIOS never had it enabled.
2742          */
2743         to_intel_plane_state(plane_state)->visible = false;
2744         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2745         intel_pre_disable_primary(&intel_crtc->base);
2746         intel_plane->disable_plane(primary, &intel_crtc->base);
2747
2748         return;
2749
2750 valid_fb:
2751         plane_state->src_x = 0;
2752         plane_state->src_y = 0;
2753         plane_state->src_w = fb->width << 16;
2754         plane_state->src_h = fb->height << 16;
2755
2756         plane_state->crtc_x = 0;
2757         plane_state->crtc_y = 0;
2758         plane_state->crtc_w = fb->width;
2759         plane_state->crtc_h = fb->height;
2760
2761         intel_state->src.x1 = plane_state->src_x;
2762         intel_state->src.y1 = plane_state->src_y;
2763         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2764         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2765         intel_state->dst.x1 = plane_state->crtc_x;
2766         intel_state->dst.y1 = plane_state->crtc_y;
2767         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2768         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2769
2770         obj = intel_fb_obj(fb);
2771         if (obj->tiling_mode != I915_TILING_NONE)
2772                 dev_priv->preserve_bios_swizzle = true;
2773
2774         drm_framebuffer_reference(fb);
2775         primary->fb = primary->state->fb = fb;
2776         primary->crtc = primary->state->crtc = &intel_crtc->base;
2777         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2778         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2779 }
2780
2781 static void i9xx_update_primary_plane(struct drm_plane *primary,
2782                                       const struct intel_crtc_state *crtc_state,
2783                                       const struct intel_plane_state *plane_state)
2784 {
2785         struct drm_device *dev = primary->dev;
2786         struct drm_i915_private *dev_priv = dev->dev_private;
2787         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2788         struct drm_framebuffer *fb = plane_state->base.fb;
2789         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2790         int plane = intel_crtc->plane;
2791         u32 linear_offset;
2792         u32 dspcntr;
2793         i915_reg_t reg = DSPCNTR(plane);
2794         unsigned int rotation = plane_state->base.rotation;
2795         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2796         int x = plane_state->src.x1 >> 16;
2797         int y = plane_state->src.y1 >> 16;
2798
2799         dspcntr = DISPPLANE_GAMMA_ENABLE;
2800
2801         dspcntr |= DISPLAY_PLANE_ENABLE;
2802
2803         if (INTEL_INFO(dev)->gen < 4) {
2804                 if (intel_crtc->pipe == PIPE_B)
2805                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2806
2807                 /* pipesrc and dspsize control the size that is scaled from,
2808                  * which should always be the user's requested size.
2809                  */
2810                 I915_WRITE(DSPSIZE(plane),
2811                            ((crtc_state->pipe_src_h - 1) << 16) |
2812                            (crtc_state->pipe_src_w - 1));
2813                 I915_WRITE(DSPPOS(plane), 0);
2814         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2815                 I915_WRITE(PRIMSIZE(plane),
2816                            ((crtc_state->pipe_src_h - 1) << 16) |
2817                            (crtc_state->pipe_src_w - 1));
2818                 I915_WRITE(PRIMPOS(plane), 0);
2819                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2820         }
2821
2822         switch (fb->pixel_format) {
2823         case DRM_FORMAT_C8:
2824                 dspcntr |= DISPPLANE_8BPP;
2825                 break;
2826         case DRM_FORMAT_XRGB1555:
2827                 dspcntr |= DISPPLANE_BGRX555;
2828                 break;
2829         case DRM_FORMAT_RGB565:
2830                 dspcntr |= DISPPLANE_BGRX565;
2831                 break;
2832         case DRM_FORMAT_XRGB8888:
2833                 dspcntr |= DISPPLANE_BGRX888;
2834                 break;
2835         case DRM_FORMAT_XBGR8888:
2836                 dspcntr |= DISPPLANE_RGBX888;
2837                 break;
2838         case DRM_FORMAT_XRGB2101010:
2839                 dspcntr |= DISPPLANE_BGRX101010;
2840                 break;
2841         case DRM_FORMAT_XBGR2101010:
2842                 dspcntr |= DISPPLANE_RGBX101010;
2843                 break;
2844         default:
2845                 BUG();
2846         }
2847
2848         if (INTEL_INFO(dev)->gen >= 4 &&
2849             obj->tiling_mode != I915_TILING_NONE)
2850                 dspcntr |= DISPPLANE_TILED;
2851
2852         if (IS_G4X(dev))
2853                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2854
2855         linear_offset = y * fb->pitches[0] + x * cpp;
2856
2857         if (INTEL_INFO(dev)->gen >= 4) {
2858                 intel_crtc->dspaddr_offset =
2859                         intel_compute_tile_offset(&x, &y, fb, 0,
2860                                                   fb->pitches[0], rotation);
2861                 linear_offset -= intel_crtc->dspaddr_offset;
2862         } else {
2863                 intel_crtc->dspaddr_offset = linear_offset;
2864         }
2865
2866         if (rotation == BIT(DRM_ROTATE_180)) {
2867                 dspcntr |= DISPPLANE_ROTATE_180;
2868
2869                 x += (crtc_state->pipe_src_w - 1);
2870                 y += (crtc_state->pipe_src_h - 1);
2871
2872                 /* Finding the last pixel of the last line of the display
2873                 data and adding to linear_offset*/
2874                 linear_offset +=
2875                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2876                         (crtc_state->pipe_src_w - 1) * cpp;
2877         }
2878
2879         intel_crtc->adjusted_x = x;
2880         intel_crtc->adjusted_y = y;
2881
2882         I915_WRITE(reg, dspcntr);
2883
2884         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2885         if (INTEL_INFO(dev)->gen >= 4) {
2886                 I915_WRITE(DSPSURF(plane),
2887                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2888                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2889                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2890         } else
2891                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2892         POSTING_READ(reg);
2893 }
2894
2895 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2896                                        struct drm_crtc *crtc)
2897 {
2898         struct drm_device *dev = crtc->dev;
2899         struct drm_i915_private *dev_priv = dev->dev_private;
2900         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2901         int plane = intel_crtc->plane;
2902
2903         I915_WRITE(DSPCNTR(plane), 0);
2904         if (INTEL_INFO(dev_priv)->gen >= 4)
2905                 I915_WRITE(DSPSURF(plane), 0);
2906         else
2907                 I915_WRITE(DSPADDR(plane), 0);
2908         POSTING_READ(DSPCNTR(plane));
2909 }
2910
2911 static void ironlake_update_primary_plane(struct drm_plane *primary,
2912                                           const struct intel_crtc_state *crtc_state,
2913                                           const struct intel_plane_state *plane_state)
2914 {
2915         struct drm_device *dev = primary->dev;
2916         struct drm_i915_private *dev_priv = dev->dev_private;
2917         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2918         struct drm_framebuffer *fb = plane_state->base.fb;
2919         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2920         int plane = intel_crtc->plane;
2921         u32 linear_offset;
2922         u32 dspcntr;
2923         i915_reg_t reg = DSPCNTR(plane);
2924         unsigned int rotation = plane_state->base.rotation;
2925         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2926         int x = plane_state->src.x1 >> 16;
2927         int y = plane_state->src.y1 >> 16;
2928
2929         dspcntr = DISPPLANE_GAMMA_ENABLE;
2930         dspcntr |= DISPLAY_PLANE_ENABLE;
2931
2932         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2933                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2934
2935         switch (fb->pixel_format) {
2936         case DRM_FORMAT_C8:
2937                 dspcntr |= DISPPLANE_8BPP;
2938                 break;
2939         case DRM_FORMAT_RGB565:
2940                 dspcntr |= DISPPLANE_BGRX565;
2941                 break;
2942         case DRM_FORMAT_XRGB8888:
2943                 dspcntr |= DISPPLANE_BGRX888;
2944                 break;
2945         case DRM_FORMAT_XBGR8888:
2946                 dspcntr |= DISPPLANE_RGBX888;
2947                 break;
2948         case DRM_FORMAT_XRGB2101010:
2949                 dspcntr |= DISPPLANE_BGRX101010;
2950                 break;
2951         case DRM_FORMAT_XBGR2101010:
2952                 dspcntr |= DISPPLANE_RGBX101010;
2953                 break;
2954         default:
2955                 BUG();
2956         }
2957
2958         if (obj->tiling_mode != I915_TILING_NONE)
2959                 dspcntr |= DISPPLANE_TILED;
2960
2961         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2962                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2963
2964         linear_offset = y * fb->pitches[0] + x * cpp;
2965         intel_crtc->dspaddr_offset =
2966                 intel_compute_tile_offset(&x, &y, fb, 0,
2967                                           fb->pitches[0], rotation);
2968         linear_offset -= intel_crtc->dspaddr_offset;
2969         if (rotation == BIT(DRM_ROTATE_180)) {
2970                 dspcntr |= DISPPLANE_ROTATE_180;
2971
2972                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2973                         x += (crtc_state->pipe_src_w - 1);
2974                         y += (crtc_state->pipe_src_h - 1);
2975
2976                         /* Finding the last pixel of the last line of the display
2977                         data and adding to linear_offset*/
2978                         linear_offset +=
2979                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2980                                 (crtc_state->pipe_src_w - 1) * cpp;
2981                 }
2982         }
2983
2984         intel_crtc->adjusted_x = x;
2985         intel_crtc->adjusted_y = y;
2986
2987         I915_WRITE(reg, dspcntr);
2988
2989         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2990         I915_WRITE(DSPSURF(plane),
2991                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2992         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2993                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2994         } else {
2995                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2996                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2997         }
2998         POSTING_READ(reg);
2999 }
3000
3001 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
3002                               uint64_t fb_modifier, uint32_t pixel_format)
3003 {
3004         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
3005                 return 64;
3006         } else {
3007                 int cpp = drm_format_plane_cpp(pixel_format, 0);
3008
3009                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
3010         }
3011 }
3012
3013 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
3014                            struct drm_i915_gem_object *obj,
3015                            unsigned int plane)
3016 {
3017         struct i915_ggtt_view view;
3018         struct i915_vma *vma;
3019         u64 offset;
3020
3021         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
3022                                 intel_plane->base.state->rotation);
3023
3024         vma = i915_gem_obj_to_ggtt_view(obj, &view);
3025         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
3026                 view.type))
3027                 return -1;
3028
3029         offset = vma->node.start;
3030
3031         if (plane == 1) {
3032                 offset += vma->ggtt_view.params.rotated.uv_start_page *
3033                           PAGE_SIZE;
3034         }
3035
3036         WARN_ON(upper_32_bits(offset));
3037
3038         return lower_32_bits(offset);
3039 }
3040
3041 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3042 {
3043         struct drm_device *dev = intel_crtc->base.dev;
3044         struct drm_i915_private *dev_priv = dev->dev_private;
3045
3046         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3047         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3048         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3049 }
3050
3051 /*
3052  * This function detaches (aka. unbinds) unused scalers in hardware
3053  */
3054 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3055 {
3056         struct intel_crtc_scaler_state *scaler_state;
3057         int i;
3058
3059         scaler_state = &intel_crtc->config->scaler_state;
3060
3061         /* loop through and disable scalers that aren't in use */
3062         for (i = 0; i < intel_crtc->num_scalers; i++) {
3063                 if (!scaler_state->scalers[i].in_use)
3064                         skl_detach_scaler(intel_crtc, i);
3065         }
3066 }
3067
3068 u32 skl_plane_ctl_format(uint32_t pixel_format)
3069 {
3070         switch (pixel_format) {
3071         case DRM_FORMAT_C8:
3072                 return PLANE_CTL_FORMAT_INDEXED;
3073         case DRM_FORMAT_RGB565:
3074                 return PLANE_CTL_FORMAT_RGB_565;
3075         case DRM_FORMAT_XBGR8888:
3076                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3077         case DRM_FORMAT_XRGB8888:
3078                 return PLANE_CTL_FORMAT_XRGB_8888;
3079         /*
3080          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3081          * to be already pre-multiplied. We need to add a knob (or a different
3082          * DRM_FORMAT) for user-space to configure that.
3083          */
3084         case DRM_FORMAT_ABGR8888:
3085                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3086                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3087         case DRM_FORMAT_ARGB8888:
3088                 return PLANE_CTL_FORMAT_XRGB_8888 |
3089                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3090         case DRM_FORMAT_XRGB2101010:
3091                 return PLANE_CTL_FORMAT_XRGB_2101010;
3092         case DRM_FORMAT_XBGR2101010:
3093                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3094         case DRM_FORMAT_YUYV:
3095                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3096         case DRM_FORMAT_YVYU:
3097                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3098         case DRM_FORMAT_UYVY:
3099                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3100         case DRM_FORMAT_VYUY:
3101                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3102         default:
3103                 MISSING_CASE(pixel_format);
3104         }
3105
3106         return 0;
3107 }
3108
3109 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3110 {
3111         switch (fb_modifier) {
3112         case DRM_FORMAT_MOD_NONE:
3113                 break;
3114         case I915_FORMAT_MOD_X_TILED:
3115                 return PLANE_CTL_TILED_X;
3116         case I915_FORMAT_MOD_Y_TILED:
3117                 return PLANE_CTL_TILED_Y;
3118         case I915_FORMAT_MOD_Yf_TILED:
3119                 return PLANE_CTL_TILED_YF;
3120         default:
3121                 MISSING_CASE(fb_modifier);
3122         }
3123
3124         return 0;
3125 }
3126
3127 u32 skl_plane_ctl_rotation(unsigned int rotation)
3128 {
3129         switch (rotation) {
3130         case BIT(DRM_ROTATE_0):
3131                 break;
3132         /*
3133          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3134          * while i915 HW rotation is clockwise, thats why this swapping.
3135          */
3136         case BIT(DRM_ROTATE_90):
3137                 return PLANE_CTL_ROTATE_270;
3138         case BIT(DRM_ROTATE_180):
3139                 return PLANE_CTL_ROTATE_180;
3140         case BIT(DRM_ROTATE_270):
3141                 return PLANE_CTL_ROTATE_90;
3142         default:
3143                 MISSING_CASE(rotation);
3144         }
3145
3146         return 0;
3147 }
3148
3149 static void skylake_update_primary_plane(struct drm_plane *plane,
3150                                          const struct intel_crtc_state *crtc_state,
3151                                          const struct intel_plane_state *plane_state)
3152 {
3153         struct drm_device *dev = plane->dev;
3154         struct drm_i915_private *dev_priv = dev->dev_private;
3155         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3156         struct drm_framebuffer *fb = plane_state->base.fb;
3157         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3158         int pipe = intel_crtc->pipe;
3159         u32 plane_ctl, stride_div, stride;
3160         u32 tile_height, plane_offset, plane_size;
3161         unsigned int rotation = plane_state->base.rotation;
3162         int x_offset, y_offset;
3163         u32 surf_addr;
3164         int scaler_id = plane_state->scaler_id;
3165         int src_x = plane_state->src.x1 >> 16;
3166         int src_y = plane_state->src.y1 >> 16;
3167         int src_w = drm_rect_width(&plane_state->src) >> 16;
3168         int src_h = drm_rect_height(&plane_state->src) >> 16;
3169         int dst_x = plane_state->dst.x1;
3170         int dst_y = plane_state->dst.y1;
3171         int dst_w = drm_rect_width(&plane_state->dst);
3172         int dst_h = drm_rect_height(&plane_state->dst);
3173
3174         plane_ctl = PLANE_CTL_ENABLE |
3175                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3176                     PLANE_CTL_PIPE_CSC_ENABLE;
3177
3178         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3179         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3180         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3181         plane_ctl |= skl_plane_ctl_rotation(rotation);
3182
3183         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3184                                                fb->pixel_format);
3185         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3186
3187         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3188
3189         if (intel_rotation_90_or_270(rotation)) {
3190                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3191
3192                 /* stride = Surface height in tiles */
3193                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3194                 stride = DIV_ROUND_UP(fb->height, tile_height);
3195                 x_offset = stride * tile_height - src_y - src_h;
3196                 y_offset = src_x;
3197                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3198         } else {
3199                 stride = fb->pitches[0] / stride_div;
3200                 x_offset = src_x;
3201                 y_offset = src_y;
3202                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3203         }
3204         plane_offset = y_offset << 16 | x_offset;
3205
3206         intel_crtc->adjusted_x = x_offset;
3207         intel_crtc->adjusted_y = y_offset;
3208
3209         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3210         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3211         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3212         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3213
3214         if (scaler_id >= 0) {
3215                 uint32_t ps_ctrl = 0;
3216
3217                 WARN_ON(!dst_w || !dst_h);
3218                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3219                         crtc_state->scaler_state.scalers[scaler_id].mode;
3220                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3221                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3222                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3223                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3224                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3225         } else {
3226                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3227         }
3228
3229         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3230
3231         POSTING_READ(PLANE_SURF(pipe, 0));
3232 }
3233
3234 static void skylake_disable_primary_plane(struct drm_plane *primary,
3235                                           struct drm_crtc *crtc)
3236 {
3237         struct drm_device *dev = crtc->dev;
3238         struct drm_i915_private *dev_priv = dev->dev_private;
3239         int pipe = to_intel_crtc(crtc)->pipe;
3240
3241         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3242         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3243         POSTING_READ(PLANE_SURF(pipe, 0));
3244 }
3245
3246 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3247 static int
3248 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3249                            int x, int y, enum mode_set_atomic state)
3250 {
3251         /* Support for kgdboc is disabled, this needs a major rework. */
3252         DRM_ERROR("legacy panic handler not supported any more.\n");
3253
3254         return -ENODEV;
3255 }
3256
3257 static void intel_complete_page_flips(struct drm_device *dev)
3258 {
3259         struct drm_crtc *crtc;
3260
3261         for_each_crtc(dev, crtc) {
3262                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3263                 enum plane plane = intel_crtc->plane;
3264
3265                 intel_prepare_page_flip(dev, plane);
3266                 intel_finish_page_flip_plane(dev, plane);
3267         }
3268 }
3269
3270 static void intel_update_primary_planes(struct drm_device *dev)
3271 {
3272         struct drm_crtc *crtc;
3273
3274         for_each_crtc(dev, crtc) {
3275                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3276                 struct intel_plane_state *plane_state;
3277
3278                 drm_modeset_lock_crtc(crtc, &plane->base);
3279                 plane_state = to_intel_plane_state(plane->base.state);
3280
3281                 if (plane_state->visible)
3282                         plane->update_plane(&plane->base,
3283                                             to_intel_crtc_state(crtc->state),
3284                                             plane_state);
3285
3286                 drm_modeset_unlock_crtc(crtc);
3287         }
3288 }
3289
3290 void intel_prepare_reset(struct drm_device *dev)
3291 {
3292         /* no reset support for gen2 */
3293         if (IS_GEN2(dev))
3294                 return;
3295
3296         /* reset doesn't touch the display */
3297         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3298                 return;
3299
3300         drm_modeset_lock_all(dev);
3301         /*
3302          * Disabling the crtcs gracefully seems nicer. Also the
3303          * g33 docs say we should at least disable all the planes.
3304          */
3305         intel_display_suspend(dev);
3306 }
3307
3308 void intel_finish_reset(struct drm_device *dev)
3309 {
3310         struct drm_i915_private *dev_priv = to_i915(dev);
3311
3312         /*
3313          * Flips in the rings will be nuked by the reset,
3314          * so complete all pending flips so that user space
3315          * will get its events and not get stuck.
3316          */
3317         intel_complete_page_flips(dev);
3318
3319         /* no reset support for gen2 */
3320         if (IS_GEN2(dev))
3321                 return;
3322
3323         /* reset doesn't touch the display */
3324         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3325                 /*
3326                  * Flips in the rings have been nuked by the reset,
3327                  * so update the base address of all primary
3328                  * planes to the the last fb to make sure we're
3329                  * showing the correct fb after a reset.
3330                  *
3331                  * FIXME: Atomic will make this obsolete since we won't schedule
3332                  * CS-based flips (which might get lost in gpu resets) any more.
3333                  */
3334                 intel_update_primary_planes(dev);
3335                 return;
3336         }
3337
3338         /*
3339          * The display has been reset as well,
3340          * so need a full re-initialization.
3341          */
3342         intel_runtime_pm_disable_interrupts(dev_priv);
3343         intel_runtime_pm_enable_interrupts(dev_priv);
3344
3345         intel_modeset_init_hw(dev);
3346
3347         spin_lock_irq(&dev_priv->irq_lock);
3348         if (dev_priv->display.hpd_irq_setup)
3349                 dev_priv->display.hpd_irq_setup(dev);
3350         spin_unlock_irq(&dev_priv->irq_lock);
3351
3352         intel_display_resume(dev);
3353
3354         intel_hpd_init(dev_priv);
3355
3356         drm_modeset_unlock_all(dev);
3357 }
3358
3359 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3360 {
3361         struct drm_device *dev = crtc->dev;
3362         struct drm_i915_private *dev_priv = dev->dev_private;
3363         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3364         bool pending;
3365
3366         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3367             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3368                 return false;
3369
3370         spin_lock_irq(&dev->event_lock);
3371         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3372         spin_unlock_irq(&dev->event_lock);
3373
3374         return pending;
3375 }
3376
3377 static void intel_update_pipe_config(struct intel_crtc *crtc,
3378                                      struct intel_crtc_state *old_crtc_state)
3379 {
3380         struct drm_device *dev = crtc->base.dev;
3381         struct drm_i915_private *dev_priv = dev->dev_private;
3382         struct intel_crtc_state *pipe_config =
3383                 to_intel_crtc_state(crtc->base.state);
3384
3385         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3386         crtc->base.mode = crtc->base.state->mode;
3387
3388         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3389                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3390                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3391
3392         if (HAS_DDI(dev))
3393                 intel_set_pipe_csc(&crtc->base);
3394
3395         /*
3396          * Update pipe size and adjust fitter if needed: the reason for this is
3397          * that in compute_mode_changes we check the native mode (not the pfit
3398          * mode) to see if we can flip rather than do a full mode set. In the
3399          * fastboot case, we'll flip, but if we don't update the pipesrc and
3400          * pfit state, we'll end up with a big fb scanned out into the wrong
3401          * sized surface.
3402          */
3403
3404         I915_WRITE(PIPESRC(crtc->pipe),
3405                    ((pipe_config->pipe_src_w - 1) << 16) |
3406                    (pipe_config->pipe_src_h - 1));
3407
3408         /* on skylake this is done by detaching scalers */
3409         if (INTEL_INFO(dev)->gen >= 9) {
3410                 skl_detach_scalers(crtc);
3411
3412                 if (pipe_config->pch_pfit.enabled)
3413                         skylake_pfit_enable(crtc);
3414         } else if (HAS_PCH_SPLIT(dev)) {
3415                 if (pipe_config->pch_pfit.enabled)
3416                         ironlake_pfit_enable(crtc);
3417                 else if (old_crtc_state->pch_pfit.enabled)
3418                         ironlake_pfit_disable(crtc, true);
3419         }
3420 }
3421
3422 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3423 {
3424         struct drm_device *dev = crtc->dev;
3425         struct drm_i915_private *dev_priv = dev->dev_private;
3426         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3427         int pipe = intel_crtc->pipe;
3428         i915_reg_t reg;
3429         u32 temp;
3430
3431         /* enable normal train */
3432         reg = FDI_TX_CTL(pipe);
3433         temp = I915_READ(reg);
3434         if (IS_IVYBRIDGE(dev)) {
3435                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3436                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3437         } else {
3438                 temp &= ~FDI_LINK_TRAIN_NONE;
3439                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3440         }
3441         I915_WRITE(reg, temp);
3442
3443         reg = FDI_RX_CTL(pipe);
3444         temp = I915_READ(reg);
3445         if (HAS_PCH_CPT(dev)) {
3446                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3447                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3448         } else {
3449                 temp &= ~FDI_LINK_TRAIN_NONE;
3450                 temp |= FDI_LINK_TRAIN_NONE;
3451         }
3452         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3453
3454         /* wait one idle pattern time */
3455         POSTING_READ(reg);
3456         udelay(1000);
3457
3458         /* IVB wants error correction enabled */
3459         if (IS_IVYBRIDGE(dev))
3460                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3461                            FDI_FE_ERRC_ENABLE);
3462 }
3463
3464 /* The FDI link training functions for ILK/Ibexpeak. */
3465 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3466 {
3467         struct drm_device *dev = crtc->dev;
3468         struct drm_i915_private *dev_priv = dev->dev_private;
3469         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3470         int pipe = intel_crtc->pipe;
3471         i915_reg_t reg;
3472         u32 temp, tries;
3473
3474         /* FDI needs bits from pipe first */
3475         assert_pipe_enabled(dev_priv, pipe);
3476
3477         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3478            for train result */
3479         reg = FDI_RX_IMR(pipe);
3480         temp = I915_READ(reg);
3481         temp &= ~FDI_RX_SYMBOL_LOCK;
3482         temp &= ~FDI_RX_BIT_LOCK;
3483         I915_WRITE(reg, temp);
3484         I915_READ(reg);
3485         udelay(150);
3486
3487         /* enable CPU FDI TX and PCH FDI RX */
3488         reg = FDI_TX_CTL(pipe);
3489         temp = I915_READ(reg);
3490         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3491         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3492         temp &= ~FDI_LINK_TRAIN_NONE;
3493         temp |= FDI_LINK_TRAIN_PATTERN_1;
3494         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3495
3496         reg = FDI_RX_CTL(pipe);
3497         temp = I915_READ(reg);
3498         temp &= ~FDI_LINK_TRAIN_NONE;
3499         temp |= FDI_LINK_TRAIN_PATTERN_1;
3500         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3501
3502         POSTING_READ(reg);
3503         udelay(150);
3504
3505         /* Ironlake workaround, enable clock pointer after FDI enable*/
3506         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3507         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3508                    FDI_RX_PHASE_SYNC_POINTER_EN);
3509
3510         reg = FDI_RX_IIR(pipe);
3511         for (tries = 0; tries < 5; tries++) {
3512                 temp = I915_READ(reg);
3513                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3514
3515                 if ((temp & FDI_RX_BIT_LOCK)) {
3516                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3517                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3518                         break;
3519                 }
3520         }
3521         if (tries == 5)
3522                 DRM_ERROR("FDI train 1 fail!\n");
3523
3524         /* Train 2 */
3525         reg = FDI_TX_CTL(pipe);
3526         temp = I915_READ(reg);
3527         temp &= ~FDI_LINK_TRAIN_NONE;
3528         temp |= FDI_LINK_TRAIN_PATTERN_2;
3529         I915_WRITE(reg, temp);
3530
3531         reg = FDI_RX_CTL(pipe);
3532         temp = I915_READ(reg);
3533         temp &= ~FDI_LINK_TRAIN_NONE;
3534         temp |= FDI_LINK_TRAIN_PATTERN_2;
3535         I915_WRITE(reg, temp);
3536
3537         POSTING_READ(reg);
3538         udelay(150);
3539
3540         reg = FDI_RX_IIR(pipe);
3541         for (tries = 0; tries < 5; tries++) {
3542                 temp = I915_READ(reg);
3543                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3544
3545                 if (temp & FDI_RX_SYMBOL_LOCK) {
3546                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3547                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3548                         break;
3549                 }
3550         }
3551         if (tries == 5)
3552                 DRM_ERROR("FDI train 2 fail!\n");
3553
3554         DRM_DEBUG_KMS("FDI train done\n");
3555
3556 }
3557
3558 static const int snb_b_fdi_train_param[] = {
3559         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3560         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3561         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3562         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3563 };
3564
3565 /* The FDI link training functions for SNB/Cougarpoint. */
3566 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3567 {
3568         struct drm_device *dev = crtc->dev;
3569         struct drm_i915_private *dev_priv = dev->dev_private;
3570         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3571         int pipe = intel_crtc->pipe;
3572         i915_reg_t reg;
3573         u32 temp, i, retry;
3574
3575         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3576            for train result */
3577         reg = FDI_RX_IMR(pipe);
3578         temp = I915_READ(reg);
3579         temp &= ~FDI_RX_SYMBOL_LOCK;
3580         temp &= ~FDI_RX_BIT_LOCK;
3581         I915_WRITE(reg, temp);
3582
3583         POSTING_READ(reg);
3584         udelay(150);
3585
3586         /* enable CPU FDI TX and PCH FDI RX */
3587         reg = FDI_TX_CTL(pipe);
3588         temp = I915_READ(reg);
3589         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3590         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3591         temp &= ~FDI_LINK_TRAIN_NONE;
3592         temp |= FDI_LINK_TRAIN_PATTERN_1;
3593         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3594         /* SNB-B */
3595         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3596         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3597
3598         I915_WRITE(FDI_RX_MISC(pipe),
3599                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3600
3601         reg = FDI_RX_CTL(pipe);
3602         temp = I915_READ(reg);
3603         if (HAS_PCH_CPT(dev)) {
3604                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3605                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3606         } else {
3607                 temp &= ~FDI_LINK_TRAIN_NONE;
3608                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3609         }
3610         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3611
3612         POSTING_READ(reg);
3613         udelay(150);
3614
3615         for (i = 0; i < 4; i++) {
3616                 reg = FDI_TX_CTL(pipe);
3617                 temp = I915_READ(reg);
3618                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3619                 temp |= snb_b_fdi_train_param[i];
3620                 I915_WRITE(reg, temp);
3621
3622                 POSTING_READ(reg);
3623                 udelay(500);
3624
3625                 for (retry = 0; retry < 5; retry++) {
3626                         reg = FDI_RX_IIR(pipe);
3627                         temp = I915_READ(reg);
3628                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3629                         if (temp & FDI_RX_BIT_LOCK) {
3630                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3631                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3632                                 break;
3633                         }
3634                         udelay(50);
3635                 }
3636                 if (retry < 5)
3637                         break;
3638         }
3639         if (i == 4)
3640                 DRM_ERROR("FDI train 1 fail!\n");
3641
3642         /* Train 2 */
3643         reg = FDI_TX_CTL(pipe);
3644         temp = I915_READ(reg);
3645         temp &= ~FDI_LINK_TRAIN_NONE;
3646         temp |= FDI_LINK_TRAIN_PATTERN_2;
3647         if (IS_GEN6(dev)) {
3648                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3649                 /* SNB-B */
3650                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3651         }
3652         I915_WRITE(reg, temp);
3653
3654         reg = FDI_RX_CTL(pipe);
3655         temp = I915_READ(reg);
3656         if (HAS_PCH_CPT(dev)) {
3657                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3658                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3659         } else {
3660                 temp &= ~FDI_LINK_TRAIN_NONE;
3661                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3662         }
3663         I915_WRITE(reg, temp);
3664
3665         POSTING_READ(reg);
3666         udelay(150);
3667
3668         for (i = 0; i < 4; i++) {
3669                 reg = FDI_TX_CTL(pipe);
3670                 temp = I915_READ(reg);
3671                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3672                 temp |= snb_b_fdi_train_param[i];
3673                 I915_WRITE(reg, temp);
3674
3675                 POSTING_READ(reg);
3676                 udelay(500);
3677
3678                 for (retry = 0; retry < 5; retry++) {
3679                         reg = FDI_RX_IIR(pipe);
3680                         temp = I915_READ(reg);
3681                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3682                         if (temp & FDI_RX_SYMBOL_LOCK) {
3683                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3684                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3685                                 break;
3686                         }
3687                         udelay(50);
3688                 }
3689                 if (retry < 5)
3690                         break;
3691         }
3692         if (i == 4)
3693                 DRM_ERROR("FDI train 2 fail!\n");
3694
3695         DRM_DEBUG_KMS("FDI train done.\n");
3696 }
3697
3698 /* Manual link training for Ivy Bridge A0 parts */
3699 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3700 {
3701         struct drm_device *dev = crtc->dev;
3702         struct drm_i915_private *dev_priv = dev->dev_private;
3703         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3704         int pipe = intel_crtc->pipe;
3705         i915_reg_t reg;
3706         u32 temp, i, j;
3707
3708         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3709            for train result */
3710         reg = FDI_RX_IMR(pipe);
3711         temp = I915_READ(reg);
3712         temp &= ~FDI_RX_SYMBOL_LOCK;
3713         temp &= ~FDI_RX_BIT_LOCK;
3714         I915_WRITE(reg, temp);
3715
3716         POSTING_READ(reg);
3717         udelay(150);
3718
3719         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3720                       I915_READ(FDI_RX_IIR(pipe)));
3721
3722         /* Try each vswing and preemphasis setting twice before moving on */
3723         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3724                 /* disable first in case we need to retry */
3725                 reg = FDI_TX_CTL(pipe);
3726                 temp = I915_READ(reg);
3727                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3728                 temp &= ~FDI_TX_ENABLE;
3729                 I915_WRITE(reg, temp);
3730
3731                 reg = FDI_RX_CTL(pipe);
3732                 temp = I915_READ(reg);
3733                 temp &= ~FDI_LINK_TRAIN_AUTO;
3734                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3735                 temp &= ~FDI_RX_ENABLE;
3736                 I915_WRITE(reg, temp);
3737
3738                 /* enable CPU FDI TX and PCH FDI RX */
3739                 reg = FDI_TX_CTL(pipe);
3740                 temp = I915_READ(reg);
3741                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3742                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3743                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3744                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3745                 temp |= snb_b_fdi_train_param[j/2];
3746                 temp |= FDI_COMPOSITE_SYNC;
3747                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3748
3749                 I915_WRITE(FDI_RX_MISC(pipe),
3750                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3751
3752                 reg = FDI_RX_CTL(pipe);
3753                 temp = I915_READ(reg);
3754                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3755                 temp |= FDI_COMPOSITE_SYNC;
3756                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3757
3758                 POSTING_READ(reg);
3759                 udelay(1); /* should be 0.5us */
3760
3761                 for (i = 0; i < 4; i++) {
3762                         reg = FDI_RX_IIR(pipe);
3763                         temp = I915_READ(reg);
3764                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3765
3766                         if (temp & FDI_RX_BIT_LOCK ||
3767                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3768                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3769                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3770                                               i);
3771                                 break;
3772                         }
3773                         udelay(1); /* should be 0.5us */
3774                 }
3775                 if (i == 4) {
3776                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3777                         continue;
3778                 }
3779
3780                 /* Train 2 */
3781                 reg = FDI_TX_CTL(pipe);
3782                 temp = I915_READ(reg);
3783                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3784                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3785                 I915_WRITE(reg, temp);
3786
3787                 reg = FDI_RX_CTL(pipe);
3788                 temp = I915_READ(reg);
3789                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3790                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3791                 I915_WRITE(reg, temp);
3792
3793                 POSTING_READ(reg);
3794                 udelay(2); /* should be 1.5us */
3795
3796                 for (i = 0; i < 4; i++) {
3797                         reg = FDI_RX_IIR(pipe);
3798                         temp = I915_READ(reg);
3799                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3800
3801                         if (temp & FDI_RX_SYMBOL_LOCK ||
3802                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3803                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3804                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3805                                               i);
3806                                 goto train_done;
3807                         }
3808                         udelay(2); /* should be 1.5us */
3809                 }
3810                 if (i == 4)
3811                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3812         }
3813
3814 train_done:
3815         DRM_DEBUG_KMS("FDI train done.\n");
3816 }
3817
3818 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3819 {
3820         struct drm_device *dev = intel_crtc->base.dev;
3821         struct drm_i915_private *dev_priv = dev->dev_private;
3822         int pipe = intel_crtc->pipe;
3823         i915_reg_t reg;
3824         u32 temp;
3825
3826         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3827         reg = FDI_RX_CTL(pipe);
3828         temp = I915_READ(reg);
3829         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3830         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3831         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3832         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3833
3834         POSTING_READ(reg);
3835         udelay(200);
3836
3837         /* Switch from Rawclk to PCDclk */
3838         temp = I915_READ(reg);
3839         I915_WRITE(reg, temp | FDI_PCDCLK);
3840
3841         POSTING_READ(reg);
3842         udelay(200);
3843
3844         /* Enable CPU FDI TX PLL, always on for Ironlake */
3845         reg = FDI_TX_CTL(pipe);
3846         temp = I915_READ(reg);
3847         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3848                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3849
3850                 POSTING_READ(reg);
3851                 udelay(100);
3852         }
3853 }
3854
3855 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3856 {
3857         struct drm_device *dev = intel_crtc->base.dev;
3858         struct drm_i915_private *dev_priv = dev->dev_private;
3859         int pipe = intel_crtc->pipe;
3860         i915_reg_t reg;
3861         u32 temp;
3862
3863         /* Switch from PCDclk to Rawclk */
3864         reg = FDI_RX_CTL(pipe);
3865         temp = I915_READ(reg);
3866         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3867
3868         /* Disable CPU FDI TX PLL */
3869         reg = FDI_TX_CTL(pipe);
3870         temp = I915_READ(reg);
3871         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3872
3873         POSTING_READ(reg);
3874         udelay(100);
3875
3876         reg = FDI_RX_CTL(pipe);
3877         temp = I915_READ(reg);
3878         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3879
3880         /* Wait for the clocks to turn off. */
3881         POSTING_READ(reg);
3882         udelay(100);
3883 }
3884
3885 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3886 {
3887         struct drm_device *dev = crtc->dev;
3888         struct drm_i915_private *dev_priv = dev->dev_private;
3889         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3890         int pipe = intel_crtc->pipe;
3891         i915_reg_t reg;
3892         u32 temp;
3893
3894         /* disable CPU FDI tx and PCH FDI rx */
3895         reg = FDI_TX_CTL(pipe);
3896         temp = I915_READ(reg);
3897         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3898         POSTING_READ(reg);
3899
3900         reg = FDI_RX_CTL(pipe);
3901         temp = I915_READ(reg);
3902         temp &= ~(0x7 << 16);
3903         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3904         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3905
3906         POSTING_READ(reg);
3907         udelay(100);
3908
3909         /* Ironlake workaround, disable clock pointer after downing FDI */
3910         if (HAS_PCH_IBX(dev))
3911                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3912
3913         /* still set train pattern 1 */
3914         reg = FDI_TX_CTL(pipe);
3915         temp = I915_READ(reg);
3916         temp &= ~FDI_LINK_TRAIN_NONE;
3917         temp |= FDI_LINK_TRAIN_PATTERN_1;
3918         I915_WRITE(reg, temp);
3919
3920         reg = FDI_RX_CTL(pipe);
3921         temp = I915_READ(reg);
3922         if (HAS_PCH_CPT(dev)) {
3923                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3924                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3925         } else {
3926                 temp &= ~FDI_LINK_TRAIN_NONE;
3927                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3928         }
3929         /* BPC in FDI rx is consistent with that in PIPECONF */
3930         temp &= ~(0x07 << 16);
3931         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3932         I915_WRITE(reg, temp);
3933
3934         POSTING_READ(reg);
3935         udelay(100);
3936 }
3937
3938 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3939 {
3940         struct intel_crtc *crtc;
3941
3942         /* Note that we don't need to be called with mode_config.lock here
3943          * as our list of CRTC objects is static for the lifetime of the
3944          * device and so cannot disappear as we iterate. Similarly, we can
3945          * happily treat the predicates as racy, atomic checks as userspace
3946          * cannot claim and pin a new fb without at least acquring the
3947          * struct_mutex and so serialising with us.
3948          */
3949         for_each_intel_crtc(dev, crtc) {
3950                 if (atomic_read(&crtc->unpin_work_count) == 0)
3951                         continue;
3952
3953                 if (crtc->unpin_work)
3954                         intel_wait_for_vblank(dev, crtc->pipe);
3955
3956                 return true;
3957         }
3958
3959         return false;
3960 }
3961
3962 static void page_flip_completed(struct intel_crtc *intel_crtc)
3963 {
3964         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3965         struct intel_unpin_work *work = intel_crtc->unpin_work;
3966
3967         /* ensure that the unpin work is consistent wrt ->pending. */
3968         smp_rmb();
3969         intel_crtc->unpin_work = NULL;
3970
3971         if (work->event)
3972                 drm_send_vblank_event(intel_crtc->base.dev,
3973                                       intel_crtc->pipe,
3974                                       work->event);
3975
3976         drm_crtc_vblank_put(&intel_crtc->base);
3977
3978         wake_up_all(&dev_priv->pending_flip_queue);
3979         queue_work(dev_priv->wq, &work->work);
3980
3981         trace_i915_flip_complete(intel_crtc->plane,
3982                                  work->pending_flip_obj);
3983 }
3984
3985 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3986 {
3987         struct drm_device *dev = crtc->dev;
3988         struct drm_i915_private *dev_priv = dev->dev_private;
3989         long ret;
3990
3991         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3992
3993         ret = wait_event_interruptible_timeout(
3994                                         dev_priv->pending_flip_queue,
3995                                         !intel_crtc_has_pending_flip(crtc),
3996                                         60*HZ);
3997
3998         if (ret < 0)
3999                 return ret;
4000
4001         if (ret == 0) {
4002                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4003
4004                 spin_lock_irq(&dev->event_lock);
4005                 if (intel_crtc->unpin_work) {
4006                         WARN_ONCE(1, "Removing stuck page flip\n");
4007                         page_flip_completed(intel_crtc);
4008                 }
4009                 spin_unlock_irq(&dev->event_lock);
4010         }
4011
4012         return 0;
4013 }
4014
4015 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4016 {
4017         u32 temp;
4018
4019         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4020
4021         mutex_lock(&dev_priv->sb_lock);
4022
4023         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4024         temp |= SBI_SSCCTL_DISABLE;
4025         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4026
4027         mutex_unlock(&dev_priv->sb_lock);
4028 }
4029
4030 /* Program iCLKIP clock to the desired frequency */
4031 static void lpt_program_iclkip(struct drm_crtc *crtc)
4032 {
4033         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
4034         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
4035         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4036         u32 temp;
4037
4038         lpt_disable_iclkip(dev_priv);
4039
4040         /* The iCLK virtual clock root frequency is in MHz,
4041          * but the adjusted_mode->crtc_clock in in KHz. To get the
4042          * divisors, it is necessary to divide one by another, so we
4043          * convert the virtual clock precision to KHz here for higher
4044          * precision.
4045          */
4046         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4047                 u32 iclk_virtual_root_freq = 172800 * 1000;
4048                 u32 iclk_pi_range = 64;
4049                 u32 desired_divisor;
4050
4051                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4052                                                     clock << auxdiv);
4053                 divsel = (desired_divisor / iclk_pi_range) - 2;
4054                 phaseinc = desired_divisor % iclk_pi_range;
4055
4056                 /*
4057                  * Near 20MHz is a corner case which is
4058                  * out of range for the 7-bit divisor
4059                  */
4060                 if (divsel <= 0x7f)
4061                         break;
4062         }
4063
4064         /* This should not happen with any sane values */
4065         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4066                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4067         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4068                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4069
4070         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4071                         clock,
4072                         auxdiv,
4073                         divsel,
4074                         phasedir,
4075                         phaseinc);
4076
4077         mutex_lock(&dev_priv->sb_lock);
4078
4079         /* Program SSCDIVINTPHASE6 */
4080         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4081         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4082         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4083         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4084         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4085         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4086         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4087         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4088
4089         /* Program SSCAUXDIV */
4090         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4091         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4092         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4093         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4094
4095         /* Enable modulator and associated divider */
4096         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4097         temp &= ~SBI_SSCCTL_DISABLE;
4098         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4099
4100         mutex_unlock(&dev_priv->sb_lock);
4101
4102         /* Wait for initialization time */
4103         udelay(24);
4104
4105         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4106 }
4107
4108 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4109 {
4110         u32 divsel, phaseinc, auxdiv;
4111         u32 iclk_virtual_root_freq = 172800 * 1000;
4112         u32 iclk_pi_range = 64;
4113         u32 desired_divisor;
4114         u32 temp;
4115
4116         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4117                 return 0;
4118
4119         mutex_lock(&dev_priv->sb_lock);
4120
4121         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4122         if (temp & SBI_SSCCTL_DISABLE) {
4123                 mutex_unlock(&dev_priv->sb_lock);
4124                 return 0;
4125         }
4126
4127         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4128         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4129                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4130         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4131                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4132
4133         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4134         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4135                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4136
4137         mutex_unlock(&dev_priv->sb_lock);
4138
4139         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4140
4141         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4142                                  desired_divisor << auxdiv);
4143 }
4144
4145 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4146                                                 enum pipe pch_transcoder)
4147 {
4148         struct drm_device *dev = crtc->base.dev;
4149         struct drm_i915_private *dev_priv = dev->dev_private;
4150         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4151
4152         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4153                    I915_READ(HTOTAL(cpu_transcoder)));
4154         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4155                    I915_READ(HBLANK(cpu_transcoder)));
4156         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4157                    I915_READ(HSYNC(cpu_transcoder)));
4158
4159         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4160                    I915_READ(VTOTAL(cpu_transcoder)));
4161         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4162                    I915_READ(VBLANK(cpu_transcoder)));
4163         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4164                    I915_READ(VSYNC(cpu_transcoder)));
4165         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4166                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4167 }
4168
4169 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4170 {
4171         struct drm_i915_private *dev_priv = dev->dev_private;
4172         uint32_t temp;
4173
4174         temp = I915_READ(SOUTH_CHICKEN1);
4175         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4176                 return;
4177
4178         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4179         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4180
4181         temp &= ~FDI_BC_BIFURCATION_SELECT;
4182         if (enable)
4183                 temp |= FDI_BC_BIFURCATION_SELECT;
4184
4185         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4186         I915_WRITE(SOUTH_CHICKEN1, temp);
4187         POSTING_READ(SOUTH_CHICKEN1);
4188 }
4189
4190 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4191 {
4192         struct drm_device *dev = intel_crtc->base.dev;
4193
4194         switch (intel_crtc->pipe) {
4195         case PIPE_A:
4196                 break;
4197         case PIPE_B:
4198                 if (intel_crtc->config->fdi_lanes > 2)
4199                         cpt_set_fdi_bc_bifurcation(dev, false);
4200                 else
4201                         cpt_set_fdi_bc_bifurcation(dev, true);
4202
4203                 break;
4204         case PIPE_C:
4205                 cpt_set_fdi_bc_bifurcation(dev, true);
4206
4207                 break;
4208         default:
4209                 BUG();
4210         }
4211 }
4212
4213 /* Return which DP Port should be selected for Transcoder DP control */
4214 static enum port
4215 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4216 {
4217         struct drm_device *dev = crtc->dev;
4218         struct intel_encoder *encoder;
4219
4220         for_each_encoder_on_crtc(dev, crtc, encoder) {
4221                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4222                     encoder->type == INTEL_OUTPUT_EDP)
4223                         return enc_to_dig_port(&encoder->base)->port;
4224         }
4225
4226         return -1;
4227 }
4228
4229 /*
4230  * Enable PCH resources required for PCH ports:
4231  *   - PCH PLLs
4232  *   - FDI training & RX/TX
4233  *   - update transcoder timings
4234  *   - DP transcoding bits
4235  *   - transcoder
4236  */
4237 static void ironlake_pch_enable(struct drm_crtc *crtc)
4238 {
4239         struct drm_device *dev = crtc->dev;
4240         struct drm_i915_private *dev_priv = dev->dev_private;
4241         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4242         int pipe = intel_crtc->pipe;
4243         u32 temp;
4244
4245         assert_pch_transcoder_disabled(dev_priv, pipe);
4246
4247         if (IS_IVYBRIDGE(dev))
4248                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4249
4250         /* Write the TU size bits before fdi link training, so that error
4251          * detection works. */
4252         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4253                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4254
4255         /*
4256          * Sometimes spurious CPU pipe underruns happen during FDI
4257          * training, at least with VGA+HDMI cloning. Suppress them.
4258          */
4259         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4260
4261         /* For PCH output, training FDI link */
4262         dev_priv->display.fdi_link_train(crtc);
4263
4264         /* We need to program the right clock selection before writing the pixel
4265          * mutliplier into the DPLL. */
4266         if (HAS_PCH_CPT(dev)) {
4267                 u32 sel;
4268
4269                 temp = I915_READ(PCH_DPLL_SEL);
4270                 temp |= TRANS_DPLL_ENABLE(pipe);
4271                 sel = TRANS_DPLLB_SEL(pipe);
4272                 if (intel_crtc->config->shared_dpll == DPLL_ID_PCH_PLL_B)
4273                         temp |= sel;
4274                 else
4275                         temp &= ~sel;
4276                 I915_WRITE(PCH_DPLL_SEL, temp);
4277         }
4278
4279         /* XXX: pch pll's can be enabled any time before we enable the PCH
4280          * transcoder, and we actually should do this to not upset any PCH
4281          * transcoder that already use the clock when we share it.
4282          *
4283          * Note that enable_shared_dpll tries to do the right thing, but
4284          * get_shared_dpll unconditionally resets the pll - we need that to have
4285          * the right LVDS enable sequence. */
4286         intel_enable_shared_dpll(intel_crtc);
4287
4288         /* set transcoder timing, panel must allow it */
4289         assert_panel_unlocked(dev_priv, pipe);
4290         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4291
4292         intel_fdi_normal_train(crtc);
4293
4294         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4295
4296         /* For PCH DP, enable TRANS_DP_CTL */
4297         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4298                 const struct drm_display_mode *adjusted_mode =
4299                         &intel_crtc->config->base.adjusted_mode;
4300                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4301                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4302                 temp = I915_READ(reg);
4303                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4304                           TRANS_DP_SYNC_MASK |
4305                           TRANS_DP_BPC_MASK);
4306                 temp |= TRANS_DP_OUTPUT_ENABLE;
4307                 temp |= bpc << 9; /* same format but at 11:9 */
4308
4309                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4310                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4311                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4312                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4313
4314                 switch (intel_trans_dp_port_sel(crtc)) {
4315                 case PORT_B:
4316                         temp |= TRANS_DP_PORT_SEL_B;
4317                         break;
4318                 case PORT_C:
4319                         temp |= TRANS_DP_PORT_SEL_C;
4320                         break;
4321                 case PORT_D:
4322                         temp |= TRANS_DP_PORT_SEL_D;
4323                         break;
4324                 default:
4325                         BUG();
4326                 }
4327
4328                 I915_WRITE(reg, temp);
4329         }
4330
4331         ironlake_enable_pch_transcoder(dev_priv, pipe);
4332 }
4333
4334 static void lpt_pch_enable(struct drm_crtc *crtc)
4335 {
4336         struct drm_device *dev = crtc->dev;
4337         struct drm_i915_private *dev_priv = dev->dev_private;
4338         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4339         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4340
4341         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4342
4343         lpt_program_iclkip(crtc);
4344
4345         /* Set transcoder timing. */
4346         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4347
4348         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4349 }
4350
4351 struct intel_shared_dpll *intel_get_shared_dpll(struct intel_crtc *crtc,
4352                                                 struct intel_crtc_state *crtc_state)
4353 {
4354         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
4355         struct intel_shared_dpll *pll;
4356         struct intel_shared_dpll_config *shared_dpll;
4357         enum intel_dpll_id i;
4358         int max = dev_priv->num_shared_dpll;
4359
4360         shared_dpll = intel_atomic_get_shared_dpll_state(crtc_state->base.state);
4361
4362         if (HAS_PCH_IBX(dev_priv->dev)) {
4363                 /* Ironlake PCH has a fixed PLL->PCH pipe mapping. */
4364                 i = (enum intel_dpll_id) crtc->pipe;
4365                 pll = &dev_priv->shared_dplls[i];
4366
4367                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4368                               crtc->base.base.id, pll->name);
4369
4370                 WARN_ON(shared_dpll[i].crtc_mask);
4371
4372                 goto found;
4373         }
4374
4375         if (IS_BROXTON(dev_priv->dev)) {
4376                 /* PLL is attached to port in bxt */
4377                 struct intel_encoder *encoder;
4378                 struct intel_digital_port *intel_dig_port;
4379
4380                 encoder = intel_ddi_get_crtc_new_encoder(crtc_state);
4381                 if (WARN_ON(!encoder))
4382                         return NULL;
4383
4384                 intel_dig_port = enc_to_dig_port(&encoder->base);
4385                 /* 1:1 mapping between ports and PLLs */
4386                 i = (enum intel_dpll_id)intel_dig_port->port;
4387                 pll = &dev_priv->shared_dplls[i];
4388                 DRM_DEBUG_KMS("CRTC:%d using pre-allocated %s\n",
4389                         crtc->base.base.id, pll->name);
4390                 WARN_ON(shared_dpll[i].crtc_mask);
4391
4392                 goto found;
4393         } else if (INTEL_INFO(dev_priv)->gen < 9 && HAS_DDI(dev_priv))
4394                 /* Do not consider SPLL */
4395                 max = 2;
4396
4397         for (i = 0; i < max; i++) {
4398                 pll = &dev_priv->shared_dplls[i];
4399
4400                 /* Only want to check enabled timings first */
4401                 if (shared_dpll[i].crtc_mask == 0)
4402                         continue;
4403
4404                 if (memcmp(&crtc_state->dpll_hw_state,
4405                            &shared_dpll[i].hw_state,
4406                            sizeof(crtc_state->dpll_hw_state)) == 0) {
4407                         DRM_DEBUG_KMS("CRTC:%d sharing existing %s (crtc mask 0x%08x, ative %d)\n",
4408                                       crtc->base.base.id, pll->name,
4409                                       shared_dpll[i].crtc_mask,
4410                                       pll->active);
4411                         goto found;
4412                 }
4413         }
4414
4415         /* Ok no matching timings, maybe there's a free one? */
4416         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4417                 pll = &dev_priv->shared_dplls[i];
4418                 if (shared_dpll[i].crtc_mask == 0) {
4419                         DRM_DEBUG_KMS("CRTC:%d allocated %s\n",
4420                                       crtc->base.base.id, pll->name);
4421                         goto found;
4422                 }
4423         }
4424
4425         return NULL;
4426
4427 found:
4428         if (shared_dpll[i].crtc_mask == 0)
4429                 shared_dpll[i].hw_state =
4430                         crtc_state->dpll_hw_state;
4431
4432         crtc_state->shared_dpll = i;
4433         DRM_DEBUG_DRIVER("using %s for pipe %c\n", pll->name,
4434                          pipe_name(crtc->pipe));
4435
4436         shared_dpll[i].crtc_mask |= 1 << crtc->pipe;
4437
4438         return pll;
4439 }
4440
4441 static void intel_shared_dpll_commit(struct drm_atomic_state *state)
4442 {
4443         struct drm_i915_private *dev_priv = to_i915(state->dev);
4444         struct intel_shared_dpll_config *shared_dpll;
4445         struct intel_shared_dpll *pll;
4446         enum intel_dpll_id i;
4447
4448         if (!to_intel_atomic_state(state)->dpll_set)
4449                 return;
4450
4451         shared_dpll = to_intel_atomic_state(state)->shared_dpll;
4452         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
4453                 pll = &dev_priv->shared_dplls[i];
4454                 pll->config = shared_dpll[i];
4455         }
4456 }
4457
4458 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4459 {
4460         struct drm_i915_private *dev_priv = dev->dev_private;
4461         i915_reg_t dslreg = PIPEDSL(pipe);
4462         u32 temp;
4463
4464         temp = I915_READ(dslreg);
4465         udelay(500);
4466         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4467                 if (wait_for(I915_READ(dslreg) != temp, 5))
4468                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4469         }
4470 }
4471
4472 static int
4473 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4474                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4475                   int src_w, int src_h, int dst_w, int dst_h)
4476 {
4477         struct intel_crtc_scaler_state *scaler_state =
4478                 &crtc_state->scaler_state;
4479         struct intel_crtc *intel_crtc =
4480                 to_intel_crtc(crtc_state->base.crtc);
4481         int need_scaling;
4482
4483         need_scaling = intel_rotation_90_or_270(rotation) ?
4484                 (src_h != dst_w || src_w != dst_h):
4485                 (src_w != dst_w || src_h != dst_h);
4486
4487         /*
4488          * if plane is being disabled or scaler is no more required or force detach
4489          *  - free scaler binded to this plane/crtc
4490          *  - in order to do this, update crtc->scaler_usage
4491          *
4492          * Here scaler state in crtc_state is set free so that
4493          * scaler can be assigned to other user. Actual register
4494          * update to free the scaler is done in plane/panel-fit programming.
4495          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4496          */
4497         if (force_detach || !need_scaling) {
4498                 if (*scaler_id >= 0) {
4499                         scaler_state->scaler_users &= ~(1 << scaler_user);
4500                         scaler_state->scalers[*scaler_id].in_use = 0;
4501
4502                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4503                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4504                                 intel_crtc->pipe, scaler_user, *scaler_id,
4505                                 scaler_state->scaler_users);
4506                         *scaler_id = -1;
4507                 }
4508                 return 0;
4509         }
4510
4511         /* range checks */
4512         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4513                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4514
4515                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4516                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4517                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4518                         "size is out of scaler range\n",
4519                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4520                 return -EINVAL;
4521         }
4522
4523         /* mark this plane as a scaler user in crtc_state */
4524         scaler_state->scaler_users |= (1 << scaler_user);
4525         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4526                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4527                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4528                 scaler_state->scaler_users);
4529
4530         return 0;
4531 }
4532
4533 /**
4534  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4535  *
4536  * @state: crtc's scaler state
4537  *
4538  * Return
4539  *     0 - scaler_usage updated successfully
4540  *    error - requested scaling cannot be supported or other error condition
4541  */
4542 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4543 {
4544         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4545         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4546
4547         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4548                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4549
4550         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4551                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4552                 state->pipe_src_w, state->pipe_src_h,
4553                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4554 }
4555
4556 /**
4557  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4558  *
4559  * @state: crtc's scaler state
4560  * @plane_state: atomic plane state to update
4561  *
4562  * Return
4563  *     0 - scaler_usage updated successfully
4564  *    error - requested scaling cannot be supported or other error condition
4565  */
4566 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4567                                    struct intel_plane_state *plane_state)
4568 {
4569
4570         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4571         struct intel_plane *intel_plane =
4572                 to_intel_plane(plane_state->base.plane);
4573         struct drm_framebuffer *fb = plane_state->base.fb;
4574         int ret;
4575
4576         bool force_detach = !fb || !plane_state->visible;
4577
4578         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4579                       intel_plane->base.base.id, intel_crtc->pipe,
4580                       drm_plane_index(&intel_plane->base));
4581
4582         ret = skl_update_scaler(crtc_state, force_detach,
4583                                 drm_plane_index(&intel_plane->base),
4584                                 &plane_state->scaler_id,
4585                                 plane_state->base.rotation,
4586                                 drm_rect_width(&plane_state->src) >> 16,
4587                                 drm_rect_height(&plane_state->src) >> 16,
4588                                 drm_rect_width(&plane_state->dst),
4589                                 drm_rect_height(&plane_state->dst));
4590
4591         if (ret || plane_state->scaler_id < 0)
4592                 return ret;
4593
4594         /* check colorkey */
4595         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4596                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4597                               intel_plane->base.base.id);
4598                 return -EINVAL;
4599         }
4600
4601         /* Check src format */
4602         switch (fb->pixel_format) {
4603         case DRM_FORMAT_RGB565:
4604         case DRM_FORMAT_XBGR8888:
4605         case DRM_FORMAT_XRGB8888:
4606         case DRM_FORMAT_ABGR8888:
4607         case DRM_FORMAT_ARGB8888:
4608         case DRM_FORMAT_XRGB2101010:
4609         case DRM_FORMAT_XBGR2101010:
4610         case DRM_FORMAT_YUYV:
4611         case DRM_FORMAT_YVYU:
4612         case DRM_FORMAT_UYVY:
4613         case DRM_FORMAT_VYUY:
4614                 break;
4615         default:
4616                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4617                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4618                 return -EINVAL;
4619         }
4620
4621         return 0;
4622 }
4623
4624 static void skylake_scaler_disable(struct intel_crtc *crtc)
4625 {
4626         int i;
4627
4628         for (i = 0; i < crtc->num_scalers; i++)
4629                 skl_detach_scaler(crtc, i);
4630 }
4631
4632 static void skylake_pfit_enable(struct intel_crtc *crtc)
4633 {
4634         struct drm_device *dev = crtc->base.dev;
4635         struct drm_i915_private *dev_priv = dev->dev_private;
4636         int pipe = crtc->pipe;
4637         struct intel_crtc_scaler_state *scaler_state =
4638                 &crtc->config->scaler_state;
4639
4640         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4641
4642         if (crtc->config->pch_pfit.enabled) {
4643                 int id;
4644
4645                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4646                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4647                         return;
4648                 }
4649
4650                 id = scaler_state->scaler_id;
4651                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4652                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4653                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4654                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4655
4656                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4657         }
4658 }
4659
4660 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4661 {
4662         struct drm_device *dev = crtc->base.dev;
4663         struct drm_i915_private *dev_priv = dev->dev_private;
4664         int pipe = crtc->pipe;
4665
4666         if (crtc->config->pch_pfit.enabled) {
4667                 /* Force use of hard-coded filter coefficients
4668                  * as some pre-programmed values are broken,
4669                  * e.g. x201.
4670                  */
4671                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4672                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4673                                                  PF_PIPE_SEL_IVB(pipe));
4674                 else
4675                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4676                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4677                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4678         }
4679 }
4680
4681 void hsw_enable_ips(struct intel_crtc *crtc)
4682 {
4683         struct drm_device *dev = crtc->base.dev;
4684         struct drm_i915_private *dev_priv = dev->dev_private;
4685
4686         if (!crtc->config->ips_enabled)
4687                 return;
4688
4689         /* We can only enable IPS after we enable a plane and wait for a vblank */
4690         intel_wait_for_vblank(dev, crtc->pipe);
4691
4692         assert_plane_enabled(dev_priv, crtc->plane);
4693         if (IS_BROADWELL(dev)) {
4694                 mutex_lock(&dev_priv->rps.hw_lock);
4695                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4696                 mutex_unlock(&dev_priv->rps.hw_lock);
4697                 /* Quoting Art Runyan: "its not safe to expect any particular
4698                  * value in IPS_CTL bit 31 after enabling IPS through the
4699                  * mailbox." Moreover, the mailbox may return a bogus state,
4700                  * so we need to just enable it and continue on.
4701                  */
4702         } else {
4703                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4704                 /* The bit only becomes 1 in the next vblank, so this wait here
4705                  * is essentially intel_wait_for_vblank. If we don't have this
4706                  * and don't wait for vblanks until the end of crtc_enable, then
4707                  * the HW state readout code will complain that the expected
4708                  * IPS_CTL value is not the one we read. */
4709                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4710                         DRM_ERROR("Timed out waiting for IPS enable\n");
4711         }
4712 }
4713
4714 void hsw_disable_ips(struct intel_crtc *crtc)
4715 {
4716         struct drm_device *dev = crtc->base.dev;
4717         struct drm_i915_private *dev_priv = dev->dev_private;
4718
4719         if (!crtc->config->ips_enabled)
4720                 return;
4721
4722         assert_plane_enabled(dev_priv, crtc->plane);
4723         if (IS_BROADWELL(dev)) {
4724                 mutex_lock(&dev_priv->rps.hw_lock);
4725                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4726                 mutex_unlock(&dev_priv->rps.hw_lock);
4727                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4728                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4729                         DRM_ERROR("Timed out waiting for IPS disable\n");
4730         } else {
4731                 I915_WRITE(IPS_CTL, 0);
4732                 POSTING_READ(IPS_CTL);
4733         }
4734
4735         /* We need to wait for a vblank before we can disable the plane. */
4736         intel_wait_for_vblank(dev, crtc->pipe);
4737 }
4738
4739 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4740 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4741 {
4742         struct drm_device *dev = crtc->dev;
4743         struct drm_i915_private *dev_priv = dev->dev_private;
4744         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4745         enum pipe pipe = intel_crtc->pipe;
4746         int i;
4747         bool reenable_ips = false;
4748
4749         /* The clocks have to be on to load the palette. */
4750         if (!crtc->state->active)
4751                 return;
4752
4753         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4754                 if (intel_crtc->config->has_dsi_encoder)
4755                         assert_dsi_pll_enabled(dev_priv);
4756                 else
4757                         assert_pll_enabled(dev_priv, pipe);
4758         }
4759
4760         /* Workaround : Do not read or write the pipe palette/gamma data while
4761          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4762          */
4763         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4764             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4765              GAMMA_MODE_MODE_SPLIT)) {
4766                 hsw_disable_ips(intel_crtc);
4767                 reenable_ips = true;
4768         }
4769
4770         for (i = 0; i < 256; i++) {
4771                 i915_reg_t palreg;
4772
4773                 if (HAS_GMCH_DISPLAY(dev))
4774                         palreg = PALETTE(pipe, i);
4775                 else
4776                         palreg = LGC_PALETTE(pipe, i);
4777
4778                 I915_WRITE(palreg,
4779                            (intel_crtc->lut_r[i] << 16) |
4780                            (intel_crtc->lut_g[i] << 8) |
4781                            intel_crtc->lut_b[i]);
4782         }
4783
4784         if (reenable_ips)
4785                 hsw_enable_ips(intel_crtc);
4786 }
4787
4788 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4789 {
4790         if (intel_crtc->overlay) {
4791                 struct drm_device *dev = intel_crtc->base.dev;
4792                 struct drm_i915_private *dev_priv = dev->dev_private;
4793
4794                 mutex_lock(&dev->struct_mutex);
4795                 dev_priv->mm.interruptible = false;
4796                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4797                 dev_priv->mm.interruptible = true;
4798                 mutex_unlock(&dev->struct_mutex);
4799         }
4800
4801         /* Let userspace switch the overlay on again. In most cases userspace
4802          * has to recompute where to put it anyway.
4803          */
4804 }
4805
4806 /**
4807  * intel_post_enable_primary - Perform operations after enabling primary plane
4808  * @crtc: the CRTC whose primary plane was just enabled
4809  *
4810  * Performs potentially sleeping operations that must be done after the primary
4811  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4812  * called due to an explicit primary plane update, or due to an implicit
4813  * re-enable that is caused when a sprite plane is updated to no longer
4814  * completely hide the primary plane.
4815  */
4816 static void
4817 intel_post_enable_primary(struct drm_crtc *crtc)
4818 {
4819         struct drm_device *dev = crtc->dev;
4820         struct drm_i915_private *dev_priv = dev->dev_private;
4821         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4822         int pipe = intel_crtc->pipe;
4823
4824         /*
4825          * FIXME IPS should be fine as long as one plane is
4826          * enabled, but in practice it seems to have problems
4827          * when going from primary only to sprite only and vice
4828          * versa.
4829          */
4830         hsw_enable_ips(intel_crtc);
4831
4832         /*
4833          * Gen2 reports pipe underruns whenever all planes are disabled.
4834          * So don't enable underrun reporting before at least some planes
4835          * are enabled.
4836          * FIXME: Need to fix the logic to work when we turn off all planes
4837          * but leave the pipe running.
4838          */
4839         if (IS_GEN2(dev))
4840                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4841
4842         /* Underruns don't always raise interrupts, so check manually. */
4843         intel_check_cpu_fifo_underruns(dev_priv);
4844         intel_check_pch_fifo_underruns(dev_priv);
4845 }
4846
4847 /**
4848  * intel_pre_disable_primary - Perform operations before disabling primary plane
4849  * @crtc: the CRTC whose primary plane is to be disabled
4850  *
4851  * Performs potentially sleeping operations that must be done before the
4852  * primary plane is disabled, such as updating FBC and IPS.  Note that this may
4853  * be called due to an explicit primary plane update, or due to an implicit
4854  * disable that is caused when a sprite plane completely hides the primary
4855  * plane.
4856  */
4857 static void
4858 intel_pre_disable_primary(struct drm_crtc *crtc)
4859 {
4860         struct drm_device *dev = crtc->dev;
4861         struct drm_i915_private *dev_priv = dev->dev_private;
4862         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4863         int pipe = intel_crtc->pipe;
4864
4865         /*
4866          * Gen2 reports pipe underruns whenever all planes are disabled.
4867          * So diasble underrun reporting before all the planes get disabled.
4868          * FIXME: Need to fix the logic to work when we turn off all planes
4869          * but leave the pipe running.
4870          */
4871         if (IS_GEN2(dev))
4872                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4873
4874         /*
4875          * Vblank time updates from the shadow to live plane control register
4876          * are blocked if the memory self-refresh mode is active at that
4877          * moment. So to make sure the plane gets truly disabled, disable
4878          * first the self-refresh mode. The self-refresh enable bit in turn
4879          * will be checked/applied by the HW only at the next frame start
4880          * event which is after the vblank start event, so we need to have a
4881          * wait-for-vblank between disabling the plane and the pipe.
4882          */
4883         if (HAS_GMCH_DISPLAY(dev)) {
4884                 intel_set_memory_cxsr(dev_priv, false);
4885                 dev_priv->wm.vlv.cxsr = false;
4886                 intel_wait_for_vblank(dev, pipe);
4887         }
4888
4889         /*
4890          * FIXME IPS should be fine as long as one plane is
4891          * enabled, but in practice it seems to have problems
4892          * when going from primary only to sprite only and vice
4893          * versa.
4894          */
4895         hsw_disable_ips(intel_crtc);
4896 }
4897
4898 static void intel_post_plane_update(struct intel_crtc *crtc)
4899 {
4900         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4901         struct intel_crtc_state *pipe_config =
4902                 to_intel_crtc_state(crtc->base.state);
4903         struct drm_device *dev = crtc->base.dev;
4904
4905         intel_frontbuffer_flip(dev, atomic->fb_bits);
4906
4907         crtc->wm.cxsr_allowed = true;
4908
4909         if (pipe_config->wm_changed && pipe_config->base.active)
4910                 intel_update_watermarks(&crtc->base);
4911
4912         if (atomic->update_fbc)
4913                 intel_fbc_post_update(crtc);
4914
4915         if (atomic->post_enable_primary)
4916                 intel_post_enable_primary(&crtc->base);
4917
4918         memset(atomic, 0, sizeof(*atomic));
4919 }
4920
4921 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4922 {
4923         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4924         struct drm_device *dev = crtc->base.dev;
4925         struct drm_i915_private *dev_priv = dev->dev_private;
4926         struct intel_crtc_atomic_commit *atomic = &crtc->atomic;
4927         struct intel_crtc_state *pipe_config =
4928                 to_intel_crtc_state(crtc->base.state);
4929         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4930         struct drm_plane *primary = crtc->base.primary;
4931         struct drm_plane_state *old_pri_state =
4932                 drm_atomic_get_existing_plane_state(old_state, primary);
4933         bool modeset = needs_modeset(&pipe_config->base);
4934
4935         if (atomic->update_fbc)
4936                 intel_fbc_pre_update(crtc);
4937
4938         if (old_pri_state) {
4939                 struct intel_plane_state *primary_state =
4940                         to_intel_plane_state(primary->state);
4941                 struct intel_plane_state *old_primary_state =
4942                         to_intel_plane_state(old_pri_state);
4943
4944                 if (old_primary_state->visible &&
4945                     (modeset || !primary_state->visible))
4946                         intel_pre_disable_primary(&crtc->base);
4947         }
4948
4949         if (pipe_config->disable_cxsr) {
4950                 crtc->wm.cxsr_allowed = false;
4951
4952                 if (old_crtc_state->base.active)
4953                         intel_set_memory_cxsr(dev_priv, false);
4954         }
4955
4956         /*
4957          * IVB workaround: must disable low power watermarks for at least
4958          * one frame before enabling scaling.  LP watermarks can be re-enabled
4959          * when scaling is disabled.
4960          *
4961          * WaCxSRDisabledForSpriteScaling:ivb
4962          */
4963         if (pipe_config->disable_lp_wm) {
4964                 ilk_disable_lp_wm(dev);
4965                 intel_wait_for_vblank(dev, crtc->pipe);
4966         }
4967
4968         /*
4969          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4970          * watermark programming here.
4971          */
4972         if (needs_modeset(&pipe_config->base))
4973                 return;
4974
4975         /*
4976          * For platforms that support atomic watermarks, program the
4977          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4978          * will be the intermediate values that are safe for both pre- and
4979          * post- vblank; when vblank happens, the 'active' values will be set
4980          * to the final 'target' values and we'll do this again to get the
4981          * optimal watermarks.  For gen9+ platforms, the values we program here
4982          * will be the final target values which will get automatically latched
4983          * at vblank time; no further programming will be necessary.
4984          *
4985          * If a platform hasn't been transitioned to atomic watermarks yet,
4986          * we'll continue to update watermarks the old way, if flags tell
4987          * us to.
4988          */
4989         if (dev_priv->display.initial_watermarks != NULL)
4990                 dev_priv->display.initial_watermarks(pipe_config);
4991         else if (pipe_config->wm_changed)
4992                 intel_update_watermarks(&crtc->base);
4993 }
4994
4995 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4996 {
4997         struct drm_device *dev = crtc->dev;
4998         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4999         struct drm_plane *p;
5000         int pipe = intel_crtc->pipe;
5001
5002         intel_crtc_dpms_overlay_disable(intel_crtc);
5003
5004         drm_for_each_plane_mask(p, dev, plane_mask)
5005                 to_intel_plane(p)->disable_plane(p, crtc);
5006
5007         /*
5008          * FIXME: Once we grow proper nuclear flip support out of this we need
5009          * to compute the mask of flip planes precisely. For the time being
5010          * consider this a flip to a NULL plane.
5011          */
5012         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
5013 }
5014
5015 static void ironlake_crtc_enable(struct drm_crtc *crtc)
5016 {
5017         struct drm_device *dev = crtc->dev;
5018         struct drm_i915_private *dev_priv = dev->dev_private;
5019         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5020         struct intel_encoder *encoder;
5021         int pipe = intel_crtc->pipe;
5022
5023         if (WARN_ON(intel_crtc->active))
5024                 return;
5025
5026         if (intel_crtc->config->has_pch_encoder)
5027                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5028
5029         if (intel_crtc->config->has_pch_encoder)
5030                 intel_prepare_shared_dpll(intel_crtc);
5031
5032         if (intel_crtc->config->has_dp_encoder)
5033                 intel_dp_set_m_n(intel_crtc, M1_N1);
5034
5035         intel_set_pipe_timings(intel_crtc);
5036
5037         if (intel_crtc->config->has_pch_encoder) {
5038                 intel_cpu_transcoder_set_m_n(intel_crtc,
5039                                      &intel_crtc->config->fdi_m_n, NULL);
5040         }
5041
5042         ironlake_set_pipeconf(crtc);
5043
5044         intel_crtc->active = true;
5045
5046         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5047
5048         for_each_encoder_on_crtc(dev, crtc, encoder)
5049                 if (encoder->pre_enable)
5050                         encoder->pre_enable(encoder);
5051
5052         if (intel_crtc->config->has_pch_encoder) {
5053                 /* Note: FDI PLL enabling _must_ be done before we enable the
5054                  * cpu pipes, hence this is separate from all the other fdi/pch
5055                  * enabling. */
5056                 ironlake_fdi_pll_enable(intel_crtc);
5057         } else {
5058                 assert_fdi_tx_disabled(dev_priv, pipe);
5059                 assert_fdi_rx_disabled(dev_priv, pipe);
5060         }
5061
5062         ironlake_pfit_enable(intel_crtc);
5063
5064         /*
5065          * On ILK+ LUT must be loaded before the pipe is running but with
5066          * clocks enabled
5067          */
5068         intel_crtc_load_lut(crtc);
5069
5070         if (dev_priv->display.initial_watermarks != NULL)
5071                 dev_priv->display.initial_watermarks(intel_crtc->config);
5072         intel_enable_pipe(intel_crtc);
5073
5074         if (intel_crtc->config->has_pch_encoder)
5075                 ironlake_pch_enable(crtc);
5076
5077         assert_vblank_disabled(crtc);
5078         drm_crtc_vblank_on(crtc);
5079
5080         for_each_encoder_on_crtc(dev, crtc, encoder)
5081                 encoder->enable(encoder);
5082
5083         if (HAS_PCH_CPT(dev))
5084                 cpt_verify_modeset(dev, intel_crtc->pipe);
5085
5086         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5087         if (intel_crtc->config->has_pch_encoder)
5088                 intel_wait_for_vblank(dev, pipe);
5089         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5090 }
5091
5092 /* IPS only exists on ULT machines and is tied to pipe A. */
5093 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5094 {
5095         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
5096 }
5097
5098 static void haswell_crtc_enable(struct drm_crtc *crtc)
5099 {
5100         struct drm_device *dev = crtc->dev;
5101         struct drm_i915_private *dev_priv = dev->dev_private;
5102         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5103         struct intel_encoder *encoder;
5104         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5105         struct intel_crtc_state *pipe_config =
5106                 to_intel_crtc_state(crtc->state);
5107
5108         if (WARN_ON(intel_crtc->active))
5109                 return;
5110
5111         if (intel_crtc->config->has_pch_encoder)
5112                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5113                                                       false);
5114
5115         if (intel_crtc_to_shared_dpll(intel_crtc))
5116                 intel_enable_shared_dpll(intel_crtc);
5117
5118         if (intel_crtc->config->has_dp_encoder)
5119                 intel_dp_set_m_n(intel_crtc, M1_N1);
5120
5121         intel_set_pipe_timings(intel_crtc);
5122
5123         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
5124                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
5125                            intel_crtc->config->pixel_multiplier - 1);
5126         }
5127
5128         if (intel_crtc->config->has_pch_encoder) {
5129                 intel_cpu_transcoder_set_m_n(intel_crtc,
5130                                      &intel_crtc->config->fdi_m_n, NULL);
5131         }
5132
5133         haswell_set_pipeconf(crtc);
5134
5135         intel_set_pipe_csc(crtc);
5136
5137         intel_crtc->active = true;
5138
5139         if (intel_crtc->config->has_pch_encoder)
5140                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5141         else
5142                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5143
5144         for_each_encoder_on_crtc(dev, crtc, encoder) {
5145                 if (encoder->pre_enable)
5146                         encoder->pre_enable(encoder);
5147         }
5148
5149         if (intel_crtc->config->has_pch_encoder)
5150                 dev_priv->display.fdi_link_train(crtc);
5151
5152         if (!intel_crtc->config->has_dsi_encoder)
5153                 intel_ddi_enable_pipe_clock(intel_crtc);
5154
5155         if (INTEL_INFO(dev)->gen >= 9)
5156                 skylake_pfit_enable(intel_crtc);
5157         else
5158                 ironlake_pfit_enable(intel_crtc);
5159
5160         /*
5161          * On ILK+ LUT must be loaded before the pipe is running but with
5162          * clocks enabled
5163          */
5164         intel_crtc_load_lut(crtc);
5165
5166         intel_ddi_set_pipe_settings(crtc);
5167         if (!intel_crtc->config->has_dsi_encoder)
5168                 intel_ddi_enable_transcoder_func(crtc);
5169
5170         if (dev_priv->display.initial_watermarks != NULL)
5171                 dev_priv->display.initial_watermarks(pipe_config);
5172         else
5173                 intel_update_watermarks(crtc);
5174         intel_enable_pipe(intel_crtc);
5175
5176         if (intel_crtc->config->has_pch_encoder)
5177                 lpt_pch_enable(crtc);
5178
5179         if (intel_crtc->config->dp_encoder_is_mst)
5180                 intel_ddi_set_vc_payload_alloc(crtc, true);
5181
5182         assert_vblank_disabled(crtc);
5183         drm_crtc_vblank_on(crtc);
5184
5185         for_each_encoder_on_crtc(dev, crtc, encoder) {
5186                 encoder->enable(encoder);
5187                 intel_opregion_notify_encoder(encoder, true);
5188         }
5189
5190         if (intel_crtc->config->has_pch_encoder) {
5191                 intel_wait_for_vblank(dev, pipe);
5192                 intel_wait_for_vblank(dev, pipe);
5193                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5194                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5195                                                       true);
5196         }
5197
5198         /* If we change the relative order between pipe/planes enabling, we need
5199          * to change the workaround. */
5200         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5201         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
5202                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5203                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5204         }
5205 }
5206
5207 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5208 {
5209         struct drm_device *dev = crtc->base.dev;
5210         struct drm_i915_private *dev_priv = dev->dev_private;
5211         int pipe = crtc->pipe;
5212
5213         /* To avoid upsetting the power well on haswell only disable the pfit if
5214          * it's in use. The hw state code will make sure we get this right. */
5215         if (force || crtc->config->pch_pfit.enabled) {
5216                 I915_WRITE(PF_CTL(pipe), 0);
5217                 I915_WRITE(PF_WIN_POS(pipe), 0);
5218                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5219         }
5220 }
5221
5222 static void ironlake_crtc_disable(struct drm_crtc *crtc)
5223 {
5224         struct drm_device *dev = crtc->dev;
5225         struct drm_i915_private *dev_priv = dev->dev_private;
5226         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5227         struct intel_encoder *encoder;
5228         int pipe = intel_crtc->pipe;
5229
5230         if (intel_crtc->config->has_pch_encoder)
5231                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5232
5233         for_each_encoder_on_crtc(dev, crtc, encoder)
5234                 encoder->disable(encoder);
5235
5236         drm_crtc_vblank_off(crtc);
5237         assert_vblank_disabled(crtc);
5238
5239         /*
5240          * Sometimes spurious CPU pipe underruns happen when the
5241          * pipe is already disabled, but FDI RX/TX is still enabled.
5242          * Happens at least with VGA+HDMI cloning. Suppress them.
5243          */
5244         if (intel_crtc->config->has_pch_encoder)
5245                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5246
5247         intel_disable_pipe(intel_crtc);
5248
5249         ironlake_pfit_disable(intel_crtc, false);
5250
5251         if (intel_crtc->config->has_pch_encoder) {
5252                 ironlake_fdi_disable(crtc);
5253                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5254         }
5255
5256         for_each_encoder_on_crtc(dev, crtc, encoder)
5257                 if (encoder->post_disable)
5258                         encoder->post_disable(encoder);
5259
5260         if (intel_crtc->config->has_pch_encoder) {
5261                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5262
5263                 if (HAS_PCH_CPT(dev)) {
5264                         i915_reg_t reg;
5265                         u32 temp;
5266
5267                         /* disable TRANS_DP_CTL */
5268                         reg = TRANS_DP_CTL(pipe);
5269                         temp = I915_READ(reg);
5270                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5271                                   TRANS_DP_PORT_SEL_MASK);
5272                         temp |= TRANS_DP_PORT_SEL_NONE;
5273                         I915_WRITE(reg, temp);
5274
5275                         /* disable DPLL_SEL */
5276                         temp = I915_READ(PCH_DPLL_SEL);
5277                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5278                         I915_WRITE(PCH_DPLL_SEL, temp);
5279                 }
5280
5281                 ironlake_fdi_pll_disable(intel_crtc);
5282         }
5283
5284         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5285 }
5286
5287 static void haswell_crtc_disable(struct drm_crtc *crtc)
5288 {
5289         struct drm_device *dev = crtc->dev;
5290         struct drm_i915_private *dev_priv = dev->dev_private;
5291         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5292         struct intel_encoder *encoder;
5293         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5294
5295         if (intel_crtc->config->has_pch_encoder)
5296                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5297                                                       false);
5298
5299         for_each_encoder_on_crtc(dev, crtc, encoder) {
5300                 intel_opregion_notify_encoder(encoder, false);
5301                 encoder->disable(encoder);
5302         }
5303
5304         drm_crtc_vblank_off(crtc);
5305         assert_vblank_disabled(crtc);
5306
5307         intel_disable_pipe(intel_crtc);
5308
5309         if (intel_crtc->config->dp_encoder_is_mst)
5310                 intel_ddi_set_vc_payload_alloc(crtc, false);
5311
5312         if (!intel_crtc->config->has_dsi_encoder)
5313                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5314
5315         if (INTEL_INFO(dev)->gen >= 9)
5316                 skylake_scaler_disable(intel_crtc);
5317         else
5318                 ironlake_pfit_disable(intel_crtc, false);
5319
5320         if (!intel_crtc->config->has_dsi_encoder)
5321                 intel_ddi_disable_pipe_clock(intel_crtc);
5322
5323         for_each_encoder_on_crtc(dev, crtc, encoder)
5324                 if (encoder->post_disable)
5325                         encoder->post_disable(encoder);
5326
5327         if (intel_crtc->config->has_pch_encoder) {
5328                 lpt_disable_pch_transcoder(dev_priv);
5329                 lpt_disable_iclkip(dev_priv);
5330                 intel_ddi_fdi_disable(crtc);
5331
5332                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5333                                                       true);
5334         }
5335 }
5336
5337 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5338 {
5339         struct drm_device *dev = crtc->base.dev;
5340         struct drm_i915_private *dev_priv = dev->dev_private;
5341         struct intel_crtc_state *pipe_config = crtc->config;
5342
5343         if (!pipe_config->gmch_pfit.control)
5344                 return;
5345
5346         /*
5347          * The panel fitter should only be adjusted whilst the pipe is disabled,
5348          * according to register description and PRM.
5349          */
5350         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5351         assert_pipe_disabled(dev_priv, crtc->pipe);
5352
5353         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5354         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5355
5356         /* Border color in case we don't scale up to the full screen. Black by
5357          * default, change to something else for debugging. */
5358         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5359 }
5360
5361 static enum intel_display_power_domain port_to_power_domain(enum port port)
5362 {
5363         switch (port) {
5364         case PORT_A:
5365                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5366         case PORT_B:
5367                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5368         case PORT_C:
5369                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5370         case PORT_D:
5371                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5372         case PORT_E:
5373                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5374         default:
5375                 MISSING_CASE(port);
5376                 return POWER_DOMAIN_PORT_OTHER;
5377         }
5378 }
5379
5380 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5381 {
5382         switch (port) {
5383         case PORT_A:
5384                 return POWER_DOMAIN_AUX_A;
5385         case PORT_B:
5386                 return POWER_DOMAIN_AUX_B;
5387         case PORT_C:
5388                 return POWER_DOMAIN_AUX_C;
5389         case PORT_D:
5390                 return POWER_DOMAIN_AUX_D;
5391         case PORT_E:
5392                 /* FIXME: Check VBT for actual wiring of PORT E */
5393                 return POWER_DOMAIN_AUX_D;
5394         default:
5395                 MISSING_CASE(port);
5396                 return POWER_DOMAIN_AUX_A;
5397         }
5398 }
5399
5400 enum intel_display_power_domain
5401 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5402 {
5403         struct drm_device *dev = intel_encoder->base.dev;
5404         struct intel_digital_port *intel_dig_port;
5405
5406         switch (intel_encoder->type) {
5407         case INTEL_OUTPUT_UNKNOWN:
5408                 /* Only DDI platforms should ever use this output type */
5409                 WARN_ON_ONCE(!HAS_DDI(dev));
5410         case INTEL_OUTPUT_DISPLAYPORT:
5411         case INTEL_OUTPUT_HDMI:
5412         case INTEL_OUTPUT_EDP:
5413                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5414                 return port_to_power_domain(intel_dig_port->port);
5415         case INTEL_OUTPUT_DP_MST:
5416                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5417                 return port_to_power_domain(intel_dig_port->port);
5418         case INTEL_OUTPUT_ANALOG:
5419                 return POWER_DOMAIN_PORT_CRT;
5420         case INTEL_OUTPUT_DSI:
5421                 return POWER_DOMAIN_PORT_DSI;
5422         default:
5423                 return POWER_DOMAIN_PORT_OTHER;
5424         }
5425 }
5426
5427 enum intel_display_power_domain
5428 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5429 {
5430         struct drm_device *dev = intel_encoder->base.dev;
5431         struct intel_digital_port *intel_dig_port;
5432
5433         switch (intel_encoder->type) {
5434         case INTEL_OUTPUT_UNKNOWN:
5435         case INTEL_OUTPUT_HDMI:
5436                 /*
5437                  * Only DDI platforms should ever use these output types.
5438                  * We can get here after the HDMI detect code has already set
5439                  * the type of the shared encoder. Since we can't be sure
5440                  * what's the status of the given connectors, play safe and
5441                  * run the DP detection too.
5442                  */
5443                 WARN_ON_ONCE(!HAS_DDI(dev));
5444         case INTEL_OUTPUT_DISPLAYPORT:
5445         case INTEL_OUTPUT_EDP:
5446                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5447                 return port_to_aux_power_domain(intel_dig_port->port);
5448         case INTEL_OUTPUT_DP_MST:
5449                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5450                 return port_to_aux_power_domain(intel_dig_port->port);
5451         default:
5452                 MISSING_CASE(intel_encoder->type);
5453                 return POWER_DOMAIN_AUX_A;
5454         }
5455 }
5456
5457 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5458                                             struct intel_crtc_state *crtc_state)
5459 {
5460         struct drm_device *dev = crtc->dev;
5461         struct drm_encoder *encoder;
5462         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5463         enum pipe pipe = intel_crtc->pipe;
5464         unsigned long mask;
5465         enum transcoder transcoder = crtc_state->cpu_transcoder;
5466
5467         if (!crtc_state->base.active)
5468                 return 0;
5469
5470         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5471         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5472         if (crtc_state->pch_pfit.enabled ||
5473             crtc_state->pch_pfit.force_thru)
5474                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5475
5476         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5477                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5478
5479                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5480         }
5481
5482         return mask;
5483 }
5484
5485 static unsigned long
5486 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5487                                struct intel_crtc_state *crtc_state)
5488 {
5489         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5490         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5491         enum intel_display_power_domain domain;
5492         unsigned long domains, new_domains, old_domains;
5493
5494         old_domains = intel_crtc->enabled_power_domains;
5495         intel_crtc->enabled_power_domains = new_domains =
5496                 get_crtc_power_domains(crtc, crtc_state);
5497
5498         domains = new_domains & ~old_domains;
5499
5500         for_each_power_domain(domain, domains)
5501                 intel_display_power_get(dev_priv, domain);
5502
5503         return old_domains & ~new_domains;
5504 }
5505
5506 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5507                                       unsigned long domains)
5508 {
5509         enum intel_display_power_domain domain;
5510
5511         for_each_power_domain(domain, domains)
5512                 intel_display_power_put(dev_priv, domain);
5513 }
5514
5515 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5516 {
5517         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5518
5519         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5520             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5521                 return max_cdclk_freq;
5522         else if (IS_CHERRYVIEW(dev_priv))
5523                 return max_cdclk_freq*95/100;
5524         else if (INTEL_INFO(dev_priv)->gen < 4)
5525                 return 2*max_cdclk_freq*90/100;
5526         else
5527                 return max_cdclk_freq*90/100;
5528 }
5529
5530 static void intel_update_max_cdclk(struct drm_device *dev)
5531 {
5532         struct drm_i915_private *dev_priv = dev->dev_private;
5533
5534         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5535                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5536
5537                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5538                         dev_priv->max_cdclk_freq = 675000;
5539                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5540                         dev_priv->max_cdclk_freq = 540000;
5541                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5542                         dev_priv->max_cdclk_freq = 450000;
5543                 else
5544                         dev_priv->max_cdclk_freq = 337500;
5545         } else if (IS_BROADWELL(dev))  {
5546                 /*
5547                  * FIXME with extra cooling we can allow
5548                  * 540 MHz for ULX and 675 Mhz for ULT.
5549                  * How can we know if extra cooling is
5550                  * available? PCI ID, VTB, something else?
5551                  */
5552                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5553                         dev_priv->max_cdclk_freq = 450000;
5554                 else if (IS_BDW_ULX(dev))
5555                         dev_priv->max_cdclk_freq = 450000;
5556                 else if (IS_BDW_ULT(dev))
5557                         dev_priv->max_cdclk_freq = 540000;
5558                 else
5559                         dev_priv->max_cdclk_freq = 675000;
5560         } else if (IS_CHERRYVIEW(dev)) {
5561                 dev_priv->max_cdclk_freq = 320000;
5562         } else if (IS_VALLEYVIEW(dev)) {
5563                 dev_priv->max_cdclk_freq = 400000;
5564         } else {
5565                 /* otherwise assume cdclk is fixed */
5566                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5567         }
5568
5569         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5570
5571         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5572                          dev_priv->max_cdclk_freq);
5573
5574         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5575                          dev_priv->max_dotclk_freq);
5576 }
5577
5578 static void intel_update_cdclk(struct drm_device *dev)
5579 {
5580         struct drm_i915_private *dev_priv = dev->dev_private;
5581
5582         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5583         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5584                          dev_priv->cdclk_freq);
5585
5586         /*
5587          * Program the gmbus_freq based on the cdclk frequency.
5588          * BSpec erroneously claims we should aim for 4MHz, but
5589          * in fact 1MHz is the correct frequency.
5590          */
5591         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
5592                 /*
5593                  * Program the gmbus_freq based on the cdclk frequency.
5594                  * BSpec erroneously claims we should aim for 4MHz, but
5595                  * in fact 1MHz is the correct frequency.
5596                  */
5597                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5598         }
5599
5600         if (dev_priv->max_cdclk_freq == 0)
5601                 intel_update_max_cdclk(dev);
5602 }
5603
5604 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5605 {
5606         struct drm_i915_private *dev_priv = dev->dev_private;
5607         uint32_t divider;
5608         uint32_t ratio;
5609         uint32_t current_freq;
5610         int ret;
5611
5612         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5613         switch (frequency) {
5614         case 144000:
5615                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5616                 ratio = BXT_DE_PLL_RATIO(60);
5617                 break;
5618         case 288000:
5619                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5620                 ratio = BXT_DE_PLL_RATIO(60);
5621                 break;
5622         case 384000:
5623                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5624                 ratio = BXT_DE_PLL_RATIO(60);
5625                 break;
5626         case 576000:
5627                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5628                 ratio = BXT_DE_PLL_RATIO(60);
5629                 break;
5630         case 624000:
5631                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5632                 ratio = BXT_DE_PLL_RATIO(65);
5633                 break;
5634         case 19200:
5635                 /*
5636                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5637                  * to suppress GCC warning.
5638                  */
5639                 ratio = 0;
5640                 divider = 0;
5641                 break;
5642         default:
5643                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5644
5645                 return;
5646         }
5647
5648         mutex_lock(&dev_priv->rps.hw_lock);
5649         /* Inform power controller of upcoming frequency change */
5650         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5651                                       0x80000000);
5652         mutex_unlock(&dev_priv->rps.hw_lock);
5653
5654         if (ret) {
5655                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5656                           ret, frequency);
5657                 return;
5658         }
5659
5660         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5661         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5662         current_freq = current_freq * 500 + 1000;
5663
5664         /*
5665          * DE PLL has to be disabled when
5666          * - setting to 19.2MHz (bypass, PLL isn't used)
5667          * - before setting to 624MHz (PLL needs toggling)
5668          * - before setting to any frequency from 624MHz (PLL needs toggling)
5669          */
5670         if (frequency == 19200 || frequency == 624000 ||
5671             current_freq == 624000) {
5672                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5673                 /* Timeout 200us */
5674                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5675                              1))
5676                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5677         }
5678
5679         if (frequency != 19200) {
5680                 uint32_t val;
5681
5682                 val = I915_READ(BXT_DE_PLL_CTL);
5683                 val &= ~BXT_DE_PLL_RATIO_MASK;
5684                 val |= ratio;
5685                 I915_WRITE(BXT_DE_PLL_CTL, val);
5686
5687                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5688                 /* Timeout 200us */
5689                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5690                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5691
5692                 val = I915_READ(CDCLK_CTL);
5693                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5694                 val |= divider;
5695                 /*
5696                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5697                  * enable otherwise.
5698                  */
5699                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5700                 if (frequency >= 500000)
5701                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5702
5703                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5704                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5705                 val |= (frequency - 1000) / 500;
5706                 I915_WRITE(CDCLK_CTL, val);
5707         }
5708
5709         mutex_lock(&dev_priv->rps.hw_lock);
5710         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5711                                       DIV_ROUND_UP(frequency, 25000));
5712         mutex_unlock(&dev_priv->rps.hw_lock);
5713
5714         if (ret) {
5715                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5716                           ret, frequency);
5717                 return;
5718         }
5719
5720         intel_update_cdclk(dev);
5721 }
5722
5723 void broxton_init_cdclk(struct drm_device *dev)
5724 {
5725         struct drm_i915_private *dev_priv = dev->dev_private;
5726         uint32_t val;
5727
5728         /*
5729          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5730          * or else the reset will hang because there is no PCH to respond.
5731          * Move the handshake programming to initialization sequence.
5732          * Previously was left up to BIOS.
5733          */
5734         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5735         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5736         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5737
5738         /* Enable PG1 for cdclk */
5739         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5740
5741         /* check if cd clock is enabled */
5742         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5743                 DRM_DEBUG_KMS("Display already initialized\n");
5744                 return;
5745         }
5746
5747         /*
5748          * FIXME:
5749          * - The initial CDCLK needs to be read from VBT.
5750          *   Need to make this change after VBT has changes for BXT.
5751          * - check if setting the max (or any) cdclk freq is really necessary
5752          *   here, it belongs to modeset time
5753          */
5754         broxton_set_cdclk(dev, 624000);
5755
5756         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5757         POSTING_READ(DBUF_CTL);
5758
5759         udelay(10);
5760
5761         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5762                 DRM_ERROR("DBuf power enable timeout!\n");
5763 }
5764
5765 void broxton_uninit_cdclk(struct drm_device *dev)
5766 {
5767         struct drm_i915_private *dev_priv = dev->dev_private;
5768
5769         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5770         POSTING_READ(DBUF_CTL);
5771
5772         udelay(10);
5773
5774         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5775                 DRM_ERROR("DBuf power disable timeout!\n");
5776
5777         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5778         broxton_set_cdclk(dev, 19200);
5779
5780         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5781 }
5782
5783 static const struct skl_cdclk_entry {
5784         unsigned int freq;
5785         unsigned int vco;
5786 } skl_cdclk_frequencies[] = {
5787         { .freq = 308570, .vco = 8640 },
5788         { .freq = 337500, .vco = 8100 },
5789         { .freq = 432000, .vco = 8640 },
5790         { .freq = 450000, .vco = 8100 },
5791         { .freq = 540000, .vco = 8100 },
5792         { .freq = 617140, .vco = 8640 },
5793         { .freq = 675000, .vco = 8100 },
5794 };
5795
5796 static unsigned int skl_cdclk_decimal(unsigned int freq)
5797 {
5798         return (freq - 1000) / 500;
5799 }
5800
5801 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5802 {
5803         unsigned int i;
5804
5805         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5806                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5807
5808                 if (e->freq == freq)
5809                         return e->vco;
5810         }
5811
5812         return 8100;
5813 }
5814
5815 static void
5816 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5817 {
5818         unsigned int min_freq;
5819         u32 val;
5820
5821         /* select the minimum CDCLK before enabling DPLL 0 */
5822         val = I915_READ(CDCLK_CTL);
5823         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5824         val |= CDCLK_FREQ_337_308;
5825
5826         if (required_vco == 8640)
5827                 min_freq = 308570;
5828         else
5829                 min_freq = 337500;
5830
5831         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5832
5833         I915_WRITE(CDCLK_CTL, val);
5834         POSTING_READ(CDCLK_CTL);
5835
5836         /*
5837          * We always enable DPLL0 with the lowest link rate possible, but still
5838          * taking into account the VCO required to operate the eDP panel at the
5839          * desired frequency. The usual DP link rates operate with a VCO of
5840          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5841          * The modeset code is responsible for the selection of the exact link
5842          * rate later on, with the constraint of choosing a frequency that
5843          * works with required_vco.
5844          */
5845         val = I915_READ(DPLL_CTRL1);
5846
5847         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5848                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5849         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5850         if (required_vco == 8640)
5851                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5852                                             SKL_DPLL0);
5853         else
5854                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5855                                             SKL_DPLL0);
5856
5857         I915_WRITE(DPLL_CTRL1, val);
5858         POSTING_READ(DPLL_CTRL1);
5859
5860         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5861
5862         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5863                 DRM_ERROR("DPLL0 not locked\n");
5864 }
5865
5866 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5867 {
5868         int ret;
5869         u32 val;
5870
5871         /* inform PCU we want to change CDCLK */
5872         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5873         mutex_lock(&dev_priv->rps.hw_lock);
5874         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5875         mutex_unlock(&dev_priv->rps.hw_lock);
5876
5877         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5878 }
5879
5880 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5881 {
5882         unsigned int i;
5883
5884         for (i = 0; i < 15; i++) {
5885                 if (skl_cdclk_pcu_ready(dev_priv))
5886                         return true;
5887                 udelay(10);
5888         }
5889
5890         return false;
5891 }
5892
5893 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5894 {
5895         struct drm_device *dev = dev_priv->dev;
5896         u32 freq_select, pcu_ack;
5897
5898         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5899
5900         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5901                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5902                 return;
5903         }
5904
5905         /* set CDCLK_CTL */
5906         switch(freq) {
5907         case 450000:
5908         case 432000:
5909                 freq_select = CDCLK_FREQ_450_432;
5910                 pcu_ack = 1;
5911                 break;
5912         case 540000:
5913                 freq_select = CDCLK_FREQ_540;
5914                 pcu_ack = 2;
5915                 break;
5916         case 308570:
5917         case 337500:
5918         default:
5919                 freq_select = CDCLK_FREQ_337_308;
5920                 pcu_ack = 0;
5921                 break;
5922         case 617140:
5923         case 675000:
5924                 freq_select = CDCLK_FREQ_675_617;
5925                 pcu_ack = 3;
5926                 break;
5927         }
5928
5929         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5930         POSTING_READ(CDCLK_CTL);
5931
5932         /* inform PCU of the change */
5933         mutex_lock(&dev_priv->rps.hw_lock);
5934         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5935         mutex_unlock(&dev_priv->rps.hw_lock);
5936
5937         intel_update_cdclk(dev);
5938 }
5939
5940 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5941 {
5942         /* disable DBUF power */
5943         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5944         POSTING_READ(DBUF_CTL);
5945
5946         udelay(10);
5947
5948         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5949                 DRM_ERROR("DBuf power disable timeout\n");
5950
5951         /* disable DPLL0 */
5952         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5953         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5954                 DRM_ERROR("Couldn't disable DPLL0\n");
5955 }
5956
5957 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5958 {
5959         unsigned int required_vco;
5960
5961         /* DPLL0 not enabled (happens on early BIOS versions) */
5962         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5963                 /* enable DPLL0 */
5964                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5965                 skl_dpll0_enable(dev_priv, required_vco);
5966         }
5967
5968         /* set CDCLK to the frequency the BIOS chose */
5969         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5970
5971         /* enable DBUF power */
5972         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5973         POSTING_READ(DBUF_CTL);
5974
5975         udelay(10);
5976
5977         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5978                 DRM_ERROR("DBuf power enable timeout\n");
5979 }
5980
5981 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5982 {
5983         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5984         uint32_t cdctl = I915_READ(CDCLK_CTL);
5985         int freq = dev_priv->skl_boot_cdclk;
5986
5987         /*
5988          * check if the pre-os intialized the display
5989          * There is SWF18 scratchpad register defined which is set by the
5990          * pre-os which can be used by the OS drivers to check the status
5991          */
5992         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5993                 goto sanitize;
5994
5995         /* Is PLL enabled and locked ? */
5996         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5997                 goto sanitize;
5998
5999         /* DPLL okay; verify the cdclock
6000          *
6001          * Noticed in some instances that the freq selection is correct but
6002          * decimal part is programmed wrong from BIOS where pre-os does not
6003          * enable display. Verify the same as well.
6004          */
6005         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
6006                 /* All well; nothing to sanitize */
6007                 return false;
6008 sanitize:
6009         /*
6010          * As of now initialize with max cdclk till
6011          * we get dynamic cdclk support
6012          * */
6013         dev_priv->skl_boot_cdclk = dev_priv->max_cdclk_freq;
6014         skl_init_cdclk(dev_priv);
6015
6016         /* we did have to sanitize */
6017         return true;
6018 }
6019
6020 /* Adjust CDclk dividers to allow high res or save power if possible */
6021 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
6022 {
6023         struct drm_i915_private *dev_priv = dev->dev_private;
6024         u32 val, cmd;
6025
6026         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6027                                         != dev_priv->cdclk_freq);
6028
6029         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
6030                 cmd = 2;
6031         else if (cdclk == 266667)
6032                 cmd = 1;
6033         else
6034                 cmd = 0;
6035
6036         mutex_lock(&dev_priv->rps.hw_lock);
6037         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6038         val &= ~DSPFREQGUAR_MASK;
6039         val |= (cmd << DSPFREQGUAR_SHIFT);
6040         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6041         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6042                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
6043                      50)) {
6044                 DRM_ERROR("timed out waiting for CDclk change\n");
6045         }
6046         mutex_unlock(&dev_priv->rps.hw_lock);
6047
6048         mutex_lock(&dev_priv->sb_lock);
6049
6050         if (cdclk == 400000) {
6051                 u32 divider;
6052
6053                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6054
6055                 /* adjust cdclk divider */
6056                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
6057                 val &= ~CCK_FREQUENCY_VALUES;
6058                 val |= divider;
6059                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
6060
6061                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
6062                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
6063                              50))
6064                         DRM_ERROR("timed out waiting for CDclk change\n");
6065         }
6066
6067         /* adjust self-refresh exit latency value */
6068         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
6069         val &= ~0x7f;
6070
6071         /*
6072          * For high bandwidth configs, we set a higher latency in the bunit
6073          * so that the core display fetch happens in time to avoid underruns.
6074          */
6075         if (cdclk == 400000)
6076                 val |= 4500 / 250; /* 4.5 usec */
6077         else
6078                 val |= 3000 / 250; /* 3.0 usec */
6079         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
6080
6081         mutex_unlock(&dev_priv->sb_lock);
6082
6083         intel_update_cdclk(dev);
6084 }
6085
6086 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
6087 {
6088         struct drm_i915_private *dev_priv = dev->dev_private;
6089         u32 val, cmd;
6090
6091         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
6092                                                 != dev_priv->cdclk_freq);
6093
6094         switch (cdclk) {
6095         case 333333:
6096         case 320000:
6097         case 266667:
6098         case 200000:
6099                 break;
6100         default:
6101                 MISSING_CASE(cdclk);
6102                 return;
6103         }
6104
6105         /*
6106          * Specs are full of misinformation, but testing on actual
6107          * hardware has shown that we just need to write the desired
6108          * CCK divider into the Punit register.
6109          */
6110         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
6111
6112         mutex_lock(&dev_priv->rps.hw_lock);
6113         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
6114         val &= ~DSPFREQGUAR_MASK_CHV;
6115         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
6116         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
6117         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
6118                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
6119                      50)) {
6120                 DRM_ERROR("timed out waiting for CDclk change\n");
6121         }
6122         mutex_unlock(&dev_priv->rps.hw_lock);
6123
6124         intel_update_cdclk(dev);
6125 }
6126
6127 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
6128                                  int max_pixclk)
6129 {
6130         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
6131         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
6132
6133         /*
6134          * Really only a few cases to deal with, as only 4 CDclks are supported:
6135          *   200MHz
6136          *   267MHz
6137          *   320/333MHz (depends on HPLL freq)
6138          *   400MHz (VLV only)
6139          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
6140          * of the lower bin and adjust if needed.
6141          *
6142          * We seem to get an unstable or solid color picture at 200MHz.
6143          * Not sure what's wrong. For now use 200MHz only when all pipes
6144          * are off.
6145          */
6146         if (!IS_CHERRYVIEW(dev_priv) &&
6147             max_pixclk > freq_320*limit/100)
6148                 return 400000;
6149         else if (max_pixclk > 266667*limit/100)
6150                 return freq_320;
6151         else if (max_pixclk > 0)
6152                 return 266667;
6153         else
6154                 return 200000;
6155 }
6156
6157 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
6158                               int max_pixclk)
6159 {
6160         /*
6161          * FIXME:
6162          * - remove the guardband, it's not needed on BXT
6163          * - set 19.2MHz bypass frequency if there are no active pipes
6164          */
6165         if (max_pixclk > 576000*9/10)
6166                 return 624000;
6167         else if (max_pixclk > 384000*9/10)
6168                 return 576000;
6169         else if (max_pixclk > 288000*9/10)
6170                 return 384000;
6171         else if (max_pixclk > 144000*9/10)
6172                 return 288000;
6173         else
6174                 return 144000;
6175 }
6176
6177 /* Compute the max pixel clock for new configuration. */
6178 static int intel_mode_max_pixclk(struct drm_device *dev,
6179                                  struct drm_atomic_state *state)
6180 {
6181         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
6182         struct drm_i915_private *dev_priv = dev->dev_private;
6183         struct drm_crtc *crtc;
6184         struct drm_crtc_state *crtc_state;
6185         unsigned max_pixclk = 0, i;
6186         enum pipe pipe;
6187
6188         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
6189                sizeof(intel_state->min_pixclk));
6190
6191         for_each_crtc_in_state(state, crtc, crtc_state, i) {
6192                 int pixclk = 0;
6193
6194                 if (crtc_state->enable)
6195                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6196
6197                 intel_state->min_pixclk[i] = pixclk;
6198         }
6199
6200         for_each_pipe(dev_priv, pipe)
6201                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6202
6203         return max_pixclk;
6204 }
6205
6206 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6207 {
6208         struct drm_device *dev = state->dev;
6209         struct drm_i915_private *dev_priv = dev->dev_private;
6210         int max_pixclk = intel_mode_max_pixclk(dev, state);
6211         struct intel_atomic_state *intel_state =
6212                 to_intel_atomic_state(state);
6213
6214         if (max_pixclk < 0)
6215                 return max_pixclk;
6216
6217         intel_state->cdclk = intel_state->dev_cdclk =
6218                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6219
6220         if (!intel_state->active_crtcs)
6221                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6222
6223         return 0;
6224 }
6225
6226 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
6227 {
6228         struct drm_device *dev = state->dev;
6229         struct drm_i915_private *dev_priv = dev->dev_private;
6230         int max_pixclk = intel_mode_max_pixclk(dev, state);
6231         struct intel_atomic_state *intel_state =
6232                 to_intel_atomic_state(state);
6233
6234         if (max_pixclk < 0)
6235                 return max_pixclk;
6236
6237         intel_state->cdclk = intel_state->dev_cdclk =
6238                 broxton_calc_cdclk(dev_priv, max_pixclk);
6239
6240         if (!intel_state->active_crtcs)
6241                 intel_state->dev_cdclk = broxton_calc_cdclk(dev_priv, 0);
6242
6243         return 0;
6244 }
6245
6246 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6247 {
6248         unsigned int credits, default_credits;
6249
6250         if (IS_CHERRYVIEW(dev_priv))
6251                 default_credits = PFI_CREDIT(12);
6252         else
6253                 default_credits = PFI_CREDIT(8);
6254
6255         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6256                 /* CHV suggested value is 31 or 63 */
6257                 if (IS_CHERRYVIEW(dev_priv))
6258                         credits = PFI_CREDIT_63;
6259                 else
6260                         credits = PFI_CREDIT(15);
6261         } else {
6262                 credits = default_credits;
6263         }
6264
6265         /*
6266          * WA - write default credits before re-programming
6267          * FIXME: should we also set the resend bit here?
6268          */
6269         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6270                    default_credits);
6271
6272         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6273                    credits | PFI_CREDIT_RESEND);
6274
6275         /*
6276          * FIXME is this guaranteed to clear
6277          * immediately or should we poll for it?
6278          */
6279         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6280 }
6281
6282 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6283 {
6284         struct drm_device *dev = old_state->dev;
6285         struct drm_i915_private *dev_priv = dev->dev_private;
6286         struct intel_atomic_state *old_intel_state =
6287                 to_intel_atomic_state(old_state);
6288         unsigned req_cdclk = old_intel_state->dev_cdclk;
6289
6290         /*
6291          * FIXME: We can end up here with all power domains off, yet
6292          * with a CDCLK frequency other than the minimum. To account
6293          * for this take the PIPE-A power domain, which covers the HW
6294          * blocks needed for the following programming. This can be
6295          * removed once it's guaranteed that we get here either with
6296          * the minimum CDCLK set, or the required power domains
6297          * enabled.
6298          */
6299         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6300
6301         if (IS_CHERRYVIEW(dev))
6302                 cherryview_set_cdclk(dev, req_cdclk);
6303         else
6304                 valleyview_set_cdclk(dev, req_cdclk);
6305
6306         vlv_program_pfi_credits(dev_priv);
6307
6308         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6309 }
6310
6311 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6312 {
6313         struct drm_device *dev = crtc->dev;
6314         struct drm_i915_private *dev_priv = to_i915(dev);
6315         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6316         struct intel_encoder *encoder;
6317         int pipe = intel_crtc->pipe;
6318
6319         if (WARN_ON(intel_crtc->active))
6320                 return;
6321
6322         if (intel_crtc->config->has_dp_encoder)
6323                 intel_dp_set_m_n(intel_crtc, M1_N1);
6324
6325         intel_set_pipe_timings(intel_crtc);
6326
6327         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6328                 struct drm_i915_private *dev_priv = dev->dev_private;
6329
6330                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6331                 I915_WRITE(CHV_CANVAS(pipe), 0);
6332         }
6333
6334         i9xx_set_pipeconf(intel_crtc);
6335
6336         intel_crtc->active = true;
6337
6338         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6339
6340         for_each_encoder_on_crtc(dev, crtc, encoder)
6341                 if (encoder->pre_pll_enable)
6342                         encoder->pre_pll_enable(encoder);
6343
6344         if (!intel_crtc->config->has_dsi_encoder) {
6345                 if (IS_CHERRYVIEW(dev)) {
6346                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6347                         chv_enable_pll(intel_crtc, intel_crtc->config);
6348                 } else {
6349                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6350                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6351                 }
6352         }
6353
6354         for_each_encoder_on_crtc(dev, crtc, encoder)
6355                 if (encoder->pre_enable)
6356                         encoder->pre_enable(encoder);
6357
6358         i9xx_pfit_enable(intel_crtc);
6359
6360         intel_crtc_load_lut(crtc);
6361
6362         intel_enable_pipe(intel_crtc);
6363
6364         assert_vblank_disabled(crtc);
6365         drm_crtc_vblank_on(crtc);
6366
6367         for_each_encoder_on_crtc(dev, crtc, encoder)
6368                 encoder->enable(encoder);
6369 }
6370
6371 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6372 {
6373         struct drm_device *dev = crtc->base.dev;
6374         struct drm_i915_private *dev_priv = dev->dev_private;
6375
6376         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6377         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6378 }
6379
6380 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6381 {
6382         struct drm_device *dev = crtc->dev;
6383         struct drm_i915_private *dev_priv = to_i915(dev);
6384         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6385         struct intel_encoder *encoder;
6386         int pipe = intel_crtc->pipe;
6387
6388         if (WARN_ON(intel_crtc->active))
6389                 return;
6390
6391         i9xx_set_pll_dividers(intel_crtc);
6392
6393         if (intel_crtc->config->has_dp_encoder)
6394                 intel_dp_set_m_n(intel_crtc, M1_N1);
6395
6396         intel_set_pipe_timings(intel_crtc);
6397
6398         i9xx_set_pipeconf(intel_crtc);
6399
6400         intel_crtc->active = true;
6401
6402         if (!IS_GEN2(dev))
6403                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6404
6405         for_each_encoder_on_crtc(dev, crtc, encoder)
6406                 if (encoder->pre_enable)
6407                         encoder->pre_enable(encoder);
6408
6409         i9xx_enable_pll(intel_crtc);
6410
6411         i9xx_pfit_enable(intel_crtc);
6412
6413         intel_crtc_load_lut(crtc);
6414
6415         intel_update_watermarks(crtc);
6416         intel_enable_pipe(intel_crtc);
6417
6418         assert_vblank_disabled(crtc);
6419         drm_crtc_vblank_on(crtc);
6420
6421         for_each_encoder_on_crtc(dev, crtc, encoder)
6422                 encoder->enable(encoder);
6423 }
6424
6425 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6426 {
6427         struct drm_device *dev = crtc->base.dev;
6428         struct drm_i915_private *dev_priv = dev->dev_private;
6429
6430         if (!crtc->config->gmch_pfit.control)
6431                 return;
6432
6433         assert_pipe_disabled(dev_priv, crtc->pipe);
6434
6435         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6436                          I915_READ(PFIT_CONTROL));
6437         I915_WRITE(PFIT_CONTROL, 0);
6438 }
6439
6440 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6441 {
6442         struct drm_device *dev = crtc->dev;
6443         struct drm_i915_private *dev_priv = dev->dev_private;
6444         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6445         struct intel_encoder *encoder;
6446         int pipe = intel_crtc->pipe;
6447
6448         /*
6449          * On gen2 planes are double buffered but the pipe isn't, so we must
6450          * wait for planes to fully turn off before disabling the pipe.
6451          * We also need to wait on all gmch platforms because of the
6452          * self-refresh mode constraint explained above.
6453          */
6454         intel_wait_for_vblank(dev, pipe);
6455
6456         for_each_encoder_on_crtc(dev, crtc, encoder)
6457                 encoder->disable(encoder);
6458
6459         drm_crtc_vblank_off(crtc);
6460         assert_vblank_disabled(crtc);
6461
6462         intel_disable_pipe(intel_crtc);
6463
6464         i9xx_pfit_disable(intel_crtc);
6465
6466         for_each_encoder_on_crtc(dev, crtc, encoder)
6467                 if (encoder->post_disable)
6468                         encoder->post_disable(encoder);
6469
6470         if (!intel_crtc->config->has_dsi_encoder) {
6471                 if (IS_CHERRYVIEW(dev))
6472                         chv_disable_pll(dev_priv, pipe);
6473                 else if (IS_VALLEYVIEW(dev))
6474                         vlv_disable_pll(dev_priv, pipe);
6475                 else
6476                         i9xx_disable_pll(intel_crtc);
6477         }
6478
6479         for_each_encoder_on_crtc(dev, crtc, encoder)
6480                 if (encoder->post_pll_disable)
6481                         encoder->post_pll_disable(encoder);
6482
6483         if (!IS_GEN2(dev))
6484                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6485 }
6486
6487 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6488 {
6489         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6490         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6491         enum intel_display_power_domain domain;
6492         unsigned long domains;
6493
6494         if (!intel_crtc->active)
6495                 return;
6496
6497         if (to_intel_plane_state(crtc->primary->state)->visible) {
6498                 WARN_ON(intel_crtc->unpin_work);
6499
6500                 intel_pre_disable_primary(crtc);
6501
6502                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6503                 to_intel_plane_state(crtc->primary->state)->visible = false;
6504         }
6505
6506         dev_priv->display.crtc_disable(crtc);
6507         intel_crtc->active = false;
6508         intel_fbc_disable(intel_crtc);
6509         intel_update_watermarks(crtc);
6510         intel_disable_shared_dpll(intel_crtc);
6511
6512         domains = intel_crtc->enabled_power_domains;
6513         for_each_power_domain(domain, domains)
6514                 intel_display_power_put(dev_priv, domain);
6515         intel_crtc->enabled_power_domains = 0;
6516
6517         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6518         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6519 }
6520
6521 /*
6522  * turn all crtc's off, but do not adjust state
6523  * This has to be paired with a call to intel_modeset_setup_hw_state.
6524  */
6525 int intel_display_suspend(struct drm_device *dev)
6526 {
6527         struct drm_i915_private *dev_priv = to_i915(dev);
6528         struct drm_atomic_state *state;
6529         int ret;
6530
6531         state = drm_atomic_helper_suspend(dev);
6532         ret = PTR_ERR_OR_ZERO(state);
6533         if (ret)
6534                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6535         else
6536                 dev_priv->modeset_restore_state = state;
6537         return ret;
6538 }
6539
6540 void intel_encoder_destroy(struct drm_encoder *encoder)
6541 {
6542         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6543
6544         drm_encoder_cleanup(encoder);
6545         kfree(intel_encoder);
6546 }
6547
6548 /* Cross check the actual hw state with our own modeset state tracking (and it's
6549  * internal consistency). */
6550 static void intel_connector_check_state(struct intel_connector *connector)
6551 {
6552         struct drm_crtc *crtc = connector->base.state->crtc;
6553
6554         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6555                       connector->base.base.id,
6556                       connector->base.name);
6557
6558         if (connector->get_hw_state(connector)) {
6559                 struct intel_encoder *encoder = connector->encoder;
6560                 struct drm_connector_state *conn_state = connector->base.state;
6561
6562                 I915_STATE_WARN(!crtc,
6563                          "connector enabled without attached crtc\n");
6564
6565                 if (!crtc)
6566                         return;
6567
6568                 I915_STATE_WARN(!crtc->state->active,
6569                       "connector is active, but attached crtc isn't\n");
6570
6571                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6572                         return;
6573
6574                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6575                         "atomic encoder doesn't match attached encoder\n");
6576
6577                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6578                         "attached encoder crtc differs from connector crtc\n");
6579         } else {
6580                 I915_STATE_WARN(crtc && crtc->state->active,
6581                         "attached crtc is active, but connector isn't\n");
6582                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6583                         "best encoder set without crtc!\n");
6584         }
6585 }
6586
6587 int intel_connector_init(struct intel_connector *connector)
6588 {
6589         drm_atomic_helper_connector_reset(&connector->base);
6590
6591         if (!connector->base.state)
6592                 return -ENOMEM;
6593
6594         return 0;
6595 }
6596
6597 struct intel_connector *intel_connector_alloc(void)
6598 {
6599         struct intel_connector *connector;
6600
6601         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6602         if (!connector)
6603                 return NULL;
6604
6605         if (intel_connector_init(connector) < 0) {
6606                 kfree(connector);
6607                 return NULL;
6608         }
6609
6610         return connector;
6611 }
6612
6613 /* Simple connector->get_hw_state implementation for encoders that support only
6614  * one connector and no cloning and hence the encoder state determines the state
6615  * of the connector. */
6616 bool intel_connector_get_hw_state(struct intel_connector *connector)
6617 {
6618         enum pipe pipe = 0;
6619         struct intel_encoder *encoder = connector->encoder;
6620
6621         return encoder->get_hw_state(encoder, &pipe);
6622 }
6623
6624 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6625 {
6626         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6627                 return crtc_state->fdi_lanes;
6628
6629         return 0;
6630 }
6631
6632 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6633                                      struct intel_crtc_state *pipe_config)
6634 {
6635         struct drm_atomic_state *state = pipe_config->base.state;
6636         struct intel_crtc *other_crtc;
6637         struct intel_crtc_state *other_crtc_state;
6638
6639         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6640                       pipe_name(pipe), pipe_config->fdi_lanes);
6641         if (pipe_config->fdi_lanes > 4) {
6642                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6643                               pipe_name(pipe), pipe_config->fdi_lanes);
6644                 return -EINVAL;
6645         }
6646
6647         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6648                 if (pipe_config->fdi_lanes > 2) {
6649                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6650                                       pipe_config->fdi_lanes);
6651                         return -EINVAL;
6652                 } else {
6653                         return 0;
6654                 }
6655         }
6656
6657         if (INTEL_INFO(dev)->num_pipes == 2)
6658                 return 0;
6659
6660         /* Ivybridge 3 pipe is really complicated */
6661         switch (pipe) {
6662         case PIPE_A:
6663                 return 0;
6664         case PIPE_B:
6665                 if (pipe_config->fdi_lanes <= 2)
6666                         return 0;
6667
6668                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6669                 other_crtc_state =
6670                         intel_atomic_get_crtc_state(state, other_crtc);
6671                 if (IS_ERR(other_crtc_state))
6672                         return PTR_ERR(other_crtc_state);
6673
6674                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6675                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6676                                       pipe_name(pipe), pipe_config->fdi_lanes);
6677                         return -EINVAL;
6678                 }
6679                 return 0;
6680         case PIPE_C:
6681                 if (pipe_config->fdi_lanes > 2) {
6682                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6683                                       pipe_name(pipe), pipe_config->fdi_lanes);
6684                         return -EINVAL;
6685                 }
6686
6687                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6688                 other_crtc_state =
6689                         intel_atomic_get_crtc_state(state, other_crtc);
6690                 if (IS_ERR(other_crtc_state))
6691                         return PTR_ERR(other_crtc_state);
6692
6693                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6694                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6695                         return -EINVAL;
6696                 }
6697                 return 0;
6698         default:
6699                 BUG();
6700         }
6701 }
6702
6703 #define RETRY 1
6704 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6705                                        struct intel_crtc_state *pipe_config)
6706 {
6707         struct drm_device *dev = intel_crtc->base.dev;
6708         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6709         int lane, link_bw, fdi_dotclock, ret;
6710         bool needs_recompute = false;
6711
6712 retry:
6713         /* FDI is a binary signal running at ~2.7GHz, encoding
6714          * each output octet as 10 bits. The actual frequency
6715          * is stored as a divider into a 100MHz clock, and the
6716          * mode pixel clock is stored in units of 1KHz.
6717          * Hence the bw of each lane in terms of the mode signal
6718          * is:
6719          */
6720         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6721
6722         fdi_dotclock = adjusted_mode->crtc_clock;
6723
6724         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6725                                            pipe_config->pipe_bpp);
6726
6727         pipe_config->fdi_lanes = lane;
6728
6729         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6730                                link_bw, &pipe_config->fdi_m_n);
6731
6732         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6733         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6734                 pipe_config->pipe_bpp -= 2*3;
6735                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6736                               pipe_config->pipe_bpp);
6737                 needs_recompute = true;
6738                 pipe_config->bw_constrained = true;
6739
6740                 goto retry;
6741         }
6742
6743         if (needs_recompute)
6744                 return RETRY;
6745
6746         return ret;
6747 }
6748
6749 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6750                                      struct intel_crtc_state *pipe_config)
6751 {
6752         if (pipe_config->pipe_bpp > 24)
6753                 return false;
6754
6755         /* HSW can handle pixel rate up to cdclk? */
6756         if (IS_HASWELL(dev_priv->dev))
6757                 return true;
6758
6759         /*
6760          * We compare against max which means we must take
6761          * the increased cdclk requirement into account when
6762          * calculating the new cdclk.
6763          *
6764          * Should measure whether using a lower cdclk w/o IPS
6765          */
6766         return ilk_pipe_pixel_rate(pipe_config) <=
6767                 dev_priv->max_cdclk_freq * 95 / 100;
6768 }
6769
6770 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6771                                    struct intel_crtc_state *pipe_config)
6772 {
6773         struct drm_device *dev = crtc->base.dev;
6774         struct drm_i915_private *dev_priv = dev->dev_private;
6775
6776         pipe_config->ips_enabled = i915.enable_ips &&
6777                 hsw_crtc_supports_ips(crtc) &&
6778                 pipe_config_supports_ips(dev_priv, pipe_config);
6779 }
6780
6781 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6782 {
6783         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6784
6785         /* GDG double wide on either pipe, otherwise pipe A only */
6786         return INTEL_INFO(dev_priv)->gen < 4 &&
6787                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6788 }
6789
6790 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6791                                      struct intel_crtc_state *pipe_config)
6792 {
6793         struct drm_device *dev = crtc->base.dev;
6794         struct drm_i915_private *dev_priv = dev->dev_private;
6795         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6796
6797         /* FIXME should check pixel clock limits on all platforms */
6798         if (INTEL_INFO(dev)->gen < 4) {
6799                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6800
6801                 /*
6802                  * Enable double wide mode when the dot clock
6803                  * is > 90% of the (display) core speed.
6804                  */
6805                 if (intel_crtc_supports_double_wide(crtc) &&
6806                     adjusted_mode->crtc_clock > clock_limit) {
6807                         clock_limit *= 2;
6808                         pipe_config->double_wide = true;
6809                 }
6810
6811                 if (adjusted_mode->crtc_clock > clock_limit) {
6812                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6813                                       adjusted_mode->crtc_clock, clock_limit,
6814                                       yesno(pipe_config->double_wide));
6815                         return -EINVAL;
6816                 }
6817         }
6818
6819         /*
6820          * Pipe horizontal size must be even in:
6821          * - DVO ganged mode
6822          * - LVDS dual channel mode
6823          * - Double wide pipe
6824          */
6825         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6826              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6827                 pipe_config->pipe_src_w &= ~1;
6828
6829         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6830          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6831          */
6832         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6833                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6834                 return -EINVAL;
6835
6836         if (HAS_IPS(dev))
6837                 hsw_compute_ips_config(crtc, pipe_config);
6838
6839         if (pipe_config->has_pch_encoder)
6840                 return ironlake_fdi_compute_config(crtc, pipe_config);
6841
6842         return 0;
6843 }
6844
6845 static int skylake_get_display_clock_speed(struct drm_device *dev)
6846 {
6847         struct drm_i915_private *dev_priv = to_i915(dev);
6848         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6849         uint32_t cdctl = I915_READ(CDCLK_CTL);
6850         uint32_t linkrate;
6851
6852         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6853                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6854
6855         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6856                 return 540000;
6857
6858         linkrate = (I915_READ(DPLL_CTRL1) &
6859                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6860
6861         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6862             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6863                 /* vco 8640 */
6864                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6865                 case CDCLK_FREQ_450_432:
6866                         return 432000;
6867                 case CDCLK_FREQ_337_308:
6868                         return 308570;
6869                 case CDCLK_FREQ_675_617:
6870                         return 617140;
6871                 default:
6872                         WARN(1, "Unknown cd freq selection\n");
6873                 }
6874         } else {
6875                 /* vco 8100 */
6876                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6877                 case CDCLK_FREQ_450_432:
6878                         return 450000;
6879                 case CDCLK_FREQ_337_308:
6880                         return 337500;
6881                 case CDCLK_FREQ_675_617:
6882                         return 675000;
6883                 default:
6884                         WARN(1, "Unknown cd freq selection\n");
6885                 }
6886         }
6887
6888         /* error case, do as if DPLL0 isn't enabled */
6889         return 24000;
6890 }
6891
6892 static int broxton_get_display_clock_speed(struct drm_device *dev)
6893 {
6894         struct drm_i915_private *dev_priv = to_i915(dev);
6895         uint32_t cdctl = I915_READ(CDCLK_CTL);
6896         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6897         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6898         int cdclk;
6899
6900         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6901                 return 19200;
6902
6903         cdclk = 19200 * pll_ratio / 2;
6904
6905         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6906         case BXT_CDCLK_CD2X_DIV_SEL_1:
6907                 return cdclk;  /* 576MHz or 624MHz */
6908         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6909                 return cdclk * 2 / 3; /* 384MHz */
6910         case BXT_CDCLK_CD2X_DIV_SEL_2:
6911                 return cdclk / 2; /* 288MHz */
6912         case BXT_CDCLK_CD2X_DIV_SEL_4:
6913                 return cdclk / 4; /* 144MHz */
6914         }
6915
6916         /* error case, do as if DE PLL isn't enabled */
6917         return 19200;
6918 }
6919
6920 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6921 {
6922         struct drm_i915_private *dev_priv = dev->dev_private;
6923         uint32_t lcpll = I915_READ(LCPLL_CTL);
6924         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6925
6926         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6927                 return 800000;
6928         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6929                 return 450000;
6930         else if (freq == LCPLL_CLK_FREQ_450)
6931                 return 450000;
6932         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6933                 return 540000;
6934         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6935                 return 337500;
6936         else
6937                 return 675000;
6938 }
6939
6940 static int haswell_get_display_clock_speed(struct drm_device *dev)
6941 {
6942         struct drm_i915_private *dev_priv = dev->dev_private;
6943         uint32_t lcpll = I915_READ(LCPLL_CTL);
6944         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6945
6946         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6947                 return 800000;
6948         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6949                 return 450000;
6950         else if (freq == LCPLL_CLK_FREQ_450)
6951                 return 450000;
6952         else if (IS_HSW_ULT(dev))
6953                 return 337500;
6954         else
6955                 return 540000;
6956 }
6957
6958 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6959 {
6960         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6961                                       CCK_DISPLAY_CLOCK_CONTROL);
6962 }
6963
6964 static int ilk_get_display_clock_speed(struct drm_device *dev)
6965 {
6966         return 450000;
6967 }
6968
6969 static int i945_get_display_clock_speed(struct drm_device *dev)
6970 {
6971         return 400000;
6972 }
6973
6974 static int i915_get_display_clock_speed(struct drm_device *dev)
6975 {
6976         return 333333;
6977 }
6978
6979 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6980 {
6981         return 200000;
6982 }
6983
6984 static int pnv_get_display_clock_speed(struct drm_device *dev)
6985 {
6986         u16 gcfgc = 0;
6987
6988         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6989
6990         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6991         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6992                 return 266667;
6993         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6994                 return 333333;
6995         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6996                 return 444444;
6997         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6998                 return 200000;
6999         default:
7000                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
7001         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
7002                 return 133333;
7003         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
7004                 return 166667;
7005         }
7006 }
7007
7008 static int i915gm_get_display_clock_speed(struct drm_device *dev)
7009 {
7010         u16 gcfgc = 0;
7011
7012         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
7013
7014         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
7015                 return 133333;
7016         else {
7017                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
7018                 case GC_DISPLAY_CLOCK_333_MHZ:
7019                         return 333333;
7020                 default:
7021                 case GC_DISPLAY_CLOCK_190_200_MHZ:
7022                         return 190000;
7023                 }
7024         }
7025 }
7026
7027 static int i865_get_display_clock_speed(struct drm_device *dev)
7028 {
7029         return 266667;
7030 }
7031
7032 static int i85x_get_display_clock_speed(struct drm_device *dev)
7033 {
7034         u16 hpllcc = 0;
7035
7036         /*
7037          * 852GM/852GMV only supports 133 MHz and the HPLLCC
7038          * encoding is different :(
7039          * FIXME is this the right way to detect 852GM/852GMV?
7040          */
7041         if (dev->pdev->revision == 0x1)
7042                 return 133333;
7043
7044         pci_bus_read_config_word(dev->pdev->bus,
7045                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
7046
7047         /* Assume that the hardware is in the high speed state.  This
7048          * should be the default.
7049          */
7050         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
7051         case GC_CLOCK_133_200:
7052         case GC_CLOCK_133_200_2:
7053         case GC_CLOCK_100_200:
7054                 return 200000;
7055         case GC_CLOCK_166_250:
7056                 return 250000;
7057         case GC_CLOCK_100_133:
7058                 return 133333;
7059         case GC_CLOCK_133_266:
7060         case GC_CLOCK_133_266_2:
7061         case GC_CLOCK_166_266:
7062                 return 266667;
7063         }
7064
7065         /* Shouldn't happen */
7066         return 0;
7067 }
7068
7069 static int i830_get_display_clock_speed(struct drm_device *dev)
7070 {
7071         return 133333;
7072 }
7073
7074 static unsigned int intel_hpll_vco(struct drm_device *dev)
7075 {
7076         struct drm_i915_private *dev_priv = dev->dev_private;
7077         static const unsigned int blb_vco[8] = {
7078                 [0] = 3200000,
7079                 [1] = 4000000,
7080                 [2] = 5333333,
7081                 [3] = 4800000,
7082                 [4] = 6400000,
7083         };
7084         static const unsigned int pnv_vco[8] = {
7085                 [0] = 3200000,
7086                 [1] = 4000000,
7087                 [2] = 5333333,
7088                 [3] = 4800000,
7089                 [4] = 2666667,
7090         };
7091         static const unsigned int cl_vco[8] = {
7092                 [0] = 3200000,
7093                 [1] = 4000000,
7094                 [2] = 5333333,
7095                 [3] = 6400000,
7096                 [4] = 3333333,
7097                 [5] = 3566667,
7098                 [6] = 4266667,
7099         };
7100         static const unsigned int elk_vco[8] = {
7101                 [0] = 3200000,
7102                 [1] = 4000000,
7103                 [2] = 5333333,
7104                 [3] = 4800000,
7105         };
7106         static const unsigned int ctg_vco[8] = {
7107                 [0] = 3200000,
7108                 [1] = 4000000,
7109                 [2] = 5333333,
7110                 [3] = 6400000,
7111                 [4] = 2666667,
7112                 [5] = 4266667,
7113         };
7114         const unsigned int *vco_table;
7115         unsigned int vco;
7116         uint8_t tmp = 0;
7117
7118         /* FIXME other chipsets? */
7119         if (IS_GM45(dev))
7120                 vco_table = ctg_vco;
7121         else if (IS_G4X(dev))
7122                 vco_table = elk_vco;
7123         else if (IS_CRESTLINE(dev))
7124                 vco_table = cl_vco;
7125         else if (IS_PINEVIEW(dev))
7126                 vco_table = pnv_vco;
7127         else if (IS_G33(dev))
7128                 vco_table = blb_vco;
7129         else
7130                 return 0;
7131
7132         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
7133
7134         vco = vco_table[tmp & 0x7];
7135         if (vco == 0)
7136                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
7137         else
7138                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
7139
7140         return vco;
7141 }
7142
7143 static int gm45_get_display_clock_speed(struct drm_device *dev)
7144 {
7145         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7146         uint16_t tmp = 0;
7147
7148         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7149
7150         cdclk_sel = (tmp >> 12) & 0x1;
7151
7152         switch (vco) {
7153         case 2666667:
7154         case 4000000:
7155         case 5333333:
7156                 return cdclk_sel ? 333333 : 222222;
7157         case 3200000:
7158                 return cdclk_sel ? 320000 : 228571;
7159         default:
7160                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
7161                 return 222222;
7162         }
7163 }
7164
7165 static int i965gm_get_display_clock_speed(struct drm_device *dev)
7166 {
7167         static const uint8_t div_3200[] = { 16, 10,  8 };
7168         static const uint8_t div_4000[] = { 20, 12, 10 };
7169         static const uint8_t div_5333[] = { 24, 16, 14 };
7170         const uint8_t *div_table;
7171         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7172         uint16_t tmp = 0;
7173
7174         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7175
7176         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
7177
7178         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7179                 goto fail;
7180
7181         switch (vco) {
7182         case 3200000:
7183                 div_table = div_3200;
7184                 break;
7185         case 4000000:
7186                 div_table = div_4000;
7187                 break;
7188         case 5333333:
7189                 div_table = div_5333;
7190                 break;
7191         default:
7192                 goto fail;
7193         }
7194
7195         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7196
7197 fail:
7198         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7199         return 200000;
7200 }
7201
7202 static int g33_get_display_clock_speed(struct drm_device *dev)
7203 {
7204         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7205         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7206         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7207         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7208         const uint8_t *div_table;
7209         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7210         uint16_t tmp = 0;
7211
7212         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7213
7214         cdclk_sel = (tmp >> 4) & 0x7;
7215
7216         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7217                 goto fail;
7218
7219         switch (vco) {
7220         case 3200000:
7221                 div_table = div_3200;
7222                 break;
7223         case 4000000:
7224                 div_table = div_4000;
7225                 break;
7226         case 4800000:
7227                 div_table = div_4800;
7228                 break;
7229         case 5333333:
7230                 div_table = div_5333;
7231                 break;
7232         default:
7233                 goto fail;
7234         }
7235
7236         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7237
7238 fail:
7239         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7240         return 190476;
7241 }
7242
7243 static void
7244 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7245 {
7246         while (*num > DATA_LINK_M_N_MASK ||
7247                *den > DATA_LINK_M_N_MASK) {
7248                 *num >>= 1;
7249                 *den >>= 1;
7250         }
7251 }
7252
7253 static void compute_m_n(unsigned int m, unsigned int n,
7254                         uint32_t *ret_m, uint32_t *ret_n)
7255 {
7256         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7257         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7258         intel_reduce_m_n_ratio(ret_m, ret_n);
7259 }
7260
7261 void
7262 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7263                        int pixel_clock, int link_clock,
7264                        struct intel_link_m_n *m_n)
7265 {
7266         m_n->tu = 64;
7267
7268         compute_m_n(bits_per_pixel * pixel_clock,
7269                     link_clock * nlanes * 8,
7270                     &m_n->gmch_m, &m_n->gmch_n);
7271
7272         compute_m_n(pixel_clock, link_clock,
7273                     &m_n->link_m, &m_n->link_n);
7274 }
7275
7276 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7277 {
7278         if (i915.panel_use_ssc >= 0)
7279                 return i915.panel_use_ssc != 0;
7280         return dev_priv->vbt.lvds_use_ssc
7281                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7282 }
7283
7284 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7285                            int num_connectors)
7286 {
7287         struct drm_device *dev = crtc_state->base.crtc->dev;
7288         struct drm_i915_private *dev_priv = dev->dev_private;
7289         int refclk;
7290
7291         WARN_ON(!crtc_state->base.state);
7292
7293         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev) || IS_BROXTON(dev)) {
7294                 refclk = 100000;
7295         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7296             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7297                 refclk = dev_priv->vbt.lvds_ssc_freq;
7298                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7299         } else if (!IS_GEN2(dev)) {
7300                 refclk = 96000;
7301         } else {
7302                 refclk = 48000;
7303         }
7304
7305         return refclk;
7306 }
7307
7308 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7309 {
7310         return (1 << dpll->n) << 16 | dpll->m2;
7311 }
7312
7313 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7314 {
7315         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7316 }
7317
7318 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7319                                      struct intel_crtc_state *crtc_state,
7320                                      intel_clock_t *reduced_clock)
7321 {
7322         struct drm_device *dev = crtc->base.dev;
7323         u32 fp, fp2 = 0;
7324
7325         if (IS_PINEVIEW(dev)) {
7326                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7327                 if (reduced_clock)
7328                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7329         } else {
7330                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7331                 if (reduced_clock)
7332                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7333         }
7334
7335         crtc_state->dpll_hw_state.fp0 = fp;
7336
7337         crtc->lowfreq_avail = false;
7338         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7339             reduced_clock) {
7340                 crtc_state->dpll_hw_state.fp1 = fp2;
7341                 crtc->lowfreq_avail = true;
7342         } else {
7343                 crtc_state->dpll_hw_state.fp1 = fp;
7344         }
7345 }
7346
7347 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7348                 pipe)
7349 {
7350         u32 reg_val;
7351
7352         /*
7353          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7354          * and set it to a reasonable value instead.
7355          */
7356         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7357         reg_val &= 0xffffff00;
7358         reg_val |= 0x00000030;
7359         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7360
7361         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7362         reg_val &= 0x8cffffff;
7363         reg_val = 0x8c000000;
7364         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7365
7366         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7367         reg_val &= 0xffffff00;
7368         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7369
7370         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7371         reg_val &= 0x00ffffff;
7372         reg_val |= 0xb0000000;
7373         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7374 }
7375
7376 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7377                                          struct intel_link_m_n *m_n)
7378 {
7379         struct drm_device *dev = crtc->base.dev;
7380         struct drm_i915_private *dev_priv = dev->dev_private;
7381         int pipe = crtc->pipe;
7382
7383         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7384         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7385         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7386         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7387 }
7388
7389 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7390                                          struct intel_link_m_n *m_n,
7391                                          struct intel_link_m_n *m2_n2)
7392 {
7393         struct drm_device *dev = crtc->base.dev;
7394         struct drm_i915_private *dev_priv = dev->dev_private;
7395         int pipe = crtc->pipe;
7396         enum transcoder transcoder = crtc->config->cpu_transcoder;
7397
7398         if (INTEL_INFO(dev)->gen >= 5) {
7399                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7400                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7401                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7402                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7403                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7404                  * for gen < 8) and if DRRS is supported (to make sure the
7405                  * registers are not unnecessarily accessed).
7406                  */
7407                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7408                         crtc->config->has_drrs) {
7409                         I915_WRITE(PIPE_DATA_M2(transcoder),
7410                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7411                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7412                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7413                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7414                 }
7415         } else {
7416                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7417                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7418                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7419                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7420         }
7421 }
7422
7423 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7424 {
7425         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7426
7427         if (m_n == M1_N1) {
7428                 dp_m_n = &crtc->config->dp_m_n;
7429                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7430         } else if (m_n == M2_N2) {
7431
7432                 /*
7433                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7434                  * needs to be programmed into M1_N1.
7435                  */
7436                 dp_m_n = &crtc->config->dp_m2_n2;
7437         } else {
7438                 DRM_ERROR("Unsupported divider value\n");
7439                 return;
7440         }
7441
7442         if (crtc->config->has_pch_encoder)
7443                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7444         else
7445                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7446 }
7447
7448 static void vlv_compute_dpll(struct intel_crtc *crtc,
7449                              struct intel_crtc_state *pipe_config)
7450 {
7451         u32 dpll, dpll_md;
7452
7453         /*
7454          * Enable DPIO clock input. We should never disable the reference
7455          * clock for pipe B, since VGA hotplug / manual detection depends
7456          * on it.
7457          */
7458         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7459                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7460         /* We should never disable this, set it here for state tracking */
7461         if (crtc->pipe == PIPE_B)
7462                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7463         dpll |= DPLL_VCO_ENABLE;
7464         pipe_config->dpll_hw_state.dpll = dpll;
7465
7466         dpll_md = (pipe_config->pixel_multiplier - 1)
7467                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7468         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7469 }
7470
7471 static void vlv_prepare_pll(struct intel_crtc *crtc,
7472                             const struct intel_crtc_state *pipe_config)
7473 {
7474         struct drm_device *dev = crtc->base.dev;
7475         struct drm_i915_private *dev_priv = dev->dev_private;
7476         int pipe = crtc->pipe;
7477         u32 mdiv;
7478         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7479         u32 coreclk, reg_val;
7480
7481         mutex_lock(&dev_priv->sb_lock);
7482
7483         bestn = pipe_config->dpll.n;
7484         bestm1 = pipe_config->dpll.m1;
7485         bestm2 = pipe_config->dpll.m2;
7486         bestp1 = pipe_config->dpll.p1;
7487         bestp2 = pipe_config->dpll.p2;
7488
7489         /* See eDP HDMI DPIO driver vbios notes doc */
7490
7491         /* PLL B needs special handling */
7492         if (pipe == PIPE_B)
7493                 vlv_pllb_recal_opamp(dev_priv, pipe);
7494
7495         /* Set up Tx target for periodic Rcomp update */
7496         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7497
7498         /* Disable target IRef on PLL */
7499         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7500         reg_val &= 0x00ffffff;
7501         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7502
7503         /* Disable fast lock */
7504         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7505
7506         /* Set idtafcrecal before PLL is enabled */
7507         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7508         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7509         mdiv |= ((bestn << DPIO_N_SHIFT));
7510         mdiv |= (1 << DPIO_K_SHIFT);
7511
7512         /*
7513          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7514          * but we don't support that).
7515          * Note: don't use the DAC post divider as it seems unstable.
7516          */
7517         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7518         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7519
7520         mdiv |= DPIO_ENABLE_CALIBRATION;
7521         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7522
7523         /* Set HBR and RBR LPF coefficients */
7524         if (pipe_config->port_clock == 162000 ||
7525             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7526             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7527                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7528                                  0x009f0003);
7529         else
7530                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7531                                  0x00d0000f);
7532
7533         if (pipe_config->has_dp_encoder) {
7534                 /* Use SSC source */
7535                 if (pipe == PIPE_A)
7536                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7537                                          0x0df40000);
7538                 else
7539                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7540                                          0x0df70000);
7541         } else { /* HDMI or VGA */
7542                 /* Use bend source */
7543                 if (pipe == PIPE_A)
7544                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7545                                          0x0df70000);
7546                 else
7547                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7548                                          0x0df40000);
7549         }
7550
7551         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7552         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7553         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7554             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7555                 coreclk |= 0x01000000;
7556         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7557
7558         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7559         mutex_unlock(&dev_priv->sb_lock);
7560 }
7561
7562 static void chv_compute_dpll(struct intel_crtc *crtc,
7563                              struct intel_crtc_state *pipe_config)
7564 {
7565         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7566                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7567                 DPLL_VCO_ENABLE;
7568         if (crtc->pipe != PIPE_A)
7569                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7570
7571         pipe_config->dpll_hw_state.dpll_md =
7572                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7573 }
7574
7575 static void chv_prepare_pll(struct intel_crtc *crtc,
7576                             const struct intel_crtc_state *pipe_config)
7577 {
7578         struct drm_device *dev = crtc->base.dev;
7579         struct drm_i915_private *dev_priv = dev->dev_private;
7580         int pipe = crtc->pipe;
7581         i915_reg_t dpll_reg = DPLL(crtc->pipe);
7582         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7583         u32 loopfilter, tribuf_calcntr;
7584         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7585         u32 dpio_val;
7586         int vco;
7587
7588         bestn = pipe_config->dpll.n;
7589         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7590         bestm1 = pipe_config->dpll.m1;
7591         bestm2 = pipe_config->dpll.m2 >> 22;
7592         bestp1 = pipe_config->dpll.p1;
7593         bestp2 = pipe_config->dpll.p2;
7594         vco = pipe_config->dpll.vco;
7595         dpio_val = 0;
7596         loopfilter = 0;
7597
7598         /*
7599          * Enable Refclk and SSC
7600          */
7601         I915_WRITE(dpll_reg,
7602                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7603
7604         mutex_lock(&dev_priv->sb_lock);
7605
7606         /* p1 and p2 divider */
7607         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7608                         5 << DPIO_CHV_S1_DIV_SHIFT |
7609                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7610                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7611                         1 << DPIO_CHV_K_DIV_SHIFT);
7612
7613         /* Feedback post-divider - m2 */
7614         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7615
7616         /* Feedback refclk divider - n and m1 */
7617         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7618                         DPIO_CHV_M1_DIV_BY_2 |
7619                         1 << DPIO_CHV_N_DIV_SHIFT);
7620
7621         /* M2 fraction division */
7622         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7623
7624         /* M2 fraction division enable */
7625         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7626         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7627         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7628         if (bestm2_frac)
7629                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7630         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7631
7632         /* Program digital lock detect threshold */
7633         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7634         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7635                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7636         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7637         if (!bestm2_frac)
7638                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7639         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7640
7641         /* Loop filter */
7642         if (vco == 5400000) {
7643                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7644                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7645                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7646                 tribuf_calcntr = 0x9;
7647         } else if (vco <= 6200000) {
7648                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7649                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7650                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7651                 tribuf_calcntr = 0x9;
7652         } else if (vco <= 6480000) {
7653                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7654                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7655                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7656                 tribuf_calcntr = 0x8;
7657         } else {
7658                 /* Not supported. Apply the same limits as in the max case */
7659                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7660                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7661                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7662                 tribuf_calcntr = 0;
7663         }
7664         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7665
7666         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7667         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7668         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7669         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7670
7671         /* AFC Recal */
7672         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7673                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7674                         DPIO_AFC_RECAL);
7675
7676         mutex_unlock(&dev_priv->sb_lock);
7677 }
7678
7679 /**
7680  * vlv_force_pll_on - forcibly enable just the PLL
7681  * @dev_priv: i915 private structure
7682  * @pipe: pipe PLL to enable
7683  * @dpll: PLL configuration
7684  *
7685  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7686  * in cases where we need the PLL enabled even when @pipe is not going to
7687  * be enabled.
7688  */
7689 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7690                      const struct dpll *dpll)
7691 {
7692         struct intel_crtc *crtc =
7693                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7694         struct intel_crtc_state *pipe_config;
7695
7696         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7697         if (!pipe_config)
7698                 return -ENOMEM;
7699
7700         pipe_config->base.crtc = &crtc->base;
7701         pipe_config->pixel_multiplier = 1;
7702         pipe_config->dpll = *dpll;
7703
7704         if (IS_CHERRYVIEW(dev)) {
7705                 chv_compute_dpll(crtc, pipe_config);
7706                 chv_prepare_pll(crtc, pipe_config);
7707                 chv_enable_pll(crtc, pipe_config);
7708         } else {
7709                 vlv_compute_dpll(crtc, pipe_config);
7710                 vlv_prepare_pll(crtc, pipe_config);
7711                 vlv_enable_pll(crtc, pipe_config);
7712         }
7713
7714         kfree(pipe_config);
7715
7716         return 0;
7717 }
7718
7719 /**
7720  * vlv_force_pll_off - forcibly disable just the PLL
7721  * @dev_priv: i915 private structure
7722  * @pipe: pipe PLL to disable
7723  *
7724  * Disable the PLL for @pipe. To be used in cases where we need
7725  * the PLL enabled even when @pipe is not going to be enabled.
7726  */
7727 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7728 {
7729         if (IS_CHERRYVIEW(dev))
7730                 chv_disable_pll(to_i915(dev), pipe);
7731         else
7732                 vlv_disable_pll(to_i915(dev), pipe);
7733 }
7734
7735 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7736                               struct intel_crtc_state *crtc_state,
7737                               intel_clock_t *reduced_clock,
7738                               int num_connectors)
7739 {
7740         struct drm_device *dev = crtc->base.dev;
7741         struct drm_i915_private *dev_priv = dev->dev_private;
7742         u32 dpll;
7743         bool is_sdvo;
7744         struct dpll *clock = &crtc_state->dpll;
7745
7746         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7747
7748         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7749                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7750
7751         dpll = DPLL_VGA_MODE_DIS;
7752
7753         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7754                 dpll |= DPLLB_MODE_LVDS;
7755         else
7756                 dpll |= DPLLB_MODE_DAC_SERIAL;
7757
7758         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7759                 dpll |= (crtc_state->pixel_multiplier - 1)
7760                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7761         }
7762
7763         if (is_sdvo)
7764                 dpll |= DPLL_SDVO_HIGH_SPEED;
7765
7766         if (crtc_state->has_dp_encoder)
7767                 dpll |= DPLL_SDVO_HIGH_SPEED;
7768
7769         /* compute bitmask from p1 value */
7770         if (IS_PINEVIEW(dev))
7771                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7772         else {
7773                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7774                 if (IS_G4X(dev) && reduced_clock)
7775                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7776         }
7777         switch (clock->p2) {
7778         case 5:
7779                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7780                 break;
7781         case 7:
7782                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7783                 break;
7784         case 10:
7785                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7786                 break;
7787         case 14:
7788                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7789                 break;
7790         }
7791         if (INTEL_INFO(dev)->gen >= 4)
7792                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7793
7794         if (crtc_state->sdvo_tv_clock)
7795                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7796         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7797                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7798                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7799         else
7800                 dpll |= PLL_REF_INPUT_DREFCLK;
7801
7802         dpll |= DPLL_VCO_ENABLE;
7803         crtc_state->dpll_hw_state.dpll = dpll;
7804
7805         if (INTEL_INFO(dev)->gen >= 4) {
7806                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7807                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7808                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7809         }
7810 }
7811
7812 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7813                               struct intel_crtc_state *crtc_state,
7814                               intel_clock_t *reduced_clock,
7815                               int num_connectors)
7816 {
7817         struct drm_device *dev = crtc->base.dev;
7818         struct drm_i915_private *dev_priv = dev->dev_private;
7819         u32 dpll;
7820         struct dpll *clock = &crtc_state->dpll;
7821
7822         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7823
7824         dpll = DPLL_VGA_MODE_DIS;
7825
7826         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7827                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7828         } else {
7829                 if (clock->p1 == 2)
7830                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7831                 else
7832                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7833                 if (clock->p2 == 4)
7834                         dpll |= PLL_P2_DIVIDE_BY_4;
7835         }
7836
7837         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7838                 dpll |= DPLL_DVO_2X_MODE;
7839
7840         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7841                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7842                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7843         else
7844                 dpll |= PLL_REF_INPUT_DREFCLK;
7845
7846         dpll |= DPLL_VCO_ENABLE;
7847         crtc_state->dpll_hw_state.dpll = dpll;
7848 }
7849
7850 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7851 {
7852         struct drm_device *dev = intel_crtc->base.dev;
7853         struct drm_i915_private *dev_priv = dev->dev_private;
7854         enum pipe pipe = intel_crtc->pipe;
7855         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7856         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7857         uint32_t crtc_vtotal, crtc_vblank_end;
7858         int vsyncshift = 0;
7859
7860         /* We need to be careful not to changed the adjusted mode, for otherwise
7861          * the hw state checker will get angry at the mismatch. */
7862         crtc_vtotal = adjusted_mode->crtc_vtotal;
7863         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7864
7865         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7866                 /* the chip adds 2 halflines automatically */
7867                 crtc_vtotal -= 1;
7868                 crtc_vblank_end -= 1;
7869
7870                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7871                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7872                 else
7873                         vsyncshift = adjusted_mode->crtc_hsync_start -
7874                                 adjusted_mode->crtc_htotal / 2;
7875                 if (vsyncshift < 0)
7876                         vsyncshift += adjusted_mode->crtc_htotal;
7877         }
7878
7879         if (INTEL_INFO(dev)->gen > 3)
7880                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7881
7882         I915_WRITE(HTOTAL(cpu_transcoder),
7883                    (adjusted_mode->crtc_hdisplay - 1) |
7884                    ((adjusted_mode->crtc_htotal - 1) << 16));
7885         I915_WRITE(HBLANK(cpu_transcoder),
7886                    (adjusted_mode->crtc_hblank_start - 1) |
7887                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7888         I915_WRITE(HSYNC(cpu_transcoder),
7889                    (adjusted_mode->crtc_hsync_start - 1) |
7890                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7891
7892         I915_WRITE(VTOTAL(cpu_transcoder),
7893                    (adjusted_mode->crtc_vdisplay - 1) |
7894                    ((crtc_vtotal - 1) << 16));
7895         I915_WRITE(VBLANK(cpu_transcoder),
7896                    (adjusted_mode->crtc_vblank_start - 1) |
7897                    ((crtc_vblank_end - 1) << 16));
7898         I915_WRITE(VSYNC(cpu_transcoder),
7899                    (adjusted_mode->crtc_vsync_start - 1) |
7900                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7901
7902         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7903          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7904          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7905          * bits. */
7906         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7907             (pipe == PIPE_B || pipe == PIPE_C))
7908                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7909
7910         /* pipesrc controls the size that is scaled from, which should
7911          * always be the user's requested size.
7912          */
7913         I915_WRITE(PIPESRC(pipe),
7914                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7915                    (intel_crtc->config->pipe_src_h - 1));
7916 }
7917
7918 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7919                                    struct intel_crtc_state *pipe_config)
7920 {
7921         struct drm_device *dev = crtc->base.dev;
7922         struct drm_i915_private *dev_priv = dev->dev_private;
7923         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7924         uint32_t tmp;
7925
7926         tmp = I915_READ(HTOTAL(cpu_transcoder));
7927         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7928         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7929         tmp = I915_READ(HBLANK(cpu_transcoder));
7930         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7931         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7932         tmp = I915_READ(HSYNC(cpu_transcoder));
7933         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7934         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7935
7936         tmp = I915_READ(VTOTAL(cpu_transcoder));
7937         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7938         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7939         tmp = I915_READ(VBLANK(cpu_transcoder));
7940         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7941         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7942         tmp = I915_READ(VSYNC(cpu_transcoder));
7943         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7944         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7945
7946         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7947                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7948                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7949                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7950         }
7951
7952         tmp = I915_READ(PIPESRC(crtc->pipe));
7953         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7954         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7955
7956         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7957         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7958 }
7959
7960 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7961                                  struct intel_crtc_state *pipe_config)
7962 {
7963         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7964         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7965         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7966         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7967
7968         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7969         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7970         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7971         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7972
7973         mode->flags = pipe_config->base.adjusted_mode.flags;
7974         mode->type = DRM_MODE_TYPE_DRIVER;
7975
7976         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7977         mode->flags |= pipe_config->base.adjusted_mode.flags;
7978
7979         mode->hsync = drm_mode_hsync(mode);
7980         mode->vrefresh = drm_mode_vrefresh(mode);
7981         drm_mode_set_name(mode);
7982 }
7983
7984 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7985 {
7986         struct drm_device *dev = intel_crtc->base.dev;
7987         struct drm_i915_private *dev_priv = dev->dev_private;
7988         uint32_t pipeconf;
7989
7990         pipeconf = 0;
7991
7992         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7993             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7994                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7995
7996         if (intel_crtc->config->double_wide)
7997                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7998
7999         /* only g4x and later have fancy bpc/dither controls */
8000         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8001                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
8002                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
8003                         pipeconf |= PIPECONF_DITHER_EN |
8004                                     PIPECONF_DITHER_TYPE_SP;
8005
8006                 switch (intel_crtc->config->pipe_bpp) {
8007                 case 18:
8008                         pipeconf |= PIPECONF_6BPC;
8009                         break;
8010                 case 24:
8011                         pipeconf |= PIPECONF_8BPC;
8012                         break;
8013                 case 30:
8014                         pipeconf |= PIPECONF_10BPC;
8015                         break;
8016                 default:
8017                         /* Case prevented by intel_choose_pipe_bpp_dither. */
8018                         BUG();
8019                 }
8020         }
8021
8022         if (HAS_PIPE_CXSR(dev)) {
8023                 if (intel_crtc->lowfreq_avail) {
8024                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
8025                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
8026                 } else {
8027                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
8028                 }
8029         }
8030
8031         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
8032                 if (INTEL_INFO(dev)->gen < 4 ||
8033                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
8034                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
8035                 else
8036                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
8037         } else
8038                 pipeconf |= PIPECONF_PROGRESSIVE;
8039
8040         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8041              intel_crtc->config->limited_color_range)
8042                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
8043
8044         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
8045         POSTING_READ(PIPECONF(intel_crtc->pipe));
8046 }
8047
8048 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
8049                                    struct intel_crtc_state *crtc_state)
8050 {
8051         struct drm_device *dev = crtc->base.dev;
8052         struct drm_i915_private *dev_priv = dev->dev_private;
8053         int refclk, num_connectors = 0;
8054         intel_clock_t clock;
8055         bool ok;
8056         const intel_limit_t *limit;
8057         struct drm_atomic_state *state = crtc_state->base.state;
8058         struct drm_connector *connector;
8059         struct drm_connector_state *connector_state;
8060         int i;
8061
8062         memset(&crtc_state->dpll_hw_state, 0,
8063                sizeof(crtc_state->dpll_hw_state));
8064
8065         if (crtc_state->has_dsi_encoder)
8066                 return 0;
8067
8068         for_each_connector_in_state(state, connector, connector_state, i) {
8069                 if (connector_state->crtc == &crtc->base)
8070                         num_connectors++;
8071         }
8072
8073         if (!crtc_state->clock_set) {
8074                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
8075
8076                 /*
8077                  * Returns a set of divisors for the desired target clock with
8078                  * the given refclk, or FALSE.  The returned values represent
8079                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
8080                  * 2) / p1 / p2.
8081                  */
8082                 limit = intel_limit(crtc_state, refclk);
8083                 ok = dev_priv->display.find_dpll(limit, crtc_state,
8084                                                  crtc_state->port_clock,
8085                                                  refclk, NULL, &clock);
8086                 if (!ok) {
8087                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
8088                         return -EINVAL;
8089                 }
8090
8091                 /* Compat-code for transition, will disappear. */
8092                 crtc_state->dpll.n = clock.n;
8093                 crtc_state->dpll.m1 = clock.m1;
8094                 crtc_state->dpll.m2 = clock.m2;
8095                 crtc_state->dpll.p1 = clock.p1;
8096                 crtc_state->dpll.p2 = clock.p2;
8097         }
8098
8099         if (IS_GEN2(dev)) {
8100                 i8xx_compute_dpll(crtc, crtc_state, NULL,
8101                                   num_connectors);
8102         } else if (IS_CHERRYVIEW(dev)) {
8103                 chv_compute_dpll(crtc, crtc_state);
8104         } else if (IS_VALLEYVIEW(dev)) {
8105                 vlv_compute_dpll(crtc, crtc_state);
8106         } else {
8107                 i9xx_compute_dpll(crtc, crtc_state, NULL,
8108                                   num_connectors);
8109         }
8110
8111         return 0;
8112 }
8113
8114 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
8115                                  struct intel_crtc_state *pipe_config)
8116 {
8117         struct drm_device *dev = crtc->base.dev;
8118         struct drm_i915_private *dev_priv = dev->dev_private;
8119         uint32_t tmp;
8120
8121         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
8122                 return;
8123
8124         tmp = I915_READ(PFIT_CONTROL);
8125         if (!(tmp & PFIT_ENABLE))
8126                 return;
8127
8128         /* Check whether the pfit is attached to our pipe. */
8129         if (INTEL_INFO(dev)->gen < 4) {
8130                 if (crtc->pipe != PIPE_B)
8131                         return;
8132         } else {
8133                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8134                         return;
8135         }
8136
8137         pipe_config->gmch_pfit.control = tmp;
8138         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8139         if (INTEL_INFO(dev)->gen < 5)
8140                 pipe_config->gmch_pfit.lvds_border_bits =
8141                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
8142 }
8143
8144 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8145                                struct intel_crtc_state *pipe_config)
8146 {
8147         struct drm_device *dev = crtc->base.dev;
8148         struct drm_i915_private *dev_priv = dev->dev_private;
8149         int pipe = pipe_config->cpu_transcoder;
8150         intel_clock_t clock;
8151         u32 mdiv;
8152         int refclk = 100000;
8153
8154         /* In case of MIPI DPLL will not even be used */
8155         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
8156                 return;
8157
8158         mutex_lock(&dev_priv->sb_lock);
8159         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8160         mutex_unlock(&dev_priv->sb_lock);
8161
8162         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8163         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8164         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8165         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8166         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8167
8168         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8169 }
8170
8171 static void
8172 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8173                               struct intel_initial_plane_config *plane_config)
8174 {
8175         struct drm_device *dev = crtc->base.dev;
8176         struct drm_i915_private *dev_priv = dev->dev_private;
8177         u32 val, base, offset;
8178         int pipe = crtc->pipe, plane = crtc->plane;
8179         int fourcc, pixel_format;
8180         unsigned int aligned_height;
8181         struct drm_framebuffer *fb;
8182         struct intel_framebuffer *intel_fb;
8183
8184         val = I915_READ(DSPCNTR(plane));
8185         if (!(val & DISPLAY_PLANE_ENABLE))
8186                 return;
8187
8188         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8189         if (!intel_fb) {
8190                 DRM_DEBUG_KMS("failed to alloc fb\n");
8191                 return;
8192         }
8193
8194         fb = &intel_fb->base;
8195
8196         if (INTEL_INFO(dev)->gen >= 4) {
8197                 if (val & DISPPLANE_TILED) {
8198                         plane_config->tiling = I915_TILING_X;
8199                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8200                 }
8201         }
8202
8203         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8204         fourcc = i9xx_format_to_fourcc(pixel_format);
8205         fb->pixel_format = fourcc;
8206         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8207
8208         if (INTEL_INFO(dev)->gen >= 4) {
8209                 if (plane_config->tiling)
8210                         offset = I915_READ(DSPTILEOFF(plane));
8211                 else
8212                         offset = I915_READ(DSPLINOFF(plane));
8213                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8214         } else {
8215                 base = I915_READ(DSPADDR(plane));
8216         }
8217         plane_config->base = base;
8218
8219         val = I915_READ(PIPESRC(pipe));
8220         fb->width = ((val >> 16) & 0xfff) + 1;
8221         fb->height = ((val >> 0) & 0xfff) + 1;
8222
8223         val = I915_READ(DSPSTRIDE(pipe));
8224         fb->pitches[0] = val & 0xffffffc0;
8225
8226         aligned_height = intel_fb_align_height(dev, fb->height,
8227                                                fb->pixel_format,
8228                                                fb->modifier[0]);
8229
8230         plane_config->size = fb->pitches[0] * aligned_height;
8231
8232         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8233                       pipe_name(pipe), plane, fb->width, fb->height,
8234                       fb->bits_per_pixel, base, fb->pitches[0],
8235                       plane_config->size);
8236
8237         plane_config->fb = intel_fb;
8238 }
8239
8240 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8241                                struct intel_crtc_state *pipe_config)
8242 {
8243         struct drm_device *dev = crtc->base.dev;
8244         struct drm_i915_private *dev_priv = dev->dev_private;
8245         int pipe = pipe_config->cpu_transcoder;
8246         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8247         intel_clock_t clock;
8248         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8249         int refclk = 100000;
8250
8251         mutex_lock(&dev_priv->sb_lock);
8252         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8253         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8254         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8255         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8256         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8257         mutex_unlock(&dev_priv->sb_lock);
8258
8259         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8260         clock.m2 = (pll_dw0 & 0xff) << 22;
8261         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8262                 clock.m2 |= pll_dw2 & 0x3fffff;
8263         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8264         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8265         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8266
8267         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8268 }
8269
8270 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8271                                  struct intel_crtc_state *pipe_config)
8272 {
8273         struct drm_device *dev = crtc->base.dev;
8274         struct drm_i915_private *dev_priv = dev->dev_private;
8275         enum intel_display_power_domain power_domain;
8276         uint32_t tmp;
8277         bool ret;
8278
8279         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8280         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8281                 return false;
8282
8283         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8284         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
8285
8286         ret = false;
8287
8288         tmp = I915_READ(PIPECONF(crtc->pipe));
8289         if (!(tmp & PIPECONF_ENABLE))
8290                 goto out;
8291
8292         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8293                 switch (tmp & PIPECONF_BPC_MASK) {
8294                 case PIPECONF_6BPC:
8295                         pipe_config->pipe_bpp = 18;
8296                         break;
8297                 case PIPECONF_8BPC:
8298                         pipe_config->pipe_bpp = 24;
8299                         break;
8300                 case PIPECONF_10BPC:
8301                         pipe_config->pipe_bpp = 30;
8302                         break;
8303                 default:
8304                         break;
8305                 }
8306         }
8307
8308         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8309             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8310                 pipe_config->limited_color_range = true;
8311
8312         if (INTEL_INFO(dev)->gen < 4)
8313                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8314
8315         intel_get_pipe_timings(crtc, pipe_config);
8316
8317         i9xx_get_pfit_config(crtc, pipe_config);
8318
8319         if (INTEL_INFO(dev)->gen >= 4) {
8320                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8321                 pipe_config->pixel_multiplier =
8322                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8323                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8324                 pipe_config->dpll_hw_state.dpll_md = tmp;
8325         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8326                 tmp = I915_READ(DPLL(crtc->pipe));
8327                 pipe_config->pixel_multiplier =
8328                         ((tmp & SDVO_MULTIPLIER_MASK)
8329                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8330         } else {
8331                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8332                  * port and will be fixed up in the encoder->get_config
8333                  * function. */
8334                 pipe_config->pixel_multiplier = 1;
8335         }
8336         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8337         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8338                 /*
8339                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8340                  * on 830. Filter it out here so that we don't
8341                  * report errors due to that.
8342                  */
8343                 if (IS_I830(dev))
8344                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8345
8346                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8347                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8348         } else {
8349                 /* Mask out read-only status bits. */
8350                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8351                                                      DPLL_PORTC_READY_MASK |
8352                                                      DPLL_PORTB_READY_MASK);
8353         }
8354
8355         if (IS_CHERRYVIEW(dev))
8356                 chv_crtc_clock_get(crtc, pipe_config);
8357         else if (IS_VALLEYVIEW(dev))
8358                 vlv_crtc_clock_get(crtc, pipe_config);
8359         else
8360                 i9xx_crtc_clock_get(crtc, pipe_config);
8361
8362         /*
8363          * Normally the dotclock is filled in by the encoder .get_config()
8364          * but in case the pipe is enabled w/o any ports we need a sane
8365          * default.
8366          */
8367         pipe_config->base.adjusted_mode.crtc_clock =
8368                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8369
8370         ret = true;
8371
8372 out:
8373         intel_display_power_put(dev_priv, power_domain);
8374
8375         return ret;
8376 }
8377
8378 static void ironlake_init_pch_refclk(struct drm_device *dev)
8379 {
8380         struct drm_i915_private *dev_priv = dev->dev_private;
8381         struct intel_encoder *encoder;
8382         u32 val, final;
8383         bool has_lvds = false;
8384         bool has_cpu_edp = false;
8385         bool has_panel = false;
8386         bool has_ck505 = false;
8387         bool can_ssc = false;
8388
8389         /* We need to take the global config into account */
8390         for_each_intel_encoder(dev, encoder) {
8391                 switch (encoder->type) {
8392                 case INTEL_OUTPUT_LVDS:
8393                         has_panel = true;
8394                         has_lvds = true;
8395                         break;
8396                 case INTEL_OUTPUT_EDP:
8397                         has_panel = true;
8398                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8399                                 has_cpu_edp = true;
8400                         break;
8401                 default:
8402                         break;
8403                 }
8404         }
8405
8406         if (HAS_PCH_IBX(dev)) {
8407                 has_ck505 = dev_priv->vbt.display_clock_mode;
8408                 can_ssc = has_ck505;
8409         } else {
8410                 has_ck505 = false;
8411                 can_ssc = true;
8412         }
8413
8414         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8415                       has_panel, has_lvds, has_ck505);
8416
8417         /* Ironlake: try to setup display ref clock before DPLL
8418          * enabling. This is only under driver's control after
8419          * PCH B stepping, previous chipset stepping should be
8420          * ignoring this setting.
8421          */
8422         val = I915_READ(PCH_DREF_CONTROL);
8423
8424         /* As we must carefully and slowly disable/enable each source in turn,
8425          * compute the final state we want first and check if we need to
8426          * make any changes at all.
8427          */
8428         final = val;
8429         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8430         if (has_ck505)
8431                 final |= DREF_NONSPREAD_CK505_ENABLE;
8432         else
8433                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8434
8435         final &= ~DREF_SSC_SOURCE_MASK;
8436         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8437         final &= ~DREF_SSC1_ENABLE;
8438
8439         if (has_panel) {
8440                 final |= DREF_SSC_SOURCE_ENABLE;
8441
8442                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8443                         final |= DREF_SSC1_ENABLE;
8444
8445                 if (has_cpu_edp) {
8446                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8447                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8448                         else
8449                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8450                 } else
8451                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8452         } else {
8453                 final |= DREF_SSC_SOURCE_DISABLE;
8454                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8455         }
8456
8457         if (final == val)
8458                 return;
8459
8460         /* Always enable nonspread source */
8461         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8462
8463         if (has_ck505)
8464                 val |= DREF_NONSPREAD_CK505_ENABLE;
8465         else
8466                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8467
8468         if (has_panel) {
8469                 val &= ~DREF_SSC_SOURCE_MASK;
8470                 val |= DREF_SSC_SOURCE_ENABLE;
8471
8472                 /* SSC must be turned on before enabling the CPU output  */
8473                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8474                         DRM_DEBUG_KMS("Using SSC on panel\n");
8475                         val |= DREF_SSC1_ENABLE;
8476                 } else
8477                         val &= ~DREF_SSC1_ENABLE;
8478
8479                 /* Get SSC going before enabling the outputs */
8480                 I915_WRITE(PCH_DREF_CONTROL, val);
8481                 POSTING_READ(PCH_DREF_CONTROL);
8482                 udelay(200);
8483
8484                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8485
8486                 /* Enable CPU source on CPU attached eDP */
8487                 if (has_cpu_edp) {
8488                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8489                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8490                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8491                         } else
8492                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8493                 } else
8494                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8495
8496                 I915_WRITE(PCH_DREF_CONTROL, val);
8497                 POSTING_READ(PCH_DREF_CONTROL);
8498                 udelay(200);
8499         } else {
8500                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8501
8502                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8503
8504                 /* Turn off CPU output */
8505                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8506
8507                 I915_WRITE(PCH_DREF_CONTROL, val);
8508                 POSTING_READ(PCH_DREF_CONTROL);
8509                 udelay(200);
8510
8511                 /* Turn off the SSC source */
8512                 val &= ~DREF_SSC_SOURCE_MASK;
8513                 val |= DREF_SSC_SOURCE_DISABLE;
8514
8515                 /* Turn off SSC1 */
8516                 val &= ~DREF_SSC1_ENABLE;
8517
8518                 I915_WRITE(PCH_DREF_CONTROL, val);
8519                 POSTING_READ(PCH_DREF_CONTROL);
8520                 udelay(200);
8521         }
8522
8523         BUG_ON(val != final);
8524 }
8525
8526 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8527 {
8528         uint32_t tmp;
8529
8530         tmp = I915_READ(SOUTH_CHICKEN2);
8531         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8532         I915_WRITE(SOUTH_CHICKEN2, tmp);
8533
8534         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8535                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8536                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8537
8538         tmp = I915_READ(SOUTH_CHICKEN2);
8539         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8540         I915_WRITE(SOUTH_CHICKEN2, tmp);
8541
8542         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8543                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8544                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8545 }
8546
8547 /* WaMPhyProgramming:hsw */
8548 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8549 {
8550         uint32_t tmp;
8551
8552         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8553         tmp &= ~(0xFF << 24);
8554         tmp |= (0x12 << 24);
8555         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8556
8557         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8558         tmp |= (1 << 11);
8559         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8560
8561         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8562         tmp |= (1 << 11);
8563         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8564
8565         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8566         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8567         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8568
8569         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8570         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8571         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8572
8573         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8574         tmp &= ~(7 << 13);
8575         tmp |= (5 << 13);
8576         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8577
8578         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8579         tmp &= ~(7 << 13);
8580         tmp |= (5 << 13);
8581         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8582
8583         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8584         tmp &= ~0xFF;
8585         tmp |= 0x1C;
8586         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8587
8588         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8589         tmp &= ~0xFF;
8590         tmp |= 0x1C;
8591         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8592
8593         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8594         tmp &= ~(0xFF << 16);
8595         tmp |= (0x1C << 16);
8596         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8597
8598         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8599         tmp &= ~(0xFF << 16);
8600         tmp |= (0x1C << 16);
8601         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8602
8603         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8604         tmp |= (1 << 27);
8605         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8606
8607         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8608         tmp |= (1 << 27);
8609         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8610
8611         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8612         tmp &= ~(0xF << 28);
8613         tmp |= (4 << 28);
8614         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8615
8616         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8617         tmp &= ~(0xF << 28);
8618         tmp |= (4 << 28);
8619         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8620 }
8621
8622 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8623  * Programming" based on the parameters passed:
8624  * - Sequence to enable CLKOUT_DP
8625  * - Sequence to enable CLKOUT_DP without spread
8626  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8627  */
8628 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8629                                  bool with_fdi)
8630 {
8631         struct drm_i915_private *dev_priv = dev->dev_private;
8632         uint32_t reg, tmp;
8633
8634         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8635                 with_spread = true;
8636         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8637                 with_fdi = false;
8638
8639         mutex_lock(&dev_priv->sb_lock);
8640
8641         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8642         tmp &= ~SBI_SSCCTL_DISABLE;
8643         tmp |= SBI_SSCCTL_PATHALT;
8644         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8645
8646         udelay(24);
8647
8648         if (with_spread) {
8649                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8650                 tmp &= ~SBI_SSCCTL_PATHALT;
8651                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8652
8653                 if (with_fdi) {
8654                         lpt_reset_fdi_mphy(dev_priv);
8655                         lpt_program_fdi_mphy(dev_priv);
8656                 }
8657         }
8658
8659         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8660         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8661         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8662         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8663
8664         mutex_unlock(&dev_priv->sb_lock);
8665 }
8666
8667 /* Sequence to disable CLKOUT_DP */
8668 static void lpt_disable_clkout_dp(struct drm_device *dev)
8669 {
8670         struct drm_i915_private *dev_priv = dev->dev_private;
8671         uint32_t reg, tmp;
8672
8673         mutex_lock(&dev_priv->sb_lock);
8674
8675         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8676         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8677         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8678         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8679
8680         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8681         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8682                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8683                         tmp |= SBI_SSCCTL_PATHALT;
8684                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8685                         udelay(32);
8686                 }
8687                 tmp |= SBI_SSCCTL_DISABLE;
8688                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8689         }
8690
8691         mutex_unlock(&dev_priv->sb_lock);
8692 }
8693
8694 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8695
8696 static const uint16_t sscdivintphase[] = {
8697         [BEND_IDX( 50)] = 0x3B23,
8698         [BEND_IDX( 45)] = 0x3B23,
8699         [BEND_IDX( 40)] = 0x3C23,
8700         [BEND_IDX( 35)] = 0x3C23,
8701         [BEND_IDX( 30)] = 0x3D23,
8702         [BEND_IDX( 25)] = 0x3D23,
8703         [BEND_IDX( 20)] = 0x3E23,
8704         [BEND_IDX( 15)] = 0x3E23,
8705         [BEND_IDX( 10)] = 0x3F23,
8706         [BEND_IDX(  5)] = 0x3F23,
8707         [BEND_IDX(  0)] = 0x0025,
8708         [BEND_IDX( -5)] = 0x0025,
8709         [BEND_IDX(-10)] = 0x0125,
8710         [BEND_IDX(-15)] = 0x0125,
8711         [BEND_IDX(-20)] = 0x0225,
8712         [BEND_IDX(-25)] = 0x0225,
8713         [BEND_IDX(-30)] = 0x0325,
8714         [BEND_IDX(-35)] = 0x0325,
8715         [BEND_IDX(-40)] = 0x0425,
8716         [BEND_IDX(-45)] = 0x0425,
8717         [BEND_IDX(-50)] = 0x0525,
8718 };
8719
8720 /*
8721  * Bend CLKOUT_DP
8722  * steps -50 to 50 inclusive, in steps of 5
8723  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8724  * change in clock period = -(steps / 10) * 5.787 ps
8725  */
8726 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8727 {
8728         uint32_t tmp;
8729         int idx = BEND_IDX(steps);
8730
8731         if (WARN_ON(steps % 5 != 0))
8732                 return;
8733
8734         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8735                 return;
8736
8737         mutex_lock(&dev_priv->sb_lock);
8738
8739         if (steps % 10 != 0)
8740                 tmp = 0xAAAAAAAB;
8741         else
8742                 tmp = 0x00000000;
8743         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8744
8745         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8746         tmp &= 0xffff0000;
8747         tmp |= sscdivintphase[idx];
8748         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8749
8750         mutex_unlock(&dev_priv->sb_lock);
8751 }
8752
8753 #undef BEND_IDX
8754
8755 static void lpt_init_pch_refclk(struct drm_device *dev)
8756 {
8757         struct intel_encoder *encoder;
8758         bool has_vga = false;
8759
8760         for_each_intel_encoder(dev, encoder) {
8761                 switch (encoder->type) {
8762                 case INTEL_OUTPUT_ANALOG:
8763                         has_vga = true;
8764                         break;
8765                 default:
8766                         break;
8767                 }
8768         }
8769
8770         if (has_vga) {
8771                 lpt_bend_clkout_dp(to_i915(dev), 0);
8772                 lpt_enable_clkout_dp(dev, true, true);
8773         } else {
8774                 lpt_disable_clkout_dp(dev);
8775         }
8776 }
8777
8778 /*
8779  * Initialize reference clocks when the driver loads
8780  */
8781 void intel_init_pch_refclk(struct drm_device *dev)
8782 {
8783         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8784                 ironlake_init_pch_refclk(dev);
8785         else if (HAS_PCH_LPT(dev))
8786                 lpt_init_pch_refclk(dev);
8787 }
8788
8789 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8790 {
8791         struct drm_device *dev = crtc_state->base.crtc->dev;
8792         struct drm_i915_private *dev_priv = dev->dev_private;
8793         struct drm_atomic_state *state = crtc_state->base.state;
8794         struct drm_connector *connector;
8795         struct drm_connector_state *connector_state;
8796         struct intel_encoder *encoder;
8797         int num_connectors = 0, i;
8798         bool is_lvds = false;
8799
8800         for_each_connector_in_state(state, connector, connector_state, i) {
8801                 if (connector_state->crtc != crtc_state->base.crtc)
8802                         continue;
8803
8804                 encoder = to_intel_encoder(connector_state->best_encoder);
8805
8806                 switch (encoder->type) {
8807                 case INTEL_OUTPUT_LVDS:
8808                         is_lvds = true;
8809                         break;
8810                 default:
8811                         break;
8812                 }
8813                 num_connectors++;
8814         }
8815
8816         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8817                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8818                               dev_priv->vbt.lvds_ssc_freq);
8819                 return dev_priv->vbt.lvds_ssc_freq;
8820         }
8821
8822         return 120000;
8823 }
8824
8825 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8826 {
8827         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8828         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8829         int pipe = intel_crtc->pipe;
8830         uint32_t val;
8831
8832         val = 0;
8833
8834         switch (intel_crtc->config->pipe_bpp) {
8835         case 18:
8836                 val |= PIPECONF_6BPC;
8837                 break;
8838         case 24:
8839                 val |= PIPECONF_8BPC;
8840                 break;
8841         case 30:
8842                 val |= PIPECONF_10BPC;
8843                 break;
8844         case 36:
8845                 val |= PIPECONF_12BPC;
8846                 break;
8847         default:
8848                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8849                 BUG();
8850         }
8851
8852         if (intel_crtc->config->dither)
8853                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8854
8855         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8856                 val |= PIPECONF_INTERLACED_ILK;
8857         else
8858                 val |= PIPECONF_PROGRESSIVE;
8859
8860         if (intel_crtc->config->limited_color_range)
8861                 val |= PIPECONF_COLOR_RANGE_SELECT;
8862
8863         I915_WRITE(PIPECONF(pipe), val);
8864         POSTING_READ(PIPECONF(pipe));
8865 }
8866
8867 /*
8868  * Set up the pipe CSC unit.
8869  *
8870  * Currently only full range RGB to limited range RGB conversion
8871  * is supported, but eventually this should handle various
8872  * RGB<->YCbCr scenarios as well.
8873  */
8874 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8875 {
8876         struct drm_device *dev = crtc->dev;
8877         struct drm_i915_private *dev_priv = dev->dev_private;
8878         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8879         int pipe = intel_crtc->pipe;
8880         uint16_t coeff = 0x7800; /* 1.0 */
8881
8882         /*
8883          * TODO: Check what kind of values actually come out of the pipe
8884          * with these coeff/postoff values and adjust to get the best
8885          * accuracy. Perhaps we even need to take the bpc value into
8886          * consideration.
8887          */
8888
8889         if (intel_crtc->config->limited_color_range)
8890                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8891
8892         /*
8893          * GY/GU and RY/RU should be the other way around according
8894          * to BSpec, but reality doesn't agree. Just set them up in
8895          * a way that results in the correct picture.
8896          */
8897         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8898         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8899
8900         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8901         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8902
8903         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8904         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8905
8906         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8907         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8908         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8909
8910         if (INTEL_INFO(dev)->gen > 6) {
8911                 uint16_t postoff = 0;
8912
8913                 if (intel_crtc->config->limited_color_range)
8914                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8915
8916                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8917                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8918                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8919
8920                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8921         } else {
8922                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8923
8924                 if (intel_crtc->config->limited_color_range)
8925                         mode |= CSC_BLACK_SCREEN_OFFSET;
8926
8927                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8928         }
8929 }
8930
8931 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8932 {
8933         struct drm_device *dev = crtc->dev;
8934         struct drm_i915_private *dev_priv = dev->dev_private;
8935         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8936         enum pipe pipe = intel_crtc->pipe;
8937         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8938         uint32_t val;
8939
8940         val = 0;
8941
8942         if (IS_HASWELL(dev) && intel_crtc->config->dither)
8943                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8944
8945         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8946                 val |= PIPECONF_INTERLACED_ILK;
8947         else
8948                 val |= PIPECONF_PROGRESSIVE;
8949
8950         I915_WRITE(PIPECONF(cpu_transcoder), val);
8951         POSTING_READ(PIPECONF(cpu_transcoder));
8952
8953         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8954         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8955
8956         if (IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) {
8957                 val = 0;
8958
8959                 switch (intel_crtc->config->pipe_bpp) {
8960                 case 18:
8961                         val |= PIPEMISC_DITHER_6_BPC;
8962                         break;
8963                 case 24:
8964                         val |= PIPEMISC_DITHER_8_BPC;
8965                         break;
8966                 case 30:
8967                         val |= PIPEMISC_DITHER_10_BPC;
8968                         break;
8969                 case 36:
8970                         val |= PIPEMISC_DITHER_12_BPC;
8971                         break;
8972                 default:
8973                         /* Case prevented by pipe_config_set_bpp. */
8974                         BUG();
8975                 }
8976
8977                 if (intel_crtc->config->dither)
8978                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8979
8980                 I915_WRITE(PIPEMISC(pipe), val);
8981         }
8982 }
8983
8984 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8985                                     struct intel_crtc_state *crtc_state,
8986                                     intel_clock_t *clock,
8987                                     bool *has_reduced_clock,
8988                                     intel_clock_t *reduced_clock)
8989 {
8990         struct drm_device *dev = crtc->dev;
8991         struct drm_i915_private *dev_priv = dev->dev_private;
8992         int refclk;
8993         const intel_limit_t *limit;
8994         bool ret;
8995
8996         refclk = ironlake_get_refclk(crtc_state);
8997
8998         /*
8999          * Returns a set of divisors for the desired target clock with the given
9000          * refclk, or FALSE.  The returned values represent the clock equation:
9001          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
9002          */
9003         limit = intel_limit(crtc_state, refclk);
9004         ret = dev_priv->display.find_dpll(limit, crtc_state,
9005                                           crtc_state->port_clock,
9006                                           refclk, NULL, clock);
9007         if (!ret)
9008                 return false;
9009
9010         return true;
9011 }
9012
9013 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
9014 {
9015         /*
9016          * Account for spread spectrum to avoid
9017          * oversubscribing the link. Max center spread
9018          * is 2.5%; use 5% for safety's sake.
9019          */
9020         u32 bps = target_clock * bpp * 21 / 20;
9021         return DIV_ROUND_UP(bps, link_bw * 8);
9022 }
9023
9024 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
9025 {
9026         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
9027 }
9028
9029 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
9030                                       struct intel_crtc_state *crtc_state,
9031                                       u32 *fp,
9032                                       intel_clock_t *reduced_clock, u32 *fp2)
9033 {
9034         struct drm_crtc *crtc = &intel_crtc->base;
9035         struct drm_device *dev = crtc->dev;
9036         struct drm_i915_private *dev_priv = dev->dev_private;
9037         struct drm_atomic_state *state = crtc_state->base.state;
9038         struct drm_connector *connector;
9039         struct drm_connector_state *connector_state;
9040         struct intel_encoder *encoder;
9041         uint32_t dpll;
9042         int factor, num_connectors = 0, i;
9043         bool is_lvds = false, is_sdvo = false;
9044
9045         for_each_connector_in_state(state, connector, connector_state, i) {
9046                 if (connector_state->crtc != crtc_state->base.crtc)
9047                         continue;
9048
9049                 encoder = to_intel_encoder(connector_state->best_encoder);
9050
9051                 switch (encoder->type) {
9052                 case INTEL_OUTPUT_LVDS:
9053                         is_lvds = true;
9054                         break;
9055                 case INTEL_OUTPUT_SDVO:
9056                 case INTEL_OUTPUT_HDMI:
9057                         is_sdvo = true;
9058                         break;
9059                 default:
9060                         break;
9061                 }
9062
9063                 num_connectors++;
9064         }
9065
9066         /* Enable autotuning of the PLL clock (if permissible) */
9067         factor = 21;
9068         if (is_lvds) {
9069                 if ((intel_panel_use_ssc(dev_priv) &&
9070                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
9071                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
9072                         factor = 25;
9073         } else if (crtc_state->sdvo_tv_clock)
9074                 factor = 20;
9075
9076         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
9077                 *fp |= FP_CB_TUNE;
9078
9079         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
9080                 *fp2 |= FP_CB_TUNE;
9081
9082         dpll = 0;
9083
9084         if (is_lvds)
9085                 dpll |= DPLLB_MODE_LVDS;
9086         else
9087                 dpll |= DPLLB_MODE_DAC_SERIAL;
9088
9089         dpll |= (crtc_state->pixel_multiplier - 1)
9090                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
9091
9092         if (is_sdvo)
9093                 dpll |= DPLL_SDVO_HIGH_SPEED;
9094         if (crtc_state->has_dp_encoder)
9095                 dpll |= DPLL_SDVO_HIGH_SPEED;
9096
9097         /* compute bitmask from p1 value */
9098         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
9099         /* also FPA1 */
9100         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
9101
9102         switch (crtc_state->dpll.p2) {
9103         case 5:
9104                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
9105                 break;
9106         case 7:
9107                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
9108                 break;
9109         case 10:
9110                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
9111                 break;
9112         case 14:
9113                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
9114                 break;
9115         }
9116
9117         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
9118                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
9119         else
9120                 dpll |= PLL_REF_INPUT_DREFCLK;
9121
9122         return dpll | DPLL_VCO_ENABLE;
9123 }
9124
9125 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
9126                                        struct intel_crtc_state *crtc_state)
9127 {
9128         struct drm_device *dev = crtc->base.dev;
9129         intel_clock_t clock, reduced_clock;
9130         u32 dpll = 0, fp = 0, fp2 = 0;
9131         bool ok, has_reduced_clock = false;
9132         bool is_lvds = false;
9133         struct intel_shared_dpll *pll;
9134
9135         memset(&crtc_state->dpll_hw_state, 0,
9136                sizeof(crtc_state->dpll_hw_state));
9137
9138         is_lvds = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS);
9139
9140         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
9141              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
9142
9143         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
9144                                      &has_reduced_clock, &reduced_clock);
9145         if (!ok && !crtc_state->clock_set) {
9146                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
9147                 return -EINVAL;
9148         }
9149         /* Compat-code for transition, will disappear. */
9150         if (!crtc_state->clock_set) {
9151                 crtc_state->dpll.n = clock.n;
9152                 crtc_state->dpll.m1 = clock.m1;
9153                 crtc_state->dpll.m2 = clock.m2;
9154                 crtc_state->dpll.p1 = clock.p1;
9155                 crtc_state->dpll.p2 = clock.p2;
9156         }
9157
9158         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9159         if (crtc_state->has_pch_encoder) {
9160                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9161                 if (has_reduced_clock)
9162                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
9163
9164                 dpll = ironlake_compute_dpll(crtc, crtc_state,
9165                                              &fp, &reduced_clock,
9166                                              has_reduced_clock ? &fp2 : NULL);
9167
9168                 crtc_state->dpll_hw_state.dpll = dpll;
9169                 crtc_state->dpll_hw_state.fp0 = fp;
9170                 if (has_reduced_clock)
9171                         crtc_state->dpll_hw_state.fp1 = fp2;
9172                 else
9173                         crtc_state->dpll_hw_state.fp1 = fp;
9174
9175                 pll = intel_get_shared_dpll(crtc, crtc_state);
9176                 if (pll == NULL) {
9177                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9178                                          pipe_name(crtc->pipe));
9179                         return -EINVAL;
9180                 }
9181         }
9182
9183         if (is_lvds && has_reduced_clock)
9184                 crtc->lowfreq_avail = true;
9185         else
9186                 crtc->lowfreq_avail = false;
9187
9188         return 0;
9189 }
9190
9191 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9192                                          struct intel_link_m_n *m_n)
9193 {
9194         struct drm_device *dev = crtc->base.dev;
9195         struct drm_i915_private *dev_priv = dev->dev_private;
9196         enum pipe pipe = crtc->pipe;
9197
9198         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9199         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9200         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9201                 & ~TU_SIZE_MASK;
9202         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9203         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9204                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9205 }
9206
9207 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9208                                          enum transcoder transcoder,
9209                                          struct intel_link_m_n *m_n,
9210                                          struct intel_link_m_n *m2_n2)
9211 {
9212         struct drm_device *dev = crtc->base.dev;
9213         struct drm_i915_private *dev_priv = dev->dev_private;
9214         enum pipe pipe = crtc->pipe;
9215
9216         if (INTEL_INFO(dev)->gen >= 5) {
9217                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9218                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9219                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9220                         & ~TU_SIZE_MASK;
9221                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9222                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9223                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9224                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9225                  * gen < 8) and if DRRS is supported (to make sure the
9226                  * registers are not unnecessarily read).
9227                  */
9228                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9229                         crtc->config->has_drrs) {
9230                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9231                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9232                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9233                                         & ~TU_SIZE_MASK;
9234                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9235                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9236                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9237                 }
9238         } else {
9239                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9240                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9241                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9242                         & ~TU_SIZE_MASK;
9243                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9244                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9245                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9246         }
9247 }
9248
9249 void intel_dp_get_m_n(struct intel_crtc *crtc,
9250                       struct intel_crtc_state *pipe_config)
9251 {
9252         if (pipe_config->has_pch_encoder)
9253                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9254         else
9255                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9256                                              &pipe_config->dp_m_n,
9257                                              &pipe_config->dp_m2_n2);
9258 }
9259
9260 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9261                                         struct intel_crtc_state *pipe_config)
9262 {
9263         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9264                                      &pipe_config->fdi_m_n, NULL);
9265 }
9266
9267 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9268                                     struct intel_crtc_state *pipe_config)
9269 {
9270         struct drm_device *dev = crtc->base.dev;
9271         struct drm_i915_private *dev_priv = dev->dev_private;
9272         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9273         uint32_t ps_ctrl = 0;
9274         int id = -1;
9275         int i;
9276
9277         /* find scaler attached to this pipe */
9278         for (i = 0; i < crtc->num_scalers; i++) {
9279                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9280                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9281                         id = i;
9282                         pipe_config->pch_pfit.enabled = true;
9283                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9284                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9285                         break;
9286                 }
9287         }
9288
9289         scaler_state->scaler_id = id;
9290         if (id >= 0) {
9291                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9292         } else {
9293                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9294         }
9295 }
9296
9297 static void
9298 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9299                                  struct intel_initial_plane_config *plane_config)
9300 {
9301         struct drm_device *dev = crtc->base.dev;
9302         struct drm_i915_private *dev_priv = dev->dev_private;
9303         u32 val, base, offset, stride_mult, tiling;
9304         int pipe = crtc->pipe;
9305         int fourcc, pixel_format;
9306         unsigned int aligned_height;
9307         struct drm_framebuffer *fb;
9308         struct intel_framebuffer *intel_fb;
9309
9310         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9311         if (!intel_fb) {
9312                 DRM_DEBUG_KMS("failed to alloc fb\n");
9313                 return;
9314         }
9315
9316         fb = &intel_fb->base;
9317
9318         val = I915_READ(PLANE_CTL(pipe, 0));
9319         if (!(val & PLANE_CTL_ENABLE))
9320                 goto error;
9321
9322         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9323         fourcc = skl_format_to_fourcc(pixel_format,
9324                                       val & PLANE_CTL_ORDER_RGBX,
9325                                       val & PLANE_CTL_ALPHA_MASK);
9326         fb->pixel_format = fourcc;
9327         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9328
9329         tiling = val & PLANE_CTL_TILED_MASK;
9330         switch (tiling) {
9331         case PLANE_CTL_TILED_LINEAR:
9332                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9333                 break;
9334         case PLANE_CTL_TILED_X:
9335                 plane_config->tiling = I915_TILING_X;
9336                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9337                 break;
9338         case PLANE_CTL_TILED_Y:
9339                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9340                 break;
9341         case PLANE_CTL_TILED_YF:
9342                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9343                 break;
9344         default:
9345                 MISSING_CASE(tiling);
9346                 goto error;
9347         }
9348
9349         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9350         plane_config->base = base;
9351
9352         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9353
9354         val = I915_READ(PLANE_SIZE(pipe, 0));
9355         fb->height = ((val >> 16) & 0xfff) + 1;
9356         fb->width = ((val >> 0) & 0x1fff) + 1;
9357
9358         val = I915_READ(PLANE_STRIDE(pipe, 0));
9359         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9360                                                 fb->pixel_format);
9361         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9362
9363         aligned_height = intel_fb_align_height(dev, fb->height,
9364                                                fb->pixel_format,
9365                                                fb->modifier[0]);
9366
9367         plane_config->size = fb->pitches[0] * aligned_height;
9368
9369         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9370                       pipe_name(pipe), fb->width, fb->height,
9371                       fb->bits_per_pixel, base, fb->pitches[0],
9372                       plane_config->size);
9373
9374         plane_config->fb = intel_fb;
9375         return;
9376
9377 error:
9378         kfree(fb);
9379 }
9380
9381 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9382                                      struct intel_crtc_state *pipe_config)
9383 {
9384         struct drm_device *dev = crtc->base.dev;
9385         struct drm_i915_private *dev_priv = dev->dev_private;
9386         uint32_t tmp;
9387
9388         tmp = I915_READ(PF_CTL(crtc->pipe));
9389
9390         if (tmp & PF_ENABLE) {
9391                 pipe_config->pch_pfit.enabled = true;
9392                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9393                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9394
9395                 /* We currently do not free assignements of panel fitters on
9396                  * ivb/hsw (since we don't use the higher upscaling modes which
9397                  * differentiates them) so just WARN about this case for now. */
9398                 if (IS_GEN7(dev)) {
9399                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9400                                 PF_PIPE_SEL_IVB(crtc->pipe));
9401                 }
9402         }
9403 }
9404
9405 static void
9406 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9407                                   struct intel_initial_plane_config *plane_config)
9408 {
9409         struct drm_device *dev = crtc->base.dev;
9410         struct drm_i915_private *dev_priv = dev->dev_private;
9411         u32 val, base, offset;
9412         int pipe = crtc->pipe;
9413         int fourcc, pixel_format;
9414         unsigned int aligned_height;
9415         struct drm_framebuffer *fb;
9416         struct intel_framebuffer *intel_fb;
9417
9418         val = I915_READ(DSPCNTR(pipe));
9419         if (!(val & DISPLAY_PLANE_ENABLE))
9420                 return;
9421
9422         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9423         if (!intel_fb) {
9424                 DRM_DEBUG_KMS("failed to alloc fb\n");
9425                 return;
9426         }
9427
9428         fb = &intel_fb->base;
9429
9430         if (INTEL_INFO(dev)->gen >= 4) {
9431                 if (val & DISPPLANE_TILED) {
9432                         plane_config->tiling = I915_TILING_X;
9433                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9434                 }
9435         }
9436
9437         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9438         fourcc = i9xx_format_to_fourcc(pixel_format);
9439         fb->pixel_format = fourcc;
9440         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9441
9442         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9443         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9444                 offset = I915_READ(DSPOFFSET(pipe));
9445         } else {
9446                 if (plane_config->tiling)
9447                         offset = I915_READ(DSPTILEOFF(pipe));
9448                 else
9449                         offset = I915_READ(DSPLINOFF(pipe));
9450         }
9451         plane_config->base = base;
9452
9453         val = I915_READ(PIPESRC(pipe));
9454         fb->width = ((val >> 16) & 0xfff) + 1;
9455         fb->height = ((val >> 0) & 0xfff) + 1;
9456
9457         val = I915_READ(DSPSTRIDE(pipe));
9458         fb->pitches[0] = val & 0xffffffc0;
9459
9460         aligned_height = intel_fb_align_height(dev, fb->height,
9461                                                fb->pixel_format,
9462                                                fb->modifier[0]);
9463
9464         plane_config->size = fb->pitches[0] * aligned_height;
9465
9466         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9467                       pipe_name(pipe), fb->width, fb->height,
9468                       fb->bits_per_pixel, base, fb->pitches[0],
9469                       plane_config->size);
9470
9471         plane_config->fb = intel_fb;
9472 }
9473
9474 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9475                                      struct intel_crtc_state *pipe_config)
9476 {
9477         struct drm_device *dev = crtc->base.dev;
9478         struct drm_i915_private *dev_priv = dev->dev_private;
9479         enum intel_display_power_domain power_domain;
9480         uint32_t tmp;
9481         bool ret;
9482
9483         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9484         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9485                 return false;
9486
9487         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9488         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
9489
9490         ret = false;
9491         tmp = I915_READ(PIPECONF(crtc->pipe));
9492         if (!(tmp & PIPECONF_ENABLE))
9493                 goto out;
9494
9495         switch (tmp & PIPECONF_BPC_MASK) {
9496         case PIPECONF_6BPC:
9497                 pipe_config->pipe_bpp = 18;
9498                 break;
9499         case PIPECONF_8BPC:
9500                 pipe_config->pipe_bpp = 24;
9501                 break;
9502         case PIPECONF_10BPC:
9503                 pipe_config->pipe_bpp = 30;
9504                 break;
9505         case PIPECONF_12BPC:
9506                 pipe_config->pipe_bpp = 36;
9507                 break;
9508         default:
9509                 break;
9510         }
9511
9512         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9513                 pipe_config->limited_color_range = true;
9514
9515         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9516                 struct intel_shared_dpll *pll;
9517
9518                 pipe_config->has_pch_encoder = true;
9519
9520                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9521                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9522                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9523
9524                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9525
9526                 if (HAS_PCH_IBX(dev_priv->dev)) {
9527                         pipe_config->shared_dpll =
9528                                 (enum intel_dpll_id) crtc->pipe;
9529                 } else {
9530                         tmp = I915_READ(PCH_DPLL_SEL);
9531                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9532                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_B;
9533                         else
9534                                 pipe_config->shared_dpll = DPLL_ID_PCH_PLL_A;
9535                 }
9536
9537                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
9538
9539                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
9540                                            &pipe_config->dpll_hw_state));
9541
9542                 tmp = pipe_config->dpll_hw_state.dpll;
9543                 pipe_config->pixel_multiplier =
9544                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9545                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9546
9547                 ironlake_pch_clock_get(crtc, pipe_config);
9548         } else {
9549                 pipe_config->pixel_multiplier = 1;
9550         }
9551
9552         intel_get_pipe_timings(crtc, pipe_config);
9553
9554         ironlake_get_pfit_config(crtc, pipe_config);
9555
9556         ret = true;
9557
9558 out:
9559         intel_display_power_put(dev_priv, power_domain);
9560
9561         return ret;
9562 }
9563
9564 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9565 {
9566         struct drm_device *dev = dev_priv->dev;
9567         struct intel_crtc *crtc;
9568
9569         for_each_intel_crtc(dev, crtc)
9570                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9571                      pipe_name(crtc->pipe));
9572
9573         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9574         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9575         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9576         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9577         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9578         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9579              "CPU PWM1 enabled\n");
9580         if (IS_HASWELL(dev))
9581                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9582                      "CPU PWM2 enabled\n");
9583         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9584              "PCH PWM1 enabled\n");
9585         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9586              "Utility pin enabled\n");
9587         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9588
9589         /*
9590          * In theory we can still leave IRQs enabled, as long as only the HPD
9591          * interrupts remain enabled. We used to check for that, but since it's
9592          * gen-specific and since we only disable LCPLL after we fully disable
9593          * the interrupts, the check below should be enough.
9594          */
9595         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9596 }
9597
9598 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9599 {
9600         struct drm_device *dev = dev_priv->dev;
9601
9602         if (IS_HASWELL(dev))
9603                 return I915_READ(D_COMP_HSW);
9604         else
9605                 return I915_READ(D_COMP_BDW);
9606 }
9607
9608 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9609 {
9610         struct drm_device *dev = dev_priv->dev;
9611
9612         if (IS_HASWELL(dev)) {
9613                 mutex_lock(&dev_priv->rps.hw_lock);
9614                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9615                                             val))
9616                         DRM_ERROR("Failed to write to D_COMP\n");
9617                 mutex_unlock(&dev_priv->rps.hw_lock);
9618         } else {
9619                 I915_WRITE(D_COMP_BDW, val);
9620                 POSTING_READ(D_COMP_BDW);
9621         }
9622 }
9623
9624 /*
9625  * This function implements pieces of two sequences from BSpec:
9626  * - Sequence for display software to disable LCPLL
9627  * - Sequence for display software to allow package C8+
9628  * The steps implemented here are just the steps that actually touch the LCPLL
9629  * register. Callers should take care of disabling all the display engine
9630  * functions, doing the mode unset, fixing interrupts, etc.
9631  */
9632 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9633                               bool switch_to_fclk, bool allow_power_down)
9634 {
9635         uint32_t val;
9636
9637         assert_can_disable_lcpll(dev_priv);
9638
9639         val = I915_READ(LCPLL_CTL);
9640
9641         if (switch_to_fclk) {
9642                 val |= LCPLL_CD_SOURCE_FCLK;
9643                 I915_WRITE(LCPLL_CTL, val);
9644
9645                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9646                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9647                         DRM_ERROR("Switching to FCLK failed\n");
9648
9649                 val = I915_READ(LCPLL_CTL);
9650         }
9651
9652         val |= LCPLL_PLL_DISABLE;
9653         I915_WRITE(LCPLL_CTL, val);
9654         POSTING_READ(LCPLL_CTL);
9655
9656         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9657                 DRM_ERROR("LCPLL still locked\n");
9658
9659         val = hsw_read_dcomp(dev_priv);
9660         val |= D_COMP_COMP_DISABLE;
9661         hsw_write_dcomp(dev_priv, val);
9662         ndelay(100);
9663
9664         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9665                      1))
9666                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9667
9668         if (allow_power_down) {
9669                 val = I915_READ(LCPLL_CTL);
9670                 val |= LCPLL_POWER_DOWN_ALLOW;
9671                 I915_WRITE(LCPLL_CTL, val);
9672                 POSTING_READ(LCPLL_CTL);
9673         }
9674 }
9675
9676 /*
9677  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9678  * source.
9679  */
9680 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9681 {
9682         uint32_t val;
9683
9684         val = I915_READ(LCPLL_CTL);
9685
9686         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9687                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9688                 return;
9689
9690         /*
9691          * Make sure we're not on PC8 state before disabling PC8, otherwise
9692          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9693          */
9694         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9695
9696         if (val & LCPLL_POWER_DOWN_ALLOW) {
9697                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9698                 I915_WRITE(LCPLL_CTL, val);
9699                 POSTING_READ(LCPLL_CTL);
9700         }
9701
9702         val = hsw_read_dcomp(dev_priv);
9703         val |= D_COMP_COMP_FORCE;
9704         val &= ~D_COMP_COMP_DISABLE;
9705         hsw_write_dcomp(dev_priv, val);
9706
9707         val = I915_READ(LCPLL_CTL);
9708         val &= ~LCPLL_PLL_DISABLE;
9709         I915_WRITE(LCPLL_CTL, val);
9710
9711         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9712                 DRM_ERROR("LCPLL not locked yet\n");
9713
9714         if (val & LCPLL_CD_SOURCE_FCLK) {
9715                 val = I915_READ(LCPLL_CTL);
9716                 val &= ~LCPLL_CD_SOURCE_FCLK;
9717                 I915_WRITE(LCPLL_CTL, val);
9718
9719                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9720                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9721                         DRM_ERROR("Switching back to LCPLL failed\n");
9722         }
9723
9724         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9725         intel_update_cdclk(dev_priv->dev);
9726 }
9727
9728 /*
9729  * Package states C8 and deeper are really deep PC states that can only be
9730  * reached when all the devices on the system allow it, so even if the graphics
9731  * device allows PC8+, it doesn't mean the system will actually get to these
9732  * states. Our driver only allows PC8+ when going into runtime PM.
9733  *
9734  * The requirements for PC8+ are that all the outputs are disabled, the power
9735  * well is disabled and most interrupts are disabled, and these are also
9736  * requirements for runtime PM. When these conditions are met, we manually do
9737  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9738  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9739  * hang the machine.
9740  *
9741  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9742  * the state of some registers, so when we come back from PC8+ we need to
9743  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9744  * need to take care of the registers kept by RC6. Notice that this happens even
9745  * if we don't put the device in PCI D3 state (which is what currently happens
9746  * because of the runtime PM support).
9747  *
9748  * For more, read "Display Sequences for Package C8" on the hardware
9749  * documentation.
9750  */
9751 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9752 {
9753         struct drm_device *dev = dev_priv->dev;
9754         uint32_t val;
9755
9756         DRM_DEBUG_KMS("Enabling package C8+\n");
9757
9758         if (HAS_PCH_LPT_LP(dev)) {
9759                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9760                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9761                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9762         }
9763
9764         lpt_disable_clkout_dp(dev);
9765         hsw_disable_lcpll(dev_priv, true, true);
9766 }
9767
9768 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9769 {
9770         struct drm_device *dev = dev_priv->dev;
9771         uint32_t val;
9772
9773         DRM_DEBUG_KMS("Disabling package C8+\n");
9774
9775         hsw_restore_lcpll(dev_priv);
9776         lpt_init_pch_refclk(dev);
9777
9778         if (HAS_PCH_LPT_LP(dev)) {
9779                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9780                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9781                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9782         }
9783 }
9784
9785 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9786 {
9787         struct drm_device *dev = old_state->dev;
9788         struct intel_atomic_state *old_intel_state =
9789                 to_intel_atomic_state(old_state);
9790         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9791
9792         broxton_set_cdclk(dev, req_cdclk);
9793 }
9794
9795 /* compute the max rate for new configuration */
9796 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9797 {
9798         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9799         struct drm_i915_private *dev_priv = state->dev->dev_private;
9800         struct drm_crtc *crtc;
9801         struct drm_crtc_state *cstate;
9802         struct intel_crtc_state *crtc_state;
9803         unsigned max_pixel_rate = 0, i;
9804         enum pipe pipe;
9805
9806         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9807                sizeof(intel_state->min_pixclk));
9808
9809         for_each_crtc_in_state(state, crtc, cstate, i) {
9810                 int pixel_rate;
9811
9812                 crtc_state = to_intel_crtc_state(cstate);
9813                 if (!crtc_state->base.enable) {
9814                         intel_state->min_pixclk[i] = 0;
9815                         continue;
9816                 }
9817
9818                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9819
9820                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9821                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9822                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9823
9824                 intel_state->min_pixclk[i] = pixel_rate;
9825         }
9826
9827         for_each_pipe(dev_priv, pipe)
9828                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9829
9830         return max_pixel_rate;
9831 }
9832
9833 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9834 {
9835         struct drm_i915_private *dev_priv = dev->dev_private;
9836         uint32_t val, data;
9837         int ret;
9838
9839         if (WARN((I915_READ(LCPLL_CTL) &
9840                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9841                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9842                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9843                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9844                  "trying to change cdclk frequency with cdclk not enabled\n"))
9845                 return;
9846
9847         mutex_lock(&dev_priv->rps.hw_lock);
9848         ret = sandybridge_pcode_write(dev_priv,
9849                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9850         mutex_unlock(&dev_priv->rps.hw_lock);
9851         if (ret) {
9852                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9853                 return;
9854         }
9855
9856         val = I915_READ(LCPLL_CTL);
9857         val |= LCPLL_CD_SOURCE_FCLK;
9858         I915_WRITE(LCPLL_CTL, val);
9859
9860         if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9861                                LCPLL_CD_SOURCE_FCLK_DONE, 1))
9862                 DRM_ERROR("Switching to FCLK failed\n");
9863
9864         val = I915_READ(LCPLL_CTL);
9865         val &= ~LCPLL_CLK_FREQ_MASK;
9866
9867         switch (cdclk) {
9868         case 450000:
9869                 val |= LCPLL_CLK_FREQ_450;
9870                 data = 0;
9871                 break;
9872         case 540000:
9873                 val |= LCPLL_CLK_FREQ_54O_BDW;
9874                 data = 1;
9875                 break;
9876         case 337500:
9877                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9878                 data = 2;
9879                 break;
9880         case 675000:
9881                 val |= LCPLL_CLK_FREQ_675_BDW;
9882                 data = 3;
9883                 break;
9884         default:
9885                 WARN(1, "invalid cdclk frequency\n");
9886                 return;
9887         }
9888
9889         I915_WRITE(LCPLL_CTL, val);
9890
9891         val = I915_READ(LCPLL_CTL);
9892         val &= ~LCPLL_CD_SOURCE_FCLK;
9893         I915_WRITE(LCPLL_CTL, val);
9894
9895         if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9896                                 LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9897                 DRM_ERROR("Switching back to LCPLL failed\n");
9898
9899         mutex_lock(&dev_priv->rps.hw_lock);
9900         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9901         mutex_unlock(&dev_priv->rps.hw_lock);
9902
9903         intel_update_cdclk(dev);
9904
9905         WARN(cdclk != dev_priv->cdclk_freq,
9906              "cdclk requested %d kHz but got %d kHz\n",
9907              cdclk, dev_priv->cdclk_freq);
9908 }
9909
9910 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9911 {
9912         struct drm_i915_private *dev_priv = to_i915(state->dev);
9913         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9914         int max_pixclk = ilk_max_pixel_rate(state);
9915         int cdclk;
9916
9917         /*
9918          * FIXME should also account for plane ratio
9919          * once 64bpp pixel formats are supported.
9920          */
9921         if (max_pixclk > 540000)
9922                 cdclk = 675000;
9923         else if (max_pixclk > 450000)
9924                 cdclk = 540000;
9925         else if (max_pixclk > 337500)
9926                 cdclk = 450000;
9927         else
9928                 cdclk = 337500;
9929
9930         if (cdclk > dev_priv->max_cdclk_freq) {
9931                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9932                               cdclk, dev_priv->max_cdclk_freq);
9933                 return -EINVAL;
9934         }
9935
9936         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9937         if (!intel_state->active_crtcs)
9938                 intel_state->dev_cdclk = 337500;
9939
9940         return 0;
9941 }
9942
9943 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9944 {
9945         struct drm_device *dev = old_state->dev;
9946         struct intel_atomic_state *old_intel_state =
9947                 to_intel_atomic_state(old_state);
9948         unsigned req_cdclk = old_intel_state->dev_cdclk;
9949
9950         broadwell_set_cdclk(dev, req_cdclk);
9951 }
9952
9953 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9954                                       struct intel_crtc_state *crtc_state)
9955 {
9956         struct intel_encoder *intel_encoder =
9957                 intel_ddi_get_crtc_new_encoder(crtc_state);
9958
9959         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9960                 if (!intel_ddi_pll_select(crtc, crtc_state))
9961                         return -EINVAL;
9962         }
9963
9964         crtc->lowfreq_avail = false;
9965
9966         return 0;
9967 }
9968
9969 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9970                                 enum port port,
9971                                 struct intel_crtc_state *pipe_config)
9972 {
9973         switch (port) {
9974         case PORT_A:
9975                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9976                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
9977                 break;
9978         case PORT_B:
9979                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9980                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
9981                 break;
9982         case PORT_C:
9983                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9984                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
9985                 break;
9986         default:
9987                 DRM_ERROR("Incorrect port type\n");
9988         }
9989 }
9990
9991 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9992                                 enum port port,
9993                                 struct intel_crtc_state *pipe_config)
9994 {
9995         u32 temp, dpll_ctl1;
9996
9997         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9998         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9999
10000         switch (pipe_config->ddi_pll_sel) {
10001         case SKL_DPLL0:
10002                 /*
10003                  * On SKL the eDP DPLL (DPLL0 as we don't use SSC) is not part
10004                  * of the shared DPLL framework and thus needs to be read out
10005                  * separately
10006                  */
10007                 dpll_ctl1 = I915_READ(DPLL_CTRL1);
10008                 pipe_config->dpll_hw_state.ctrl1 = dpll_ctl1 & 0x3f;
10009                 break;
10010         case SKL_DPLL1:
10011                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL1;
10012                 break;
10013         case SKL_DPLL2:
10014                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL2;
10015                 break;
10016         case SKL_DPLL3:
10017                 pipe_config->shared_dpll = DPLL_ID_SKL_DPLL3;
10018                 break;
10019         }
10020 }
10021
10022 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
10023                                 enum port port,
10024                                 struct intel_crtc_state *pipe_config)
10025 {
10026         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
10027
10028         switch (pipe_config->ddi_pll_sel) {
10029         case PORT_CLK_SEL_WRPLL1:
10030                 pipe_config->shared_dpll = DPLL_ID_WRPLL1;
10031                 break;
10032         case PORT_CLK_SEL_WRPLL2:
10033                 pipe_config->shared_dpll = DPLL_ID_WRPLL2;
10034                 break;
10035         case PORT_CLK_SEL_SPLL:
10036                 pipe_config->shared_dpll = DPLL_ID_SPLL;
10037                 break;
10038         }
10039 }
10040
10041 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
10042                                        struct intel_crtc_state *pipe_config)
10043 {
10044         struct drm_device *dev = crtc->base.dev;
10045         struct drm_i915_private *dev_priv = dev->dev_private;
10046         struct intel_shared_dpll *pll;
10047         enum port port;
10048         uint32_t tmp;
10049
10050         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
10051
10052         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
10053
10054         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
10055                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
10056         else if (IS_BROXTON(dev))
10057                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
10058         else
10059                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
10060
10061         if (pipe_config->shared_dpll >= 0) {
10062                 pll = &dev_priv->shared_dplls[pipe_config->shared_dpll];
10063
10064                 WARN_ON(!pll->get_hw_state(dev_priv, pll,
10065                                            &pipe_config->dpll_hw_state));
10066         }
10067
10068         /*
10069          * Haswell has only FDI/PCH transcoder A. It is which is connected to
10070          * DDI E. So just check whether this pipe is wired to DDI E and whether
10071          * the PCH transcoder is on.
10072          */
10073         if (INTEL_INFO(dev)->gen < 9 &&
10074             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
10075                 pipe_config->has_pch_encoder = true;
10076
10077                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
10078                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
10079                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
10080
10081                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
10082         }
10083 }
10084
10085 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
10086                                     struct intel_crtc_state *pipe_config)
10087 {
10088         struct drm_device *dev = crtc->base.dev;
10089         struct drm_i915_private *dev_priv = dev->dev_private;
10090         enum intel_display_power_domain power_domain;
10091         unsigned long power_domain_mask;
10092         uint32_t tmp;
10093         bool ret;
10094
10095         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
10096         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10097                 return false;
10098         power_domain_mask = BIT(power_domain);
10099
10100         ret = false;
10101
10102         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
10103         pipe_config->shared_dpll = DPLL_ID_PRIVATE;
10104
10105         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
10106         if (tmp & TRANS_DDI_FUNC_ENABLE) {
10107                 enum pipe trans_edp_pipe;
10108                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
10109                 default:
10110                         WARN(1, "unknown pipe linked to edp transcoder\n");
10111                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
10112                 case TRANS_DDI_EDP_INPUT_A_ON:
10113                         trans_edp_pipe = PIPE_A;
10114                         break;
10115                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
10116                         trans_edp_pipe = PIPE_B;
10117                         break;
10118                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
10119                         trans_edp_pipe = PIPE_C;
10120                         break;
10121                 }
10122
10123                 if (trans_edp_pipe == crtc->pipe)
10124                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
10125         }
10126
10127         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
10128         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10129                 goto out;
10130         power_domain_mask |= BIT(power_domain);
10131
10132         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10133         if (!(tmp & PIPECONF_ENABLE))
10134                 goto out;
10135
10136         haswell_get_ddi_port_state(crtc, pipe_config);
10137
10138         intel_get_pipe_timings(crtc, pipe_config);
10139
10140         if (INTEL_INFO(dev)->gen >= 9) {
10141                 skl_init_scalers(dev, crtc, pipe_config);
10142         }
10143
10144         if (INTEL_INFO(dev)->gen >= 9) {
10145                 pipe_config->scaler_state.scaler_id = -1;
10146                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10147         }
10148
10149         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10150         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10151                 power_domain_mask |= BIT(power_domain);
10152                 if (INTEL_INFO(dev)->gen >= 9)
10153                         skylake_get_pfit_config(crtc, pipe_config);
10154                 else
10155                         ironlake_get_pfit_config(crtc, pipe_config);
10156         }
10157
10158         if (IS_HASWELL(dev))
10159                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10160                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10161
10162         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
10163                 pipe_config->pixel_multiplier =
10164                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10165         } else {
10166                 pipe_config->pixel_multiplier = 1;
10167         }
10168
10169         ret = true;
10170
10171 out:
10172         for_each_power_domain(power_domain, power_domain_mask)
10173                 intel_display_power_put(dev_priv, power_domain);
10174
10175         return ret;
10176 }
10177
10178 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10179                                const struct intel_plane_state *plane_state)
10180 {
10181         struct drm_device *dev = crtc->dev;
10182         struct drm_i915_private *dev_priv = dev->dev_private;
10183         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10184         uint32_t cntl = 0, size = 0;
10185
10186         if (plane_state && plane_state->visible) {
10187                 unsigned int width = plane_state->base.crtc_w;
10188                 unsigned int height = plane_state->base.crtc_h;
10189                 unsigned int stride = roundup_pow_of_two(width) * 4;
10190
10191                 switch (stride) {
10192                 default:
10193                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10194                                   width, stride);
10195                         stride = 256;
10196                         /* fallthrough */
10197                 case 256:
10198                 case 512:
10199                 case 1024:
10200                 case 2048:
10201                         break;
10202                 }
10203
10204                 cntl |= CURSOR_ENABLE |
10205                         CURSOR_GAMMA_ENABLE |
10206                         CURSOR_FORMAT_ARGB |
10207                         CURSOR_STRIDE(stride);
10208
10209                 size = (height << 12) | width;
10210         }
10211
10212         if (intel_crtc->cursor_cntl != 0 &&
10213             (intel_crtc->cursor_base != base ||
10214              intel_crtc->cursor_size != size ||
10215              intel_crtc->cursor_cntl != cntl)) {
10216                 /* On these chipsets we can only modify the base/size/stride
10217                  * whilst the cursor is disabled.
10218                  */
10219                 I915_WRITE(CURCNTR(PIPE_A), 0);
10220                 POSTING_READ(CURCNTR(PIPE_A));
10221                 intel_crtc->cursor_cntl = 0;
10222         }
10223
10224         if (intel_crtc->cursor_base != base) {
10225                 I915_WRITE(CURBASE(PIPE_A), base);
10226                 intel_crtc->cursor_base = base;
10227         }
10228
10229         if (intel_crtc->cursor_size != size) {
10230                 I915_WRITE(CURSIZE, size);
10231                 intel_crtc->cursor_size = size;
10232         }
10233
10234         if (intel_crtc->cursor_cntl != cntl) {
10235                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10236                 POSTING_READ(CURCNTR(PIPE_A));
10237                 intel_crtc->cursor_cntl = cntl;
10238         }
10239 }
10240
10241 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10242                                const struct intel_plane_state *plane_state)
10243 {
10244         struct drm_device *dev = crtc->dev;
10245         struct drm_i915_private *dev_priv = dev->dev_private;
10246         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10247         int pipe = intel_crtc->pipe;
10248         uint32_t cntl = 0;
10249
10250         if (plane_state && plane_state->visible) {
10251                 cntl = MCURSOR_GAMMA_ENABLE;
10252                 switch (plane_state->base.crtc_w) {
10253                         case 64:
10254                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10255                                 break;
10256                         case 128:
10257                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10258                                 break;
10259                         case 256:
10260                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10261                                 break;
10262                         default:
10263                                 MISSING_CASE(plane_state->base.crtc_w);
10264                                 return;
10265                 }
10266                 cntl |= pipe << 28; /* Connect to correct pipe */
10267
10268                 if (HAS_DDI(dev))
10269                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10270
10271                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10272                         cntl |= CURSOR_ROTATE_180;
10273         }
10274
10275         if (intel_crtc->cursor_cntl != cntl) {
10276                 I915_WRITE(CURCNTR(pipe), cntl);
10277                 POSTING_READ(CURCNTR(pipe));
10278                 intel_crtc->cursor_cntl = cntl;
10279         }
10280
10281         /* and commit changes on next vblank */
10282         I915_WRITE(CURBASE(pipe), base);
10283         POSTING_READ(CURBASE(pipe));
10284
10285         intel_crtc->cursor_base = base;
10286 }
10287
10288 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10289 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10290                                      const struct intel_plane_state *plane_state)
10291 {
10292         struct drm_device *dev = crtc->dev;
10293         struct drm_i915_private *dev_priv = dev->dev_private;
10294         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10295         int pipe = intel_crtc->pipe;
10296         u32 base = intel_crtc->cursor_addr;
10297         u32 pos = 0;
10298
10299         if (plane_state) {
10300                 int x = plane_state->base.crtc_x;
10301                 int y = plane_state->base.crtc_y;
10302
10303                 if (x < 0) {
10304                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10305                         x = -x;
10306                 }
10307                 pos |= x << CURSOR_X_SHIFT;
10308
10309                 if (y < 0) {
10310                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10311                         y = -y;
10312                 }
10313                 pos |= y << CURSOR_Y_SHIFT;
10314
10315                 /* ILK+ do this automagically */
10316                 if (HAS_GMCH_DISPLAY(dev) &&
10317                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10318                         base += (plane_state->base.crtc_h *
10319                                  plane_state->base.crtc_w - 1) * 4;
10320                 }
10321         }
10322
10323         I915_WRITE(CURPOS(pipe), pos);
10324
10325         if (IS_845G(dev) || IS_I865G(dev))
10326                 i845_update_cursor(crtc, base, plane_state);
10327         else
10328                 i9xx_update_cursor(crtc, base, plane_state);
10329 }
10330
10331 static bool cursor_size_ok(struct drm_device *dev,
10332                            uint32_t width, uint32_t height)
10333 {
10334         if (width == 0 || height == 0)
10335                 return false;
10336
10337         /*
10338          * 845g/865g are special in that they are only limited by
10339          * the width of their cursors, the height is arbitrary up to
10340          * the precision of the register. Everything else requires
10341          * square cursors, limited to a few power-of-two sizes.
10342          */
10343         if (IS_845G(dev) || IS_I865G(dev)) {
10344                 if ((width & 63) != 0)
10345                         return false;
10346
10347                 if (width > (IS_845G(dev) ? 64 : 512))
10348                         return false;
10349
10350                 if (height > 1023)
10351                         return false;
10352         } else {
10353                 switch (width | height) {
10354                 case 256:
10355                 case 128:
10356                         if (IS_GEN2(dev))
10357                                 return false;
10358                 case 64:
10359                         break;
10360                 default:
10361                         return false;
10362                 }
10363         }
10364
10365         return true;
10366 }
10367
10368 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10369                                  u16 *blue, uint32_t start, uint32_t size)
10370 {
10371         int end = (start + size > 256) ? 256 : start + size, i;
10372         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10373
10374         for (i = start; i < end; i++) {
10375                 intel_crtc->lut_r[i] = red[i] >> 8;
10376                 intel_crtc->lut_g[i] = green[i] >> 8;
10377                 intel_crtc->lut_b[i] = blue[i] >> 8;
10378         }
10379
10380         intel_crtc_load_lut(crtc);
10381 }
10382
10383 /* VESA 640x480x72Hz mode to set on the pipe */
10384 static struct drm_display_mode load_detect_mode = {
10385         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10386                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10387 };
10388
10389 struct drm_framebuffer *
10390 __intel_framebuffer_create(struct drm_device *dev,
10391                            struct drm_mode_fb_cmd2 *mode_cmd,
10392                            struct drm_i915_gem_object *obj)
10393 {
10394         struct intel_framebuffer *intel_fb;
10395         int ret;
10396
10397         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10398         if (!intel_fb)
10399                 return ERR_PTR(-ENOMEM);
10400
10401         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10402         if (ret)
10403                 goto err;
10404
10405         return &intel_fb->base;
10406
10407 err:
10408         kfree(intel_fb);
10409         return ERR_PTR(ret);
10410 }
10411
10412 static struct drm_framebuffer *
10413 intel_framebuffer_create(struct drm_device *dev,
10414                          struct drm_mode_fb_cmd2 *mode_cmd,
10415                          struct drm_i915_gem_object *obj)
10416 {
10417         struct drm_framebuffer *fb;
10418         int ret;
10419
10420         ret = i915_mutex_lock_interruptible(dev);
10421         if (ret)
10422                 return ERR_PTR(ret);
10423         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10424         mutex_unlock(&dev->struct_mutex);
10425
10426         return fb;
10427 }
10428
10429 static u32
10430 intel_framebuffer_pitch_for_width(int width, int bpp)
10431 {
10432         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10433         return ALIGN(pitch, 64);
10434 }
10435
10436 static u32
10437 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10438 {
10439         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10440         return PAGE_ALIGN(pitch * mode->vdisplay);
10441 }
10442
10443 static struct drm_framebuffer *
10444 intel_framebuffer_create_for_mode(struct drm_device *dev,
10445                                   struct drm_display_mode *mode,
10446                                   int depth, int bpp)
10447 {
10448         struct drm_framebuffer *fb;
10449         struct drm_i915_gem_object *obj;
10450         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10451
10452         obj = i915_gem_alloc_object(dev,
10453                                     intel_framebuffer_size_for_mode(mode, bpp));
10454         if (obj == NULL)
10455                 return ERR_PTR(-ENOMEM);
10456
10457         mode_cmd.width = mode->hdisplay;
10458         mode_cmd.height = mode->vdisplay;
10459         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10460                                                                 bpp);
10461         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10462
10463         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10464         if (IS_ERR(fb))
10465                 drm_gem_object_unreference_unlocked(&obj->base);
10466
10467         return fb;
10468 }
10469
10470 static struct drm_framebuffer *
10471 mode_fits_in_fbdev(struct drm_device *dev,
10472                    struct drm_display_mode *mode)
10473 {
10474 #ifdef CONFIG_DRM_FBDEV_EMULATION
10475         struct drm_i915_private *dev_priv = dev->dev_private;
10476         struct drm_i915_gem_object *obj;
10477         struct drm_framebuffer *fb;
10478
10479         if (!dev_priv->fbdev)
10480                 return NULL;
10481
10482         if (!dev_priv->fbdev->fb)
10483                 return NULL;
10484
10485         obj = dev_priv->fbdev->fb->obj;
10486         BUG_ON(!obj);
10487
10488         fb = &dev_priv->fbdev->fb->base;
10489         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10490                                                                fb->bits_per_pixel))
10491                 return NULL;
10492
10493         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10494                 return NULL;
10495
10496         drm_framebuffer_reference(fb);
10497         return fb;
10498 #else
10499         return NULL;
10500 #endif
10501 }
10502
10503 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10504                                            struct drm_crtc *crtc,
10505                                            struct drm_display_mode *mode,
10506                                            struct drm_framebuffer *fb,
10507                                            int x, int y)
10508 {
10509         struct drm_plane_state *plane_state;
10510         int hdisplay, vdisplay;
10511         int ret;
10512
10513         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10514         if (IS_ERR(plane_state))
10515                 return PTR_ERR(plane_state);
10516
10517         if (mode)
10518                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10519         else
10520                 hdisplay = vdisplay = 0;
10521
10522         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10523         if (ret)
10524                 return ret;
10525         drm_atomic_set_fb_for_plane(plane_state, fb);
10526         plane_state->crtc_x = 0;
10527         plane_state->crtc_y = 0;
10528         plane_state->crtc_w = hdisplay;
10529         plane_state->crtc_h = vdisplay;
10530         plane_state->src_x = x << 16;
10531         plane_state->src_y = y << 16;
10532         plane_state->src_w = hdisplay << 16;
10533         plane_state->src_h = vdisplay << 16;
10534
10535         return 0;
10536 }
10537
10538 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10539                                 struct drm_display_mode *mode,
10540                                 struct intel_load_detect_pipe *old,
10541                                 struct drm_modeset_acquire_ctx *ctx)
10542 {
10543         struct intel_crtc *intel_crtc;
10544         struct intel_encoder *intel_encoder =
10545                 intel_attached_encoder(connector);
10546         struct drm_crtc *possible_crtc;
10547         struct drm_encoder *encoder = &intel_encoder->base;
10548         struct drm_crtc *crtc = NULL;
10549         struct drm_device *dev = encoder->dev;
10550         struct drm_framebuffer *fb;
10551         struct drm_mode_config *config = &dev->mode_config;
10552         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10553         struct drm_connector_state *connector_state;
10554         struct intel_crtc_state *crtc_state;
10555         int ret, i = -1;
10556
10557         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10558                       connector->base.id, connector->name,
10559                       encoder->base.id, encoder->name);
10560
10561         old->restore_state = NULL;
10562
10563 retry:
10564         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10565         if (ret)
10566                 goto fail;
10567
10568         /*
10569          * Algorithm gets a little messy:
10570          *
10571          *   - if the connector already has an assigned crtc, use it (but make
10572          *     sure it's on first)
10573          *
10574          *   - try to find the first unused crtc that can drive this connector,
10575          *     and use that if we find one
10576          */
10577
10578         /* See if we already have a CRTC for this connector */
10579         if (connector->state->crtc) {
10580                 crtc = connector->state->crtc;
10581
10582                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10583                 if (ret)
10584                         goto fail;
10585
10586                 /* Make sure the crtc and connector are running */
10587                 goto found;
10588         }
10589
10590         /* Find an unused one (if possible) */
10591         for_each_crtc(dev, possible_crtc) {
10592                 i++;
10593                 if (!(encoder->possible_crtcs & (1 << i)))
10594                         continue;
10595
10596                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10597                 if (ret)
10598                         goto fail;
10599
10600                 if (possible_crtc->state->enable) {
10601                         drm_modeset_unlock(&possible_crtc->mutex);
10602                         continue;
10603                 }
10604
10605                 crtc = possible_crtc;
10606                 break;
10607         }
10608
10609         /*
10610          * If we didn't find an unused CRTC, don't use any.
10611          */
10612         if (!crtc) {
10613                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10614                 goto fail;
10615         }
10616
10617 found:
10618         intel_crtc = to_intel_crtc(crtc);
10619
10620         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10621         if (ret)
10622                 goto fail;
10623
10624         state = drm_atomic_state_alloc(dev);
10625         restore_state = drm_atomic_state_alloc(dev);
10626         if (!state || !restore_state) {
10627                 ret = -ENOMEM;
10628                 goto fail;
10629         }
10630
10631         state->acquire_ctx = ctx;
10632         restore_state->acquire_ctx = ctx;
10633
10634         connector_state = drm_atomic_get_connector_state(state, connector);
10635         if (IS_ERR(connector_state)) {
10636                 ret = PTR_ERR(connector_state);
10637                 goto fail;
10638         }
10639
10640         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10641         if (ret)
10642                 goto fail;
10643
10644         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10645         if (IS_ERR(crtc_state)) {
10646                 ret = PTR_ERR(crtc_state);
10647                 goto fail;
10648         }
10649
10650         crtc_state->base.active = crtc_state->base.enable = true;
10651
10652         if (!mode)
10653                 mode = &load_detect_mode;
10654
10655         /* We need a framebuffer large enough to accommodate all accesses
10656          * that the plane may generate whilst we perform load detection.
10657          * We can not rely on the fbcon either being present (we get called
10658          * during its initialisation to detect all boot displays, or it may
10659          * not even exist) or that it is large enough to satisfy the
10660          * requested mode.
10661          */
10662         fb = mode_fits_in_fbdev(dev, mode);
10663         if (fb == NULL) {
10664                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10665                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10666         } else
10667                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10668         if (IS_ERR(fb)) {
10669                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10670                 goto fail;
10671         }
10672
10673         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10674         if (ret)
10675                 goto fail;
10676
10677         drm_framebuffer_unreference(fb);
10678
10679         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10680         if (ret)
10681                 goto fail;
10682
10683         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10684         if (!ret)
10685                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10686         if (!ret)
10687                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10688         if (ret) {
10689                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10690                 goto fail;
10691         }
10692
10693         ret = drm_atomic_commit(state);
10694         if (ret) {
10695                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10696                 goto fail;
10697         }
10698
10699         old->restore_state = restore_state;
10700
10701         /* let the connector get through one full cycle before testing */
10702         intel_wait_for_vblank(dev, intel_crtc->pipe);
10703         return true;
10704
10705 fail:
10706         drm_atomic_state_free(state);
10707         drm_atomic_state_free(restore_state);
10708         restore_state = state = NULL;
10709
10710         if (ret == -EDEADLK) {
10711                 drm_modeset_backoff(ctx);
10712                 goto retry;
10713         }
10714
10715         return false;
10716 }
10717
10718 void intel_release_load_detect_pipe(struct drm_connector *connector,
10719                                     struct intel_load_detect_pipe *old,
10720                                     struct drm_modeset_acquire_ctx *ctx)
10721 {
10722         struct intel_encoder *intel_encoder =
10723                 intel_attached_encoder(connector);
10724         struct drm_encoder *encoder = &intel_encoder->base;
10725         struct drm_atomic_state *state = old->restore_state;
10726         int ret;
10727
10728         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10729                       connector->base.id, connector->name,
10730                       encoder->base.id, encoder->name);
10731
10732         if (!state)
10733                 return;
10734
10735         ret = drm_atomic_commit(state);
10736         if (ret) {
10737                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10738                 drm_atomic_state_free(state);
10739         }
10740 }
10741
10742 static int i9xx_pll_refclk(struct drm_device *dev,
10743                            const struct intel_crtc_state *pipe_config)
10744 {
10745         struct drm_i915_private *dev_priv = dev->dev_private;
10746         u32 dpll = pipe_config->dpll_hw_state.dpll;
10747
10748         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10749                 return dev_priv->vbt.lvds_ssc_freq;
10750         else if (HAS_PCH_SPLIT(dev))
10751                 return 120000;
10752         else if (!IS_GEN2(dev))
10753                 return 96000;
10754         else
10755                 return 48000;
10756 }
10757
10758 /* Returns the clock of the currently programmed mode of the given pipe. */
10759 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10760                                 struct intel_crtc_state *pipe_config)
10761 {
10762         struct drm_device *dev = crtc->base.dev;
10763         struct drm_i915_private *dev_priv = dev->dev_private;
10764         int pipe = pipe_config->cpu_transcoder;
10765         u32 dpll = pipe_config->dpll_hw_state.dpll;
10766         u32 fp;
10767         intel_clock_t clock;
10768         int port_clock;
10769         int refclk = i9xx_pll_refclk(dev, pipe_config);
10770
10771         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10772                 fp = pipe_config->dpll_hw_state.fp0;
10773         else
10774                 fp = pipe_config->dpll_hw_state.fp1;
10775
10776         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10777         if (IS_PINEVIEW(dev)) {
10778                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10779                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10780         } else {
10781                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10782                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10783         }
10784
10785         if (!IS_GEN2(dev)) {
10786                 if (IS_PINEVIEW(dev))
10787                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10788                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10789                 else
10790                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10791                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10792
10793                 switch (dpll & DPLL_MODE_MASK) {
10794                 case DPLLB_MODE_DAC_SERIAL:
10795                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10796                                 5 : 10;
10797                         break;
10798                 case DPLLB_MODE_LVDS:
10799                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10800                                 7 : 14;
10801                         break;
10802                 default:
10803                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10804                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10805                         return;
10806                 }
10807
10808                 if (IS_PINEVIEW(dev))
10809                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10810                 else
10811                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10812         } else {
10813                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10814                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10815
10816                 if (is_lvds) {
10817                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10818                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10819
10820                         if (lvds & LVDS_CLKB_POWER_UP)
10821                                 clock.p2 = 7;
10822                         else
10823                                 clock.p2 = 14;
10824                 } else {
10825                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10826                                 clock.p1 = 2;
10827                         else {
10828                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10829                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10830                         }
10831                         if (dpll & PLL_P2_DIVIDE_BY_4)
10832                                 clock.p2 = 4;
10833                         else
10834                                 clock.p2 = 2;
10835                 }
10836
10837                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10838         }
10839
10840         /*
10841          * This value includes pixel_multiplier. We will use
10842          * port_clock to compute adjusted_mode.crtc_clock in the
10843          * encoder's get_config() function.
10844          */
10845         pipe_config->port_clock = port_clock;
10846 }
10847
10848 int intel_dotclock_calculate(int link_freq,
10849                              const struct intel_link_m_n *m_n)
10850 {
10851         /*
10852          * The calculation for the data clock is:
10853          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10854          * But we want to avoid losing precison if possible, so:
10855          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10856          *
10857          * and the link clock is simpler:
10858          * link_clock = (m * link_clock) / n
10859          */
10860
10861         if (!m_n->link_n)
10862                 return 0;
10863
10864         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10865 }
10866
10867 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10868                                    struct intel_crtc_state *pipe_config)
10869 {
10870         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10871
10872         /* read out port_clock from the DPLL */
10873         i9xx_crtc_clock_get(crtc, pipe_config);
10874
10875         /*
10876          * In case there is an active pipe without active ports,
10877          * we may need some idea for the dotclock anyway.
10878          * Calculate one based on the FDI configuration.
10879          */
10880         pipe_config->base.adjusted_mode.crtc_clock =
10881                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10882                                          &pipe_config->fdi_m_n);
10883 }
10884
10885 /** Returns the currently programmed mode of the given pipe. */
10886 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10887                                              struct drm_crtc *crtc)
10888 {
10889         struct drm_i915_private *dev_priv = dev->dev_private;
10890         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10891         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10892         struct drm_display_mode *mode;
10893         struct intel_crtc_state *pipe_config;
10894         int htot = I915_READ(HTOTAL(cpu_transcoder));
10895         int hsync = I915_READ(HSYNC(cpu_transcoder));
10896         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10897         int vsync = I915_READ(VSYNC(cpu_transcoder));
10898         enum pipe pipe = intel_crtc->pipe;
10899
10900         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10901         if (!mode)
10902                 return NULL;
10903
10904         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10905         if (!pipe_config) {
10906                 kfree(mode);
10907                 return NULL;
10908         }
10909
10910         /*
10911          * Construct a pipe_config sufficient for getting the clock info
10912          * back out of crtc_clock_get.
10913          *
10914          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10915          * to use a real value here instead.
10916          */
10917         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10918         pipe_config->pixel_multiplier = 1;
10919         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10920         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10921         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10922         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10923
10924         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10925         mode->hdisplay = (htot & 0xffff) + 1;
10926         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10927         mode->hsync_start = (hsync & 0xffff) + 1;
10928         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10929         mode->vdisplay = (vtot & 0xffff) + 1;
10930         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10931         mode->vsync_start = (vsync & 0xffff) + 1;
10932         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10933
10934         drm_mode_set_name(mode);
10935
10936         kfree(pipe_config);
10937
10938         return mode;
10939 }
10940
10941 void intel_mark_busy(struct drm_device *dev)
10942 {
10943         struct drm_i915_private *dev_priv = dev->dev_private;
10944
10945         if (dev_priv->mm.busy)
10946                 return;
10947
10948         intel_runtime_pm_get(dev_priv);
10949         i915_update_gfx_val(dev_priv);
10950         if (INTEL_INFO(dev)->gen >= 6)
10951                 gen6_rps_busy(dev_priv);
10952         dev_priv->mm.busy = true;
10953 }
10954
10955 void intel_mark_idle(struct drm_device *dev)
10956 {
10957         struct drm_i915_private *dev_priv = dev->dev_private;
10958
10959         if (!dev_priv->mm.busy)
10960                 return;
10961
10962         dev_priv->mm.busy = false;
10963
10964         if (INTEL_INFO(dev)->gen >= 6)
10965                 gen6_rps_idle(dev->dev_private);
10966
10967         intel_runtime_pm_put(dev_priv);
10968 }
10969
10970 static void intel_crtc_destroy(struct drm_crtc *crtc)
10971 {
10972         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10973         struct drm_device *dev = crtc->dev;
10974         struct intel_unpin_work *work;
10975
10976         spin_lock_irq(&dev->event_lock);
10977         work = intel_crtc->unpin_work;
10978         intel_crtc->unpin_work = NULL;
10979         spin_unlock_irq(&dev->event_lock);
10980
10981         if (work) {
10982                 cancel_work_sync(&work->work);
10983                 kfree(work);
10984         }
10985
10986         drm_crtc_cleanup(crtc);
10987
10988         kfree(intel_crtc);
10989 }
10990
10991 static void intel_unpin_work_fn(struct work_struct *__work)
10992 {
10993         struct intel_unpin_work *work =
10994                 container_of(__work, struct intel_unpin_work, work);
10995         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10996         struct drm_device *dev = crtc->base.dev;
10997         struct drm_plane *primary = crtc->base.primary;
10998
10999         mutex_lock(&dev->struct_mutex);
11000         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
11001         drm_gem_object_unreference(&work->pending_flip_obj->base);
11002
11003         if (work->flip_queued_req)
11004                 i915_gem_request_assign(&work->flip_queued_req, NULL);
11005         mutex_unlock(&dev->struct_mutex);
11006
11007         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
11008         intel_fbc_post_update(crtc);
11009         drm_framebuffer_unreference(work->old_fb);
11010
11011         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
11012         atomic_dec(&crtc->unpin_work_count);
11013
11014         kfree(work);
11015 }
11016
11017 static void do_intel_finish_page_flip(struct drm_device *dev,
11018                                       struct drm_crtc *crtc)
11019 {
11020         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11021         struct intel_unpin_work *work;
11022         unsigned long flags;
11023
11024         /* Ignore early vblank irqs */
11025         if (intel_crtc == NULL)
11026                 return;
11027
11028         /*
11029          * This is called both by irq handlers and the reset code (to complete
11030          * lost pageflips) so needs the full irqsave spinlocks.
11031          */
11032         spin_lock_irqsave(&dev->event_lock, flags);
11033         work = intel_crtc->unpin_work;
11034
11035         /* Ensure we don't miss a work->pending update ... */
11036         smp_rmb();
11037
11038         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
11039                 spin_unlock_irqrestore(&dev->event_lock, flags);
11040                 return;
11041         }
11042
11043         page_flip_completed(intel_crtc);
11044
11045         spin_unlock_irqrestore(&dev->event_lock, flags);
11046 }
11047
11048 void intel_finish_page_flip(struct drm_device *dev, int pipe)
11049 {
11050         struct drm_i915_private *dev_priv = dev->dev_private;
11051         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11052
11053         do_intel_finish_page_flip(dev, crtc);
11054 }
11055
11056 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
11057 {
11058         struct drm_i915_private *dev_priv = dev->dev_private;
11059         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
11060
11061         do_intel_finish_page_flip(dev, crtc);
11062 }
11063
11064 /* Is 'a' after or equal to 'b'? */
11065 static bool g4x_flip_count_after_eq(u32 a, u32 b)
11066 {
11067         return !((a - b) & 0x80000000);
11068 }
11069
11070 static bool page_flip_finished(struct intel_crtc *crtc)
11071 {
11072         struct drm_device *dev = crtc->base.dev;
11073         struct drm_i915_private *dev_priv = dev->dev_private;
11074
11075         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
11076             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
11077                 return true;
11078
11079         /*
11080          * The relevant registers doen't exist on pre-ctg.
11081          * As the flip done interrupt doesn't trigger for mmio
11082          * flips on gmch platforms, a flip count check isn't
11083          * really needed there. But since ctg has the registers,
11084          * include it in the check anyway.
11085          */
11086         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
11087                 return true;
11088
11089         /*
11090          * BDW signals flip done immediately if the plane
11091          * is disabled, even if the plane enable is already
11092          * armed to occur at the next vblank :(
11093          */
11094
11095         /*
11096          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
11097          * used the same base address. In that case the mmio flip might
11098          * have completed, but the CS hasn't even executed the flip yet.
11099          *
11100          * A flip count check isn't enough as the CS might have updated
11101          * the base address just after start of vblank, but before we
11102          * managed to process the interrupt. This means we'd complete the
11103          * CS flip too soon.
11104          *
11105          * Combining both checks should get us a good enough result. It may
11106          * still happen that the CS flip has been executed, but has not
11107          * yet actually completed. But in case the base address is the same
11108          * anyway, we don't really care.
11109          */
11110         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
11111                 crtc->unpin_work->gtt_offset &&
11112                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
11113                                     crtc->unpin_work->flip_count);
11114 }
11115
11116 void intel_prepare_page_flip(struct drm_device *dev, int plane)
11117 {
11118         struct drm_i915_private *dev_priv = dev->dev_private;
11119         struct intel_crtc *intel_crtc =
11120                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
11121         unsigned long flags;
11122
11123
11124         /*
11125          * This is called both by irq handlers and the reset code (to complete
11126          * lost pageflips) so needs the full irqsave spinlocks.
11127          *
11128          * NB: An MMIO update of the plane base pointer will also
11129          * generate a page-flip completion irq, i.e. every modeset
11130          * is also accompanied by a spurious intel_prepare_page_flip().
11131          */
11132         spin_lock_irqsave(&dev->event_lock, flags);
11133         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
11134                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
11135         spin_unlock_irqrestore(&dev->event_lock, flags);
11136 }
11137
11138 static inline void intel_mark_page_flip_active(struct intel_unpin_work *work)
11139 {
11140         /* Ensure that the work item is consistent when activating it ... */
11141         smp_wmb();
11142         atomic_set(&work->pending, INTEL_FLIP_PENDING);
11143         /* and that it is marked active as soon as the irq could fire. */
11144         smp_wmb();
11145 }
11146
11147 static int intel_gen2_queue_flip(struct drm_device *dev,
11148                                  struct drm_crtc *crtc,
11149                                  struct drm_framebuffer *fb,
11150                                  struct drm_i915_gem_object *obj,
11151                                  struct drm_i915_gem_request *req,
11152                                  uint32_t flags)
11153 {
11154         struct intel_engine_cs *ring = req->ring;
11155         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11156         u32 flip_mask;
11157         int ret;
11158
11159         ret = intel_ring_begin(req, 6);
11160         if (ret)
11161                 return ret;
11162
11163         /* Can't queue multiple flips, so wait for the previous
11164          * one to finish before executing the next.
11165          */
11166         if (intel_crtc->plane)
11167                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11168         else
11169                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11170         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11171         intel_ring_emit(ring, MI_NOOP);
11172         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11173                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11174         intel_ring_emit(ring, fb->pitches[0]);
11175         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11176         intel_ring_emit(ring, 0); /* aux display base address, unused */
11177
11178         intel_mark_page_flip_active(intel_crtc->unpin_work);
11179         return 0;
11180 }
11181
11182 static int intel_gen3_queue_flip(struct drm_device *dev,
11183                                  struct drm_crtc *crtc,
11184                                  struct drm_framebuffer *fb,
11185                                  struct drm_i915_gem_object *obj,
11186                                  struct drm_i915_gem_request *req,
11187                                  uint32_t flags)
11188 {
11189         struct intel_engine_cs *ring = req->ring;
11190         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11191         u32 flip_mask;
11192         int ret;
11193
11194         ret = intel_ring_begin(req, 6);
11195         if (ret)
11196                 return ret;
11197
11198         if (intel_crtc->plane)
11199                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11200         else
11201                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11202         intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
11203         intel_ring_emit(ring, MI_NOOP);
11204         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 |
11205                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11206         intel_ring_emit(ring, fb->pitches[0]);
11207         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11208         intel_ring_emit(ring, MI_NOOP);
11209
11210         intel_mark_page_flip_active(intel_crtc->unpin_work);
11211         return 0;
11212 }
11213
11214 static int intel_gen4_queue_flip(struct drm_device *dev,
11215                                  struct drm_crtc *crtc,
11216                                  struct drm_framebuffer *fb,
11217                                  struct drm_i915_gem_object *obj,
11218                                  struct drm_i915_gem_request *req,
11219                                  uint32_t flags)
11220 {
11221         struct intel_engine_cs *ring = req->ring;
11222         struct drm_i915_private *dev_priv = dev->dev_private;
11223         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11224         uint32_t pf, pipesrc;
11225         int ret;
11226
11227         ret = intel_ring_begin(req, 4);
11228         if (ret)
11229                 return ret;
11230
11231         /* i965+ uses the linear or tiled offsets from the
11232          * Display Registers (which do not change across a page-flip)
11233          * so we need only reprogram the base address.
11234          */
11235         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11236                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11237         intel_ring_emit(ring, fb->pitches[0]);
11238         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset |
11239                         obj->tiling_mode);
11240
11241         /* XXX Enabling the panel-fitter across page-flip is so far
11242          * untested on non-native modes, so ignore it for now.
11243          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11244          */
11245         pf = 0;
11246         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11247         intel_ring_emit(ring, pf | pipesrc);
11248
11249         intel_mark_page_flip_active(intel_crtc->unpin_work);
11250         return 0;
11251 }
11252
11253 static int intel_gen6_queue_flip(struct drm_device *dev,
11254                                  struct drm_crtc *crtc,
11255                                  struct drm_framebuffer *fb,
11256                                  struct drm_i915_gem_object *obj,
11257                                  struct drm_i915_gem_request *req,
11258                                  uint32_t flags)
11259 {
11260         struct intel_engine_cs *ring = req->ring;
11261         struct drm_i915_private *dev_priv = dev->dev_private;
11262         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11263         uint32_t pf, pipesrc;
11264         int ret;
11265
11266         ret = intel_ring_begin(req, 4);
11267         if (ret)
11268                 return ret;
11269
11270         intel_ring_emit(ring, MI_DISPLAY_FLIP |
11271                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11272         intel_ring_emit(ring, fb->pitches[0] | obj->tiling_mode);
11273         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11274
11275         /* Contrary to the suggestions in the documentation,
11276          * "Enable Panel Fitter" does not seem to be required when page
11277          * flipping with a non-native mode, and worse causes a normal
11278          * modeset to fail.
11279          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11280          */
11281         pf = 0;
11282         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11283         intel_ring_emit(ring, pf | pipesrc);
11284
11285         intel_mark_page_flip_active(intel_crtc->unpin_work);
11286         return 0;
11287 }
11288
11289 static int intel_gen7_queue_flip(struct drm_device *dev,
11290                                  struct drm_crtc *crtc,
11291                                  struct drm_framebuffer *fb,
11292                                  struct drm_i915_gem_object *obj,
11293                                  struct drm_i915_gem_request *req,
11294                                  uint32_t flags)
11295 {
11296         struct intel_engine_cs *ring = req->ring;
11297         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11298         uint32_t plane_bit = 0;
11299         int len, ret;
11300
11301         switch (intel_crtc->plane) {
11302         case PLANE_A:
11303                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11304                 break;
11305         case PLANE_B:
11306                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11307                 break;
11308         case PLANE_C:
11309                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11310                 break;
11311         default:
11312                 WARN_ONCE(1, "unknown plane in flip command\n");
11313                 return -ENODEV;
11314         }
11315
11316         len = 4;
11317         if (ring->id == RCS) {
11318                 len += 6;
11319                 /*
11320                  * On Gen 8, SRM is now taking an extra dword to accommodate
11321                  * 48bits addresses, and we need a NOOP for the batch size to
11322                  * stay even.
11323                  */
11324                 if (IS_GEN8(dev))
11325                         len += 2;
11326         }
11327
11328         /*
11329          * BSpec MI_DISPLAY_FLIP for IVB:
11330          * "The full packet must be contained within the same cache line."
11331          *
11332          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11333          * cacheline, if we ever start emitting more commands before
11334          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11335          * then do the cacheline alignment, and finally emit the
11336          * MI_DISPLAY_FLIP.
11337          */
11338         ret = intel_ring_cacheline_align(req);
11339         if (ret)
11340                 return ret;
11341
11342         ret = intel_ring_begin(req, len);
11343         if (ret)
11344                 return ret;
11345
11346         /* Unmask the flip-done completion message. Note that the bspec says that
11347          * we should do this for both the BCS and RCS, and that we must not unmask
11348          * more than one flip event at any time (or ensure that one flip message
11349          * can be sent by waiting for flip-done prior to queueing new flips).
11350          * Experimentation says that BCS works despite DERRMR masking all
11351          * flip-done completion events and that unmasking all planes at once
11352          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11353          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11354          */
11355         if (ring->id == RCS) {
11356                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
11357                 intel_ring_emit_reg(ring, DERRMR);
11358                 intel_ring_emit(ring, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11359                                         DERRMR_PIPEB_PRI_FLIP_DONE |
11360                                         DERRMR_PIPEC_PRI_FLIP_DONE));
11361                 if (IS_GEN8(dev))
11362                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM_GEN8 |
11363                                               MI_SRM_LRM_GLOBAL_GTT);
11364                 else
11365                         intel_ring_emit(ring, MI_STORE_REGISTER_MEM |
11366                                               MI_SRM_LRM_GLOBAL_GTT);
11367                 intel_ring_emit_reg(ring, DERRMR);
11368                 intel_ring_emit(ring, ring->scratch.gtt_offset + 256);
11369                 if (IS_GEN8(dev)) {
11370                         intel_ring_emit(ring, 0);
11371                         intel_ring_emit(ring, MI_NOOP);
11372                 }
11373         }
11374
11375         intel_ring_emit(ring, MI_DISPLAY_FLIP_I915 | plane_bit);
11376         intel_ring_emit(ring, (fb->pitches[0] | obj->tiling_mode));
11377         intel_ring_emit(ring, intel_crtc->unpin_work->gtt_offset);
11378         intel_ring_emit(ring, (MI_NOOP));
11379
11380         intel_mark_page_flip_active(intel_crtc->unpin_work);
11381         return 0;
11382 }
11383
11384 static bool use_mmio_flip(struct intel_engine_cs *ring,
11385                           struct drm_i915_gem_object *obj)
11386 {
11387         /*
11388          * This is not being used for older platforms, because
11389          * non-availability of flip done interrupt forces us to use
11390          * CS flips. Older platforms derive flip done using some clever
11391          * tricks involving the flip_pending status bits and vblank irqs.
11392          * So using MMIO flips there would disrupt this mechanism.
11393          */
11394
11395         if (ring == NULL)
11396                 return true;
11397
11398         if (INTEL_INFO(ring->dev)->gen < 5)
11399                 return false;
11400
11401         if (i915.use_mmio_flip < 0)
11402                 return false;
11403         else if (i915.use_mmio_flip > 0)
11404                 return true;
11405         else if (i915.enable_execlists)
11406                 return true;
11407         else if (obj->base.dma_buf &&
11408                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11409                                                        false))
11410                 return true;
11411         else
11412                 return ring != i915_gem_request_get_ring(obj->last_write_req);
11413 }
11414
11415 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11416                              unsigned int rotation,
11417                              struct intel_unpin_work *work)
11418 {
11419         struct drm_device *dev = intel_crtc->base.dev;
11420         struct drm_i915_private *dev_priv = dev->dev_private;
11421         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11422         const enum pipe pipe = intel_crtc->pipe;
11423         u32 ctl, stride, tile_height;
11424
11425         ctl = I915_READ(PLANE_CTL(pipe, 0));
11426         ctl &= ~PLANE_CTL_TILED_MASK;
11427         switch (fb->modifier[0]) {
11428         case DRM_FORMAT_MOD_NONE:
11429                 break;
11430         case I915_FORMAT_MOD_X_TILED:
11431                 ctl |= PLANE_CTL_TILED_X;
11432                 break;
11433         case I915_FORMAT_MOD_Y_TILED:
11434                 ctl |= PLANE_CTL_TILED_Y;
11435                 break;
11436         case I915_FORMAT_MOD_Yf_TILED:
11437                 ctl |= PLANE_CTL_TILED_YF;
11438                 break;
11439         default:
11440                 MISSING_CASE(fb->modifier[0]);
11441         }
11442
11443         /*
11444          * The stride is either expressed as a multiple of 64 bytes chunks for
11445          * linear buffers or in number of tiles for tiled buffers.
11446          */
11447         if (intel_rotation_90_or_270(rotation)) {
11448                 /* stride = Surface height in tiles */
11449                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11450                 stride = DIV_ROUND_UP(fb->height, tile_height);
11451         } else {
11452                 stride = fb->pitches[0] /
11453                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11454                                                   fb->pixel_format);
11455         }
11456
11457         /*
11458          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11459          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11460          */
11461         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11462         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11463
11464         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11465         POSTING_READ(PLANE_SURF(pipe, 0));
11466 }
11467
11468 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11469                              struct intel_unpin_work *work)
11470 {
11471         struct drm_device *dev = intel_crtc->base.dev;
11472         struct drm_i915_private *dev_priv = dev->dev_private;
11473         struct intel_framebuffer *intel_fb =
11474                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11475         struct drm_i915_gem_object *obj = intel_fb->obj;
11476         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11477         u32 dspcntr;
11478
11479         dspcntr = I915_READ(reg);
11480
11481         if (obj->tiling_mode != I915_TILING_NONE)
11482                 dspcntr |= DISPPLANE_TILED;
11483         else
11484                 dspcntr &= ~DISPPLANE_TILED;
11485
11486         I915_WRITE(reg, dspcntr);
11487
11488         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11489         POSTING_READ(DSPSURF(intel_crtc->plane));
11490 }
11491
11492 /*
11493  * XXX: This is the temporary way to update the plane registers until we get
11494  * around to using the usual plane update functions for MMIO flips
11495  */
11496 static void intel_do_mmio_flip(struct intel_mmio_flip *mmio_flip)
11497 {
11498         struct intel_crtc *crtc = mmio_flip->crtc;
11499         struct intel_unpin_work *work;
11500
11501         spin_lock_irq(&crtc->base.dev->event_lock);
11502         work = crtc->unpin_work;
11503         spin_unlock_irq(&crtc->base.dev->event_lock);
11504         if (work == NULL)
11505                 return;
11506
11507         intel_mark_page_flip_active(work);
11508
11509         intel_pipe_update_start(crtc);
11510
11511         if (INTEL_INFO(mmio_flip->i915)->gen >= 9)
11512                 skl_do_mmio_flip(crtc, mmio_flip->rotation, work);
11513         else
11514                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11515                 ilk_do_mmio_flip(crtc, work);
11516
11517         intel_pipe_update_end(crtc);
11518 }
11519
11520 static void intel_mmio_flip_work_func(struct work_struct *work)
11521 {
11522         struct intel_mmio_flip *mmio_flip =
11523                 container_of(work, struct intel_mmio_flip, work);
11524         struct intel_framebuffer *intel_fb =
11525                 to_intel_framebuffer(mmio_flip->crtc->base.primary->fb);
11526         struct drm_i915_gem_object *obj = intel_fb->obj;
11527
11528         if (mmio_flip->req) {
11529                 WARN_ON(__i915_wait_request(mmio_flip->req,
11530                                             mmio_flip->crtc->reset_counter,
11531                                             false, NULL,
11532                                             &mmio_flip->i915->rps.mmioflips));
11533                 i915_gem_request_unreference__unlocked(mmio_flip->req);
11534         }
11535
11536         /* For framebuffer backed by dmabuf, wait for fence */
11537         if (obj->base.dma_buf)
11538                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11539                                                             false, false,
11540                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11541
11542         intel_do_mmio_flip(mmio_flip);
11543         kfree(mmio_flip);
11544 }
11545
11546 static int intel_queue_mmio_flip(struct drm_device *dev,
11547                                  struct drm_crtc *crtc,
11548                                  struct drm_i915_gem_object *obj)
11549 {
11550         struct intel_mmio_flip *mmio_flip;
11551
11552         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11553         if (mmio_flip == NULL)
11554                 return -ENOMEM;
11555
11556         mmio_flip->i915 = to_i915(dev);
11557         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11558         mmio_flip->crtc = to_intel_crtc(crtc);
11559         mmio_flip->rotation = crtc->primary->state->rotation;
11560
11561         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11562         schedule_work(&mmio_flip->work);
11563
11564         return 0;
11565 }
11566
11567 static int intel_default_queue_flip(struct drm_device *dev,
11568                                     struct drm_crtc *crtc,
11569                                     struct drm_framebuffer *fb,
11570                                     struct drm_i915_gem_object *obj,
11571                                     struct drm_i915_gem_request *req,
11572                                     uint32_t flags)
11573 {
11574         return -ENODEV;
11575 }
11576
11577 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11578                                          struct drm_crtc *crtc)
11579 {
11580         struct drm_i915_private *dev_priv = dev->dev_private;
11581         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11582         struct intel_unpin_work *work = intel_crtc->unpin_work;
11583         u32 addr;
11584
11585         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11586                 return true;
11587
11588         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11589                 return false;
11590
11591         if (!work->enable_stall_check)
11592                 return false;
11593
11594         if (work->flip_ready_vblank == 0) {
11595                 if (work->flip_queued_req &&
11596                     !i915_gem_request_completed(work->flip_queued_req, true))
11597                         return false;
11598
11599                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11600         }
11601
11602         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11603                 return false;
11604
11605         /* Potential stall - if we see that the flip has happened,
11606          * assume a missed interrupt. */
11607         if (INTEL_INFO(dev)->gen >= 4)
11608                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11609         else
11610                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11611
11612         /* There is a potential issue here with a false positive after a flip
11613          * to the same address. We could address this by checking for a
11614          * non-incrementing frame counter.
11615          */
11616         return addr == work->gtt_offset;
11617 }
11618
11619 void intel_check_page_flip(struct drm_device *dev, int pipe)
11620 {
11621         struct drm_i915_private *dev_priv = dev->dev_private;
11622         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11623         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11624         struct intel_unpin_work *work;
11625
11626         WARN_ON(!in_interrupt());
11627
11628         if (crtc == NULL)
11629                 return;
11630
11631         spin_lock(&dev->event_lock);
11632         work = intel_crtc->unpin_work;
11633         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11634                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11635                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11636                 page_flip_completed(intel_crtc);
11637                 work = NULL;
11638         }
11639         if (work != NULL &&
11640             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11641                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11642         spin_unlock(&dev->event_lock);
11643 }
11644
11645 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11646                                 struct drm_framebuffer *fb,
11647                                 struct drm_pending_vblank_event *event,
11648                                 uint32_t page_flip_flags)
11649 {
11650         struct drm_device *dev = crtc->dev;
11651         struct drm_i915_private *dev_priv = dev->dev_private;
11652         struct drm_framebuffer *old_fb = crtc->primary->fb;
11653         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11654         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11655         struct drm_plane *primary = crtc->primary;
11656         enum pipe pipe = intel_crtc->pipe;
11657         struct intel_unpin_work *work;
11658         struct intel_engine_cs *ring;
11659         bool mmio_flip;
11660         struct drm_i915_gem_request *request = NULL;
11661         int ret;
11662
11663         /*
11664          * drm_mode_page_flip_ioctl() should already catch this, but double
11665          * check to be safe.  In the future we may enable pageflipping from
11666          * a disabled primary plane.
11667          */
11668         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11669                 return -EBUSY;
11670
11671         /* Can't change pixel format via MI display flips. */
11672         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11673                 return -EINVAL;
11674
11675         /*
11676          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11677          * Note that pitch changes could also affect these register.
11678          */
11679         if (INTEL_INFO(dev)->gen > 3 &&
11680             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11681              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11682                 return -EINVAL;
11683
11684         if (i915_terminally_wedged(&dev_priv->gpu_error))
11685                 goto out_hang;
11686
11687         work = kzalloc(sizeof(*work), GFP_KERNEL);
11688         if (work == NULL)
11689                 return -ENOMEM;
11690
11691         work->event = event;
11692         work->crtc = crtc;
11693         work->old_fb = old_fb;
11694         INIT_WORK(&work->work, intel_unpin_work_fn);
11695
11696         ret = drm_crtc_vblank_get(crtc);
11697         if (ret)
11698                 goto free_work;
11699
11700         /* We borrow the event spin lock for protecting unpin_work */
11701         spin_lock_irq(&dev->event_lock);
11702         if (intel_crtc->unpin_work) {
11703                 /* Before declaring the flip queue wedged, check if
11704                  * the hardware completed the operation behind our backs.
11705                  */
11706                 if (__intel_pageflip_stall_check(dev, crtc)) {
11707                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11708                         page_flip_completed(intel_crtc);
11709                 } else {
11710                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11711                         spin_unlock_irq(&dev->event_lock);
11712
11713                         drm_crtc_vblank_put(crtc);
11714                         kfree(work);
11715                         return -EBUSY;
11716                 }
11717         }
11718         intel_crtc->unpin_work = work;
11719         spin_unlock_irq(&dev->event_lock);
11720
11721         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11722                 flush_workqueue(dev_priv->wq);
11723
11724         /* Reference the objects for the scheduled work. */
11725         drm_framebuffer_reference(work->old_fb);
11726         drm_gem_object_reference(&obj->base);
11727
11728         crtc->primary->fb = fb;
11729         update_state_fb(crtc->primary);
11730         intel_fbc_pre_update(intel_crtc);
11731
11732         work->pending_flip_obj = obj;
11733
11734         ret = i915_mutex_lock_interruptible(dev);
11735         if (ret)
11736                 goto cleanup;
11737
11738         atomic_inc(&intel_crtc->unpin_work_count);
11739         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11740
11741         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11742                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11743
11744         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11745                 ring = &dev_priv->ring[BCS];
11746                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11747                         /* vlv: DISPLAY_FLIP fails to change tiling */
11748                         ring = NULL;
11749         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11750                 ring = &dev_priv->ring[BCS];
11751         } else if (INTEL_INFO(dev)->gen >= 7) {
11752                 ring = i915_gem_request_get_ring(obj->last_write_req);
11753                 if (ring == NULL || ring->id != RCS)
11754                         ring = &dev_priv->ring[BCS];
11755         } else {
11756                 ring = &dev_priv->ring[RCS];
11757         }
11758
11759         mmio_flip = use_mmio_flip(ring, obj);
11760
11761         /* When using CS flips, we want to emit semaphores between rings.
11762          * However, when using mmio flips we will create a task to do the
11763          * synchronisation, so all we want here is to pin the framebuffer
11764          * into the display plane and skip any waits.
11765          */
11766         if (!mmio_flip) {
11767                 ret = i915_gem_object_sync(obj, ring, &request);
11768                 if (ret)
11769                         goto cleanup_pending;
11770         }
11771
11772         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11773         if (ret)
11774                 goto cleanup_pending;
11775
11776         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11777                                                   obj, 0);
11778         work->gtt_offset += intel_crtc->dspaddr_offset;
11779
11780         if (mmio_flip) {
11781                 ret = intel_queue_mmio_flip(dev, crtc, obj);
11782                 if (ret)
11783                         goto cleanup_unpin;
11784
11785                 i915_gem_request_assign(&work->flip_queued_req,
11786                                         obj->last_write_req);
11787         } else {
11788                 if (!request) {
11789                         request = i915_gem_request_alloc(ring, NULL);
11790                         if (IS_ERR(request)) {
11791                                 ret = PTR_ERR(request);
11792                                 goto cleanup_unpin;
11793                         }
11794                 }
11795
11796                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11797                                                    page_flip_flags);
11798                 if (ret)
11799                         goto cleanup_unpin;
11800
11801                 i915_gem_request_assign(&work->flip_queued_req, request);
11802         }
11803
11804         if (request)
11805                 i915_add_request_no_flush(request);
11806
11807         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11808         work->enable_stall_check = true;
11809
11810         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11811                           to_intel_plane(primary)->frontbuffer_bit);
11812         mutex_unlock(&dev->struct_mutex);
11813
11814         intel_frontbuffer_flip_prepare(dev,
11815                                        to_intel_plane(primary)->frontbuffer_bit);
11816
11817         trace_i915_flip_request(intel_crtc->plane, obj);
11818
11819         return 0;
11820
11821 cleanup_unpin:
11822         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11823 cleanup_pending:
11824         if (!IS_ERR_OR_NULL(request))
11825                 i915_gem_request_cancel(request);
11826         atomic_dec(&intel_crtc->unpin_work_count);
11827         mutex_unlock(&dev->struct_mutex);
11828 cleanup:
11829         crtc->primary->fb = old_fb;
11830         update_state_fb(crtc->primary);
11831
11832         drm_gem_object_unreference_unlocked(&obj->base);
11833         drm_framebuffer_unreference(work->old_fb);
11834
11835         spin_lock_irq(&dev->event_lock);
11836         intel_crtc->unpin_work = NULL;
11837         spin_unlock_irq(&dev->event_lock);
11838
11839         drm_crtc_vblank_put(crtc);
11840 free_work:
11841         kfree(work);
11842
11843         if (ret == -EIO) {
11844                 struct drm_atomic_state *state;
11845                 struct drm_plane_state *plane_state;
11846
11847 out_hang:
11848                 state = drm_atomic_state_alloc(dev);
11849                 if (!state)
11850                         return -ENOMEM;
11851                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11852
11853 retry:
11854                 plane_state = drm_atomic_get_plane_state(state, primary);
11855                 ret = PTR_ERR_OR_ZERO(plane_state);
11856                 if (!ret) {
11857                         drm_atomic_set_fb_for_plane(plane_state, fb);
11858
11859                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11860                         if (!ret)
11861                                 ret = drm_atomic_commit(state);
11862                 }
11863
11864                 if (ret == -EDEADLK) {
11865                         drm_modeset_backoff(state->acquire_ctx);
11866                         drm_atomic_state_clear(state);
11867                         goto retry;
11868                 }
11869
11870                 if (ret)
11871                         drm_atomic_state_free(state);
11872
11873                 if (ret == 0 && event) {
11874                         spin_lock_irq(&dev->event_lock);
11875                         drm_send_vblank_event(dev, pipe, event);
11876                         spin_unlock_irq(&dev->event_lock);
11877                 }
11878         }
11879         return ret;
11880 }
11881
11882
11883 /**
11884  * intel_wm_need_update - Check whether watermarks need updating
11885  * @plane: drm plane
11886  * @state: new plane state
11887  *
11888  * Check current plane state versus the new one to determine whether
11889  * watermarks need to be recalculated.
11890  *
11891  * Returns true or false.
11892  */
11893 static bool intel_wm_need_update(struct drm_plane *plane,
11894                                  struct drm_plane_state *state)
11895 {
11896         struct intel_plane_state *new = to_intel_plane_state(state);
11897         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11898
11899         /* Update watermarks on tiling or size changes. */
11900         if (new->visible != cur->visible)
11901                 return true;
11902
11903         if (!cur->base.fb || !new->base.fb)
11904                 return false;
11905
11906         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11907             cur->base.rotation != new->base.rotation ||
11908             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11909             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11910             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11911             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11912                 return true;
11913
11914         return false;
11915 }
11916
11917 static bool needs_scaling(struct intel_plane_state *state)
11918 {
11919         int src_w = drm_rect_width(&state->src) >> 16;
11920         int src_h = drm_rect_height(&state->src) >> 16;
11921         int dst_w = drm_rect_width(&state->dst);
11922         int dst_h = drm_rect_height(&state->dst);
11923
11924         return (src_w != dst_w || src_h != dst_h);
11925 }
11926
11927 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11928                                     struct drm_plane_state *plane_state)
11929 {
11930         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11931         struct drm_crtc *crtc = crtc_state->crtc;
11932         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11933         struct drm_plane *plane = plane_state->plane;
11934         struct drm_device *dev = crtc->dev;
11935         struct drm_i915_private *dev_priv = to_i915(dev);
11936         struct intel_plane_state *old_plane_state =
11937                 to_intel_plane_state(plane->state);
11938         int idx = intel_crtc->base.base.id, ret;
11939         bool mode_changed = needs_modeset(crtc_state);
11940         bool was_crtc_enabled = crtc->state->active;
11941         bool is_crtc_enabled = crtc_state->active;
11942         bool turn_off, turn_on, visible, was_visible;
11943         struct drm_framebuffer *fb = plane_state->fb;
11944
11945         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11946             plane->type != DRM_PLANE_TYPE_CURSOR) {
11947                 ret = skl_update_scaler_plane(
11948                         to_intel_crtc_state(crtc_state),
11949                         to_intel_plane_state(plane_state));
11950                 if (ret)
11951                         return ret;
11952         }
11953
11954         was_visible = old_plane_state->visible;
11955         visible = to_intel_plane_state(plane_state)->visible;
11956
11957         if (!was_crtc_enabled && WARN_ON(was_visible))
11958                 was_visible = false;
11959
11960         /*
11961          * Visibility is calculated as if the crtc was on, but
11962          * after scaler setup everything depends on it being off
11963          * when the crtc isn't active.
11964          */
11965         if (!is_crtc_enabled)
11966                 to_intel_plane_state(plane_state)->visible = visible = false;
11967
11968         if (!was_visible && !visible)
11969                 return 0;
11970
11971         if (fb != old_plane_state->base.fb)
11972                 pipe_config->fb_changed = true;
11973
11974         turn_off = was_visible && (!visible || mode_changed);
11975         turn_on = visible && (!was_visible || mode_changed);
11976
11977         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11978                          plane->base.id, fb ? fb->base.id : -1);
11979
11980         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11981                          plane->base.id, was_visible, visible,
11982                          turn_off, turn_on, mode_changed);
11983
11984         if (turn_on || turn_off) {
11985                 pipe_config->wm_changed = true;
11986
11987                 /* must disable cxsr around plane enable/disable */
11988                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11989                         pipe_config->disable_cxsr = true;
11990         } else if (intel_wm_need_update(plane, plane_state)) {
11991                 pipe_config->wm_changed = true;
11992         }
11993
11994         /* Pre-gen9 platforms need two-step watermark updates */
11995         if (pipe_config->wm_changed && INTEL_INFO(dev)->gen < 9 &&
11996             dev_priv->display.optimize_watermarks)
11997                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11998
11999         if (visible || was_visible)
12000                 intel_crtc->atomic.fb_bits |=
12001                         to_intel_plane(plane)->frontbuffer_bit;
12002
12003         switch (plane->type) {
12004         case DRM_PLANE_TYPE_PRIMARY:
12005                 intel_crtc->atomic.post_enable_primary = turn_on;
12006                 intel_crtc->atomic.update_fbc = true;
12007
12008                 break;
12009         case DRM_PLANE_TYPE_CURSOR:
12010                 break;
12011         case DRM_PLANE_TYPE_OVERLAY:
12012                 /*
12013                  * WaCxSRDisabledForSpriteScaling:ivb
12014                  *
12015                  * cstate->update_wm was already set above, so this flag will
12016                  * take effect when we commit and program watermarks.
12017                  */
12018                 if (IS_IVYBRIDGE(dev) &&
12019                     needs_scaling(to_intel_plane_state(plane_state)) &&
12020                     !needs_scaling(old_plane_state))
12021                         pipe_config->disable_lp_wm = true;
12022
12023                 break;
12024         }
12025         return 0;
12026 }
12027
12028 static bool encoders_cloneable(const struct intel_encoder *a,
12029                                const struct intel_encoder *b)
12030 {
12031         /* masks could be asymmetric, so check both ways */
12032         return a == b || (a->cloneable & (1 << b->type) &&
12033                           b->cloneable & (1 << a->type));
12034 }
12035
12036 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
12037                                          struct intel_crtc *crtc,
12038                                          struct intel_encoder *encoder)
12039 {
12040         struct intel_encoder *source_encoder;
12041         struct drm_connector *connector;
12042         struct drm_connector_state *connector_state;
12043         int i;
12044
12045         for_each_connector_in_state(state, connector, connector_state, i) {
12046                 if (connector_state->crtc != &crtc->base)
12047                         continue;
12048
12049                 source_encoder =
12050                         to_intel_encoder(connector_state->best_encoder);
12051                 if (!encoders_cloneable(encoder, source_encoder))
12052                         return false;
12053         }
12054
12055         return true;
12056 }
12057
12058 static bool check_encoder_cloning(struct drm_atomic_state *state,
12059                                   struct intel_crtc *crtc)
12060 {
12061         struct intel_encoder *encoder;
12062         struct drm_connector *connector;
12063         struct drm_connector_state *connector_state;
12064         int i;
12065
12066         for_each_connector_in_state(state, connector, connector_state, i) {
12067                 if (connector_state->crtc != &crtc->base)
12068                         continue;
12069
12070                 encoder = to_intel_encoder(connector_state->best_encoder);
12071                 if (!check_single_encoder_cloning(state, crtc, encoder))
12072                         return false;
12073         }
12074
12075         return true;
12076 }
12077
12078 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
12079                                    struct drm_crtc_state *crtc_state)
12080 {
12081         struct drm_device *dev = crtc->dev;
12082         struct drm_i915_private *dev_priv = dev->dev_private;
12083         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12084         struct intel_crtc_state *pipe_config =
12085                 to_intel_crtc_state(crtc_state);
12086         struct drm_atomic_state *state = crtc_state->state;
12087         int ret;
12088         bool mode_changed = needs_modeset(crtc_state);
12089
12090         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
12091                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
12092                 return -EINVAL;
12093         }
12094
12095         if (mode_changed && !crtc_state->active)
12096                 pipe_config->wm_changed = true;
12097
12098         if (mode_changed && crtc_state->enable &&
12099             dev_priv->display.crtc_compute_clock &&
12100             !WARN_ON(pipe_config->shared_dpll != DPLL_ID_PRIVATE)) {
12101                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
12102                                                            pipe_config);
12103                 if (ret)
12104                         return ret;
12105         }
12106
12107         ret = 0;
12108         if (dev_priv->display.compute_pipe_wm) {
12109                 ret = dev_priv->display.compute_pipe_wm(intel_crtc, state);
12110                 if (ret) {
12111                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
12112                         return ret;
12113                 }
12114         }
12115
12116         if (dev_priv->display.compute_intermediate_wm &&
12117             !to_intel_atomic_state(state)->skip_intermediate_wm) {
12118                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
12119                         return 0;
12120
12121                 /*
12122                  * Calculate 'intermediate' watermarks that satisfy both the
12123                  * old state and the new state.  We can program these
12124                  * immediately.
12125                  */
12126                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
12127                                                                 intel_crtc,
12128                                                                 pipe_config);
12129                 if (ret) {
12130                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
12131                         return ret;
12132                 }
12133         }
12134
12135         if (INTEL_INFO(dev)->gen >= 9) {
12136                 if (mode_changed)
12137                         ret = skl_update_scaler_crtc(pipe_config);
12138
12139                 if (!ret)
12140                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12141                                                          pipe_config);
12142         }
12143
12144         return ret;
12145 }
12146
12147 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12148         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12149         .load_lut = intel_crtc_load_lut,
12150         .atomic_begin = intel_begin_crtc_commit,
12151         .atomic_flush = intel_finish_crtc_commit,
12152         .atomic_check = intel_crtc_atomic_check,
12153 };
12154
12155 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12156 {
12157         struct intel_connector *connector;
12158
12159         for_each_intel_connector(dev, connector) {
12160                 if (connector->base.encoder) {
12161                         connector->base.state->best_encoder =
12162                                 connector->base.encoder;
12163                         connector->base.state->crtc =
12164                                 connector->base.encoder->crtc;
12165                 } else {
12166                         connector->base.state->best_encoder = NULL;
12167                         connector->base.state->crtc = NULL;
12168                 }
12169         }
12170 }
12171
12172 static void
12173 connected_sink_compute_bpp(struct intel_connector *connector,
12174                            struct intel_crtc_state *pipe_config)
12175 {
12176         int bpp = pipe_config->pipe_bpp;
12177
12178         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12179                 connector->base.base.id,
12180                 connector->base.name);
12181
12182         /* Don't use an invalid EDID bpc value */
12183         if (connector->base.display_info.bpc &&
12184             connector->base.display_info.bpc * 3 < bpp) {
12185                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12186                               bpp, connector->base.display_info.bpc*3);
12187                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12188         }
12189
12190         /* Clamp bpp to default limit on screens without EDID 1.4 */
12191         if (connector->base.display_info.bpc == 0) {
12192                 int type = connector->base.connector_type;
12193                 int clamp_bpp = 24;
12194
12195                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12196                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12197                     type == DRM_MODE_CONNECTOR_eDP)
12198                         clamp_bpp = 18;
12199
12200                 if (bpp > clamp_bpp) {
12201                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12202                                       bpp, clamp_bpp);
12203                         pipe_config->pipe_bpp = clamp_bpp;
12204                 }
12205         }
12206 }
12207
12208 static int
12209 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12210                           struct intel_crtc_state *pipe_config)
12211 {
12212         struct drm_device *dev = crtc->base.dev;
12213         struct drm_atomic_state *state;
12214         struct drm_connector *connector;
12215         struct drm_connector_state *connector_state;
12216         int bpp, i;
12217
12218         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12219                 bpp = 10*3;
12220         else if (INTEL_INFO(dev)->gen >= 5)
12221                 bpp = 12*3;
12222         else
12223                 bpp = 8*3;
12224
12225
12226         pipe_config->pipe_bpp = bpp;
12227
12228         state = pipe_config->base.state;
12229
12230         /* Clamp display bpp to EDID value */
12231         for_each_connector_in_state(state, connector, connector_state, i) {
12232                 if (connector_state->crtc != &crtc->base)
12233                         continue;
12234
12235                 connected_sink_compute_bpp(to_intel_connector(connector),
12236                                            pipe_config);
12237         }
12238
12239         return bpp;
12240 }
12241
12242 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12243 {
12244         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12245                         "type: 0x%x flags: 0x%x\n",
12246                 mode->crtc_clock,
12247                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12248                 mode->crtc_hsync_end, mode->crtc_htotal,
12249                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12250                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12251 }
12252
12253 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12254                                    struct intel_crtc_state *pipe_config,
12255                                    const char *context)
12256 {
12257         struct drm_device *dev = crtc->base.dev;
12258         struct drm_plane *plane;
12259         struct intel_plane *intel_plane;
12260         struct intel_plane_state *state;
12261         struct drm_framebuffer *fb;
12262
12263         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12264                       context, pipe_config, pipe_name(crtc->pipe));
12265
12266         DRM_DEBUG_KMS("cpu_transcoder: %c\n", transcoder_name(pipe_config->cpu_transcoder));
12267         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12268                       pipe_config->pipe_bpp, pipe_config->dither);
12269         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12270                       pipe_config->has_pch_encoder,
12271                       pipe_config->fdi_lanes,
12272                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12273                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12274                       pipe_config->fdi_m_n.tu);
12275         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12276                       pipe_config->has_dp_encoder,
12277                       pipe_config->lane_count,
12278                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12279                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12280                       pipe_config->dp_m_n.tu);
12281
12282         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12283                       pipe_config->has_dp_encoder,
12284                       pipe_config->lane_count,
12285                       pipe_config->dp_m2_n2.gmch_m,
12286                       pipe_config->dp_m2_n2.gmch_n,
12287                       pipe_config->dp_m2_n2.link_m,
12288                       pipe_config->dp_m2_n2.link_n,
12289                       pipe_config->dp_m2_n2.tu);
12290
12291         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12292                       pipe_config->has_audio,
12293                       pipe_config->has_infoframe);
12294
12295         DRM_DEBUG_KMS("requested mode:\n");
12296         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12297         DRM_DEBUG_KMS("adjusted mode:\n");
12298         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12299         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12300         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12301         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12302                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12303         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12304                       crtc->num_scalers,
12305                       pipe_config->scaler_state.scaler_users,
12306                       pipe_config->scaler_state.scaler_id);
12307         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12308                       pipe_config->gmch_pfit.control,
12309                       pipe_config->gmch_pfit.pgm_ratios,
12310                       pipe_config->gmch_pfit.lvds_border_bits);
12311         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12312                       pipe_config->pch_pfit.pos,
12313                       pipe_config->pch_pfit.size,
12314                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12315         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12316         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12317
12318         if (IS_BROXTON(dev)) {
12319                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12320                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12321                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12322                               pipe_config->ddi_pll_sel,
12323                               pipe_config->dpll_hw_state.ebb0,
12324                               pipe_config->dpll_hw_state.ebb4,
12325                               pipe_config->dpll_hw_state.pll0,
12326                               pipe_config->dpll_hw_state.pll1,
12327                               pipe_config->dpll_hw_state.pll2,
12328                               pipe_config->dpll_hw_state.pll3,
12329                               pipe_config->dpll_hw_state.pll6,
12330                               pipe_config->dpll_hw_state.pll8,
12331                               pipe_config->dpll_hw_state.pll9,
12332                               pipe_config->dpll_hw_state.pll10,
12333                               pipe_config->dpll_hw_state.pcsdw12);
12334         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12335                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12336                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12337                               pipe_config->ddi_pll_sel,
12338                               pipe_config->dpll_hw_state.ctrl1,
12339                               pipe_config->dpll_hw_state.cfgcr1,
12340                               pipe_config->dpll_hw_state.cfgcr2);
12341         } else if (HAS_DDI(dev)) {
12342                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12343                               pipe_config->ddi_pll_sel,
12344                               pipe_config->dpll_hw_state.wrpll,
12345                               pipe_config->dpll_hw_state.spll);
12346         } else {
12347                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12348                               "fp0: 0x%x, fp1: 0x%x\n",
12349                               pipe_config->dpll_hw_state.dpll,
12350                               pipe_config->dpll_hw_state.dpll_md,
12351                               pipe_config->dpll_hw_state.fp0,
12352                               pipe_config->dpll_hw_state.fp1);
12353         }
12354
12355         DRM_DEBUG_KMS("planes on this crtc\n");
12356         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12357                 intel_plane = to_intel_plane(plane);
12358                 if (intel_plane->pipe != crtc->pipe)
12359                         continue;
12360
12361                 state = to_intel_plane_state(plane->state);
12362                 fb = state->base.fb;
12363                 if (!fb) {
12364                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12365                                 "disabled, scaler_id = %d\n",
12366                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12367                                 plane->base.id, intel_plane->pipe,
12368                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12369                                 drm_plane_index(plane), state->scaler_id);
12370                         continue;
12371                 }
12372
12373                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12374                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12375                         plane->base.id, intel_plane->pipe,
12376                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12377                         drm_plane_index(plane));
12378                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12379                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12380                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12381                         state->scaler_id,
12382                         state->src.x1 >> 16, state->src.y1 >> 16,
12383                         drm_rect_width(&state->src) >> 16,
12384                         drm_rect_height(&state->src) >> 16,
12385                         state->dst.x1, state->dst.y1,
12386                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12387         }
12388 }
12389
12390 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12391 {
12392         struct drm_device *dev = state->dev;
12393         struct drm_connector *connector;
12394         unsigned int used_ports = 0;
12395
12396         /*
12397          * Walk the connector list instead of the encoder
12398          * list to detect the problem on ddi platforms
12399          * where there's just one encoder per digital port.
12400          */
12401         drm_for_each_connector(connector, dev) {
12402                 struct drm_connector_state *connector_state;
12403                 struct intel_encoder *encoder;
12404
12405                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12406                 if (!connector_state)
12407                         connector_state = connector->state;
12408
12409                 if (!connector_state->best_encoder)
12410                         continue;
12411
12412                 encoder = to_intel_encoder(connector_state->best_encoder);
12413
12414                 WARN_ON(!connector_state->crtc);
12415
12416                 switch (encoder->type) {
12417                         unsigned int port_mask;
12418                 case INTEL_OUTPUT_UNKNOWN:
12419                         if (WARN_ON(!HAS_DDI(dev)))
12420                                 break;
12421                 case INTEL_OUTPUT_DISPLAYPORT:
12422                 case INTEL_OUTPUT_HDMI:
12423                 case INTEL_OUTPUT_EDP:
12424                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12425
12426                         /* the same port mustn't appear more than once */
12427                         if (used_ports & port_mask)
12428                                 return false;
12429
12430                         used_ports |= port_mask;
12431                 default:
12432                         break;
12433                 }
12434         }
12435
12436         return true;
12437 }
12438
12439 static void
12440 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12441 {
12442         struct drm_crtc_state tmp_state;
12443         struct intel_crtc_scaler_state scaler_state;
12444         struct intel_dpll_hw_state dpll_hw_state;
12445         enum intel_dpll_id shared_dpll;
12446         uint32_t ddi_pll_sel;
12447         bool force_thru;
12448
12449         /* FIXME: before the switch to atomic started, a new pipe_config was
12450          * kzalloc'd. Code that depends on any field being zero should be
12451          * fixed, so that the crtc_state can be safely duplicated. For now,
12452          * only fields that are know to not cause problems are preserved. */
12453
12454         tmp_state = crtc_state->base;
12455         scaler_state = crtc_state->scaler_state;
12456         shared_dpll = crtc_state->shared_dpll;
12457         dpll_hw_state = crtc_state->dpll_hw_state;
12458         ddi_pll_sel = crtc_state->ddi_pll_sel;
12459         force_thru = crtc_state->pch_pfit.force_thru;
12460
12461         memset(crtc_state, 0, sizeof *crtc_state);
12462
12463         crtc_state->base = tmp_state;
12464         crtc_state->scaler_state = scaler_state;
12465         crtc_state->shared_dpll = shared_dpll;
12466         crtc_state->dpll_hw_state = dpll_hw_state;
12467         crtc_state->ddi_pll_sel = ddi_pll_sel;
12468         crtc_state->pch_pfit.force_thru = force_thru;
12469 }
12470
12471 static int
12472 intel_modeset_pipe_config(struct drm_crtc *crtc,
12473                           struct intel_crtc_state *pipe_config)
12474 {
12475         struct drm_atomic_state *state = pipe_config->base.state;
12476         struct intel_encoder *encoder;
12477         struct drm_connector *connector;
12478         struct drm_connector_state *connector_state;
12479         int base_bpp, ret = -EINVAL;
12480         int i;
12481         bool retry = true;
12482
12483         clear_intel_crtc_state(pipe_config);
12484
12485         pipe_config->cpu_transcoder =
12486                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12487
12488         /*
12489          * Sanitize sync polarity flags based on requested ones. If neither
12490          * positive or negative polarity is requested, treat this as meaning
12491          * negative polarity.
12492          */
12493         if (!(pipe_config->base.adjusted_mode.flags &
12494               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12495                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12496
12497         if (!(pipe_config->base.adjusted_mode.flags &
12498               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12499                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12500
12501         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12502                                              pipe_config);
12503         if (base_bpp < 0)
12504                 goto fail;
12505
12506         /*
12507          * Determine the real pipe dimensions. Note that stereo modes can
12508          * increase the actual pipe size due to the frame doubling and
12509          * insertion of additional space for blanks between the frame. This
12510          * is stored in the crtc timings. We use the requested mode to do this
12511          * computation to clearly distinguish it from the adjusted mode, which
12512          * can be changed by the connectors in the below retry loop.
12513          */
12514         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12515                                &pipe_config->pipe_src_w,
12516                                &pipe_config->pipe_src_h);
12517
12518 encoder_retry:
12519         /* Ensure the port clock defaults are reset when retrying. */
12520         pipe_config->port_clock = 0;
12521         pipe_config->pixel_multiplier = 1;
12522
12523         /* Fill in default crtc timings, allow encoders to overwrite them. */
12524         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12525                               CRTC_STEREO_DOUBLE);
12526
12527         /* Pass our mode to the connectors and the CRTC to give them a chance to
12528          * adjust it according to limitations or connector properties, and also
12529          * a chance to reject the mode entirely.
12530          */
12531         for_each_connector_in_state(state, connector, connector_state, i) {
12532                 if (connector_state->crtc != crtc)
12533                         continue;
12534
12535                 encoder = to_intel_encoder(connector_state->best_encoder);
12536
12537                 if (!(encoder->compute_config(encoder, pipe_config))) {
12538                         DRM_DEBUG_KMS("Encoder config failure\n");
12539                         goto fail;
12540                 }
12541         }
12542
12543         /* Set default port clock if not overwritten by the encoder. Needs to be
12544          * done afterwards in case the encoder adjusts the mode. */
12545         if (!pipe_config->port_clock)
12546                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12547                         * pipe_config->pixel_multiplier;
12548
12549         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12550         if (ret < 0) {
12551                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12552                 goto fail;
12553         }
12554
12555         if (ret == RETRY) {
12556                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12557                         ret = -EINVAL;
12558                         goto fail;
12559                 }
12560
12561                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12562                 retry = false;
12563                 goto encoder_retry;
12564         }
12565
12566         /* Dithering seems to not pass-through bits correctly when it should, so
12567          * only enable it on 6bpc panels. */
12568         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12569         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12570                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12571
12572 fail:
12573         return ret;
12574 }
12575
12576 static void
12577 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12578 {
12579         struct drm_crtc *crtc;
12580         struct drm_crtc_state *crtc_state;
12581         int i;
12582
12583         /* Double check state. */
12584         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12585                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12586
12587                 /* Update hwmode for vblank functions */
12588                 if (crtc->state->active)
12589                         crtc->hwmode = crtc->state->adjusted_mode;
12590                 else
12591                         crtc->hwmode.crtc_clock = 0;
12592
12593                 /*
12594                  * Update legacy state to satisfy fbc code. This can
12595                  * be removed when fbc uses the atomic state.
12596                  */
12597                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12598                         struct drm_plane_state *plane_state = crtc->primary->state;
12599
12600                         crtc->primary->fb = plane_state->fb;
12601                         crtc->x = plane_state->src_x >> 16;
12602                         crtc->y = plane_state->src_y >> 16;
12603                 }
12604         }
12605 }
12606
12607 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12608 {
12609         int diff;
12610
12611         if (clock1 == clock2)
12612                 return true;
12613
12614         if (!clock1 || !clock2)
12615                 return false;
12616
12617         diff = abs(clock1 - clock2);
12618
12619         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12620                 return true;
12621
12622         return false;
12623 }
12624
12625 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12626         list_for_each_entry((intel_crtc), \
12627                             &(dev)->mode_config.crtc_list, \
12628                             base.head) \
12629                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12630
12631 static bool
12632 intel_compare_m_n(unsigned int m, unsigned int n,
12633                   unsigned int m2, unsigned int n2,
12634                   bool exact)
12635 {
12636         if (m == m2 && n == n2)
12637                 return true;
12638
12639         if (exact || !m || !n || !m2 || !n2)
12640                 return false;
12641
12642         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12643
12644         if (n > n2) {
12645                 while (n > n2) {
12646                         m2 <<= 1;
12647                         n2 <<= 1;
12648                 }
12649         } else if (n < n2) {
12650                 while (n < n2) {
12651                         m <<= 1;
12652                         n <<= 1;
12653                 }
12654         }
12655
12656         if (n != n2)
12657                 return false;
12658
12659         return intel_fuzzy_clock_check(m, m2);
12660 }
12661
12662 static bool
12663 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12664                        struct intel_link_m_n *m2_n2,
12665                        bool adjust)
12666 {
12667         if (m_n->tu == m2_n2->tu &&
12668             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12669                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12670             intel_compare_m_n(m_n->link_m, m_n->link_n,
12671                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12672                 if (adjust)
12673                         *m2_n2 = *m_n;
12674
12675                 return true;
12676         }
12677
12678         return false;
12679 }
12680
12681 static bool
12682 intel_pipe_config_compare(struct drm_device *dev,
12683                           struct intel_crtc_state *current_config,
12684                           struct intel_crtc_state *pipe_config,
12685                           bool adjust)
12686 {
12687         bool ret = true;
12688
12689 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12690         do { \
12691                 if (!adjust) \
12692                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12693                 else \
12694                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12695         } while (0)
12696
12697 #define PIPE_CONF_CHECK_X(name) \
12698         if (current_config->name != pipe_config->name) { \
12699                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12700                           "(expected 0x%08x, found 0x%08x)\n", \
12701                           current_config->name, \
12702                           pipe_config->name); \
12703                 ret = false; \
12704         }
12705
12706 #define PIPE_CONF_CHECK_I(name) \
12707         if (current_config->name != pipe_config->name) { \
12708                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12709                           "(expected %i, found %i)\n", \
12710                           current_config->name, \
12711                           pipe_config->name); \
12712                 ret = false; \
12713         }
12714
12715 #define PIPE_CONF_CHECK_M_N(name) \
12716         if (!intel_compare_link_m_n(&current_config->name, \
12717                                     &pipe_config->name,\
12718                                     adjust)) { \
12719                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12720                           "(expected tu %i gmch %i/%i link %i/%i, " \
12721                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12722                           current_config->name.tu, \
12723                           current_config->name.gmch_m, \
12724                           current_config->name.gmch_n, \
12725                           current_config->name.link_m, \
12726                           current_config->name.link_n, \
12727                           pipe_config->name.tu, \
12728                           pipe_config->name.gmch_m, \
12729                           pipe_config->name.gmch_n, \
12730                           pipe_config->name.link_m, \
12731                           pipe_config->name.link_n); \
12732                 ret = false; \
12733         }
12734
12735 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12736         if (!intel_compare_link_m_n(&current_config->name, \
12737                                     &pipe_config->name, adjust) && \
12738             !intel_compare_link_m_n(&current_config->alt_name, \
12739                                     &pipe_config->name, adjust)) { \
12740                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12741                           "(expected tu %i gmch %i/%i link %i/%i, " \
12742                           "or tu %i gmch %i/%i link %i/%i, " \
12743                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12744                           current_config->name.tu, \
12745                           current_config->name.gmch_m, \
12746                           current_config->name.gmch_n, \
12747                           current_config->name.link_m, \
12748                           current_config->name.link_n, \
12749                           current_config->alt_name.tu, \
12750                           current_config->alt_name.gmch_m, \
12751                           current_config->alt_name.gmch_n, \
12752                           current_config->alt_name.link_m, \
12753                           current_config->alt_name.link_n, \
12754                           pipe_config->name.tu, \
12755                           pipe_config->name.gmch_m, \
12756                           pipe_config->name.gmch_n, \
12757                           pipe_config->name.link_m, \
12758                           pipe_config->name.link_n); \
12759                 ret = false; \
12760         }
12761
12762 /* This is required for BDW+ where there is only one set of registers for
12763  * switching between high and low RR.
12764  * This macro can be used whenever a comparison has to be made between one
12765  * hw state and multiple sw state variables.
12766  */
12767 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12768         if ((current_config->name != pipe_config->name) && \
12769                 (current_config->alt_name != pipe_config->name)) { \
12770                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12771                                   "(expected %i or %i, found %i)\n", \
12772                                   current_config->name, \
12773                                   current_config->alt_name, \
12774                                   pipe_config->name); \
12775                         ret = false; \
12776         }
12777
12778 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12779         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12780                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12781                           "(expected %i, found %i)\n", \
12782                           current_config->name & (mask), \
12783                           pipe_config->name & (mask)); \
12784                 ret = false; \
12785         }
12786
12787 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12788         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12789                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12790                           "(expected %i, found %i)\n", \
12791                           current_config->name, \
12792                           pipe_config->name); \
12793                 ret = false; \
12794         }
12795
12796 #define PIPE_CONF_QUIRK(quirk)  \
12797         ((current_config->quirks | pipe_config->quirks) & (quirk))
12798
12799         PIPE_CONF_CHECK_I(cpu_transcoder);
12800
12801         PIPE_CONF_CHECK_I(has_pch_encoder);
12802         PIPE_CONF_CHECK_I(fdi_lanes);
12803         PIPE_CONF_CHECK_M_N(fdi_m_n);
12804
12805         PIPE_CONF_CHECK_I(has_dp_encoder);
12806         PIPE_CONF_CHECK_I(lane_count);
12807
12808         if (INTEL_INFO(dev)->gen < 8) {
12809                 PIPE_CONF_CHECK_M_N(dp_m_n);
12810
12811                 if (current_config->has_drrs)
12812                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12813         } else
12814                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12815
12816         PIPE_CONF_CHECK_I(has_dsi_encoder);
12817
12818         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12819         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12820         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12821         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12822         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12823         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12824
12825         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12826         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12827         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12828         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12829         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12830         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12831
12832         PIPE_CONF_CHECK_I(pixel_multiplier);
12833         PIPE_CONF_CHECK_I(has_hdmi_sink);
12834         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12835             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12836                 PIPE_CONF_CHECK_I(limited_color_range);
12837         PIPE_CONF_CHECK_I(has_infoframe);
12838
12839         PIPE_CONF_CHECK_I(has_audio);
12840
12841         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12842                               DRM_MODE_FLAG_INTERLACE);
12843
12844         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12845                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12846                                       DRM_MODE_FLAG_PHSYNC);
12847                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12848                                       DRM_MODE_FLAG_NHSYNC);
12849                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12850                                       DRM_MODE_FLAG_PVSYNC);
12851                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12852                                       DRM_MODE_FLAG_NVSYNC);
12853         }
12854
12855         PIPE_CONF_CHECK_X(gmch_pfit.control);
12856         /* pfit ratios are autocomputed by the hw on gen4+ */
12857         if (INTEL_INFO(dev)->gen < 4)
12858                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12859         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12860
12861         if (!adjust) {
12862                 PIPE_CONF_CHECK_I(pipe_src_w);
12863                 PIPE_CONF_CHECK_I(pipe_src_h);
12864
12865                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12866                 if (current_config->pch_pfit.enabled) {
12867                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12868                         PIPE_CONF_CHECK_X(pch_pfit.size);
12869                 }
12870
12871                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12872         }
12873
12874         /* BDW+ don't expose a synchronous way to read the state */
12875         if (IS_HASWELL(dev))
12876                 PIPE_CONF_CHECK_I(ips_enabled);
12877
12878         PIPE_CONF_CHECK_I(double_wide);
12879
12880         PIPE_CONF_CHECK_X(ddi_pll_sel);
12881
12882         PIPE_CONF_CHECK_I(shared_dpll);
12883         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12884         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12885         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12886         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12887         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12888         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12889         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12890         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12891         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12892
12893         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12894                 PIPE_CONF_CHECK_I(pipe_bpp);
12895
12896         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12897         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12898
12899 #undef PIPE_CONF_CHECK_X
12900 #undef PIPE_CONF_CHECK_I
12901 #undef PIPE_CONF_CHECK_I_ALT
12902 #undef PIPE_CONF_CHECK_FLAGS
12903 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12904 #undef PIPE_CONF_QUIRK
12905 #undef INTEL_ERR_OR_DBG_KMS
12906
12907         return ret;
12908 }
12909
12910 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12911                                            const struct intel_crtc_state *pipe_config)
12912 {
12913         if (pipe_config->has_pch_encoder) {
12914                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12915                                                             &pipe_config->fdi_m_n);
12916                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12917
12918                 /*
12919                  * FDI already provided one idea for the dotclock.
12920                  * Yell if the encoder disagrees.
12921                  */
12922                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12923                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12924                      fdi_dotclock, dotclock);
12925         }
12926 }
12927
12928 static void check_wm_state(struct drm_device *dev)
12929 {
12930         struct drm_i915_private *dev_priv = dev->dev_private;
12931         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12932         struct intel_crtc *intel_crtc;
12933         int plane;
12934
12935         if (INTEL_INFO(dev)->gen < 9)
12936                 return;
12937
12938         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12939         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12940
12941         for_each_intel_crtc(dev, intel_crtc) {
12942                 struct skl_ddb_entry *hw_entry, *sw_entry;
12943                 const enum pipe pipe = intel_crtc->pipe;
12944
12945                 if (!intel_crtc->active)
12946                         continue;
12947
12948                 /* planes */
12949                 for_each_plane(dev_priv, pipe, plane) {
12950                         hw_entry = &hw_ddb.plane[pipe][plane];
12951                         sw_entry = &sw_ddb->plane[pipe][plane];
12952
12953                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12954                                 continue;
12955
12956                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12957                                   "(expected (%u,%u), found (%u,%u))\n",
12958                                   pipe_name(pipe), plane + 1,
12959                                   sw_entry->start, sw_entry->end,
12960                                   hw_entry->start, hw_entry->end);
12961                 }
12962
12963                 /* cursor */
12964                 hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12965                 sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12966
12967                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12968                         continue;
12969
12970                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12971                           "(expected (%u,%u), found (%u,%u))\n",
12972                           pipe_name(pipe),
12973                           sw_entry->start, sw_entry->end,
12974                           hw_entry->start, hw_entry->end);
12975         }
12976 }
12977
12978 static void
12979 check_connector_state(struct drm_device *dev,
12980                       struct drm_atomic_state *old_state)
12981 {
12982         struct drm_connector_state *old_conn_state;
12983         struct drm_connector *connector;
12984         int i;
12985
12986         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12987                 struct drm_encoder *encoder = connector->encoder;
12988                 struct drm_connector_state *state = connector->state;
12989
12990                 /* This also checks the encoder/connector hw state with the
12991                  * ->get_hw_state callbacks. */
12992                 intel_connector_check_state(to_intel_connector(connector));
12993
12994                 I915_STATE_WARN(state->best_encoder != encoder,
12995                      "connector's atomic encoder doesn't match legacy encoder\n");
12996         }
12997 }
12998
12999 static void
13000 check_encoder_state(struct drm_device *dev)
13001 {
13002         struct intel_encoder *encoder;
13003         struct intel_connector *connector;
13004
13005         for_each_intel_encoder(dev, encoder) {
13006                 bool enabled = false;
13007                 enum pipe pipe;
13008
13009                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
13010                               encoder->base.base.id,
13011                               encoder->base.name);
13012
13013                 for_each_intel_connector(dev, connector) {
13014                         if (connector->base.state->best_encoder != &encoder->base)
13015                                 continue;
13016                         enabled = true;
13017
13018                         I915_STATE_WARN(connector->base.state->crtc !=
13019                                         encoder->base.crtc,
13020                              "connector's crtc doesn't match encoder crtc\n");
13021                 }
13022
13023                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
13024                      "encoder's enabled state mismatch "
13025                      "(expected %i, found %i)\n",
13026                      !!encoder->base.crtc, enabled);
13027
13028                 if (!encoder->base.crtc) {
13029                         bool active;
13030
13031                         active = encoder->get_hw_state(encoder, &pipe);
13032                         I915_STATE_WARN(active,
13033                              "encoder detached but still enabled on pipe %c.\n",
13034                              pipe_name(pipe));
13035                 }
13036         }
13037 }
13038
13039 static void
13040 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
13041 {
13042         struct drm_i915_private *dev_priv = dev->dev_private;
13043         struct intel_encoder *encoder;
13044         struct drm_crtc_state *old_crtc_state;
13045         struct drm_crtc *crtc;
13046         int i;
13047
13048         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
13049                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13050                 struct intel_crtc_state *pipe_config, *sw_config;
13051                 bool active;
13052
13053                 if (!needs_modeset(crtc->state) &&
13054                     !to_intel_crtc_state(crtc->state)->update_pipe)
13055                         continue;
13056
13057                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
13058                 pipe_config = to_intel_crtc_state(old_crtc_state);
13059                 memset(pipe_config, 0, sizeof(*pipe_config));
13060                 pipe_config->base.crtc = crtc;
13061                 pipe_config->base.state = old_state;
13062
13063                 DRM_DEBUG_KMS("[CRTC:%d]\n",
13064                               crtc->base.id);
13065
13066                 active = dev_priv->display.get_pipe_config(intel_crtc,
13067                                                            pipe_config);
13068
13069                 /* hw state is inconsistent with the pipe quirk */
13070                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
13071                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
13072                         active = crtc->state->active;
13073
13074                 I915_STATE_WARN(crtc->state->active != active,
13075                      "crtc active state doesn't match with hw state "
13076                      "(expected %i, found %i)\n", crtc->state->active, active);
13077
13078                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
13079                      "transitional active state does not match atomic hw state "
13080                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
13081
13082                 for_each_encoder_on_crtc(dev, crtc, encoder) {
13083                         enum pipe pipe;
13084
13085                         active = encoder->get_hw_state(encoder, &pipe);
13086                         I915_STATE_WARN(active != crtc->state->active,
13087                                 "[ENCODER:%i] active %i with crtc active %i\n",
13088                                 encoder->base.base.id, active, crtc->state->active);
13089
13090                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
13091                                         "Encoder connected to wrong pipe %c\n",
13092                                         pipe_name(pipe));
13093
13094                         if (active)
13095                                 encoder->get_config(encoder, pipe_config);
13096                 }
13097
13098                 if (!crtc->state->active)
13099                         continue;
13100
13101                 intel_pipe_config_sanity_check(dev_priv, pipe_config);
13102
13103                 sw_config = to_intel_crtc_state(crtc->state);
13104                 if (!intel_pipe_config_compare(dev, sw_config,
13105                                                pipe_config, false)) {
13106                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
13107                         intel_dump_pipe_config(intel_crtc, pipe_config,
13108                                                "[hw state]");
13109                         intel_dump_pipe_config(intel_crtc, sw_config,
13110                                                "[sw state]");
13111                 }
13112         }
13113 }
13114
13115 static void
13116 check_shared_dpll_state(struct drm_device *dev)
13117 {
13118         struct drm_i915_private *dev_priv = dev->dev_private;
13119         struct intel_crtc *crtc;
13120         struct intel_dpll_hw_state dpll_hw_state;
13121         int i;
13122
13123         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13124                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
13125                 int enabled_crtcs = 0, active_crtcs = 0;
13126                 bool active;
13127
13128                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13129
13130                 DRM_DEBUG_KMS("%s\n", pll->name);
13131
13132                 active = pll->get_hw_state(dev_priv, pll, &dpll_hw_state);
13133
13134                 I915_STATE_WARN(pll->active > hweight32(pll->config.crtc_mask),
13135                      "more active pll users than references: %i vs %i\n",
13136                      pll->active, hweight32(pll->config.crtc_mask));
13137                 I915_STATE_WARN(pll->active && !pll->on,
13138                      "pll in active use but not on in sw tracking\n");
13139                 I915_STATE_WARN(pll->on && !pll->active,
13140                      "pll in on but not on in use in sw tracking\n");
13141                 I915_STATE_WARN(pll->on != active,
13142                      "pll on state mismatch (expected %i, found %i)\n",
13143                      pll->on, active);
13144
13145                 for_each_intel_crtc(dev, crtc) {
13146                         if (crtc->base.state->enable && intel_crtc_to_shared_dpll(crtc) == pll)
13147                                 enabled_crtcs++;
13148                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll)
13149                                 active_crtcs++;
13150                 }
13151                 I915_STATE_WARN(pll->active != active_crtcs,
13152                      "pll active crtcs mismatch (expected %i, found %i)\n",
13153                      pll->active, active_crtcs);
13154                 I915_STATE_WARN(hweight32(pll->config.crtc_mask) != enabled_crtcs,
13155                      "pll enabled crtcs mismatch (expected %i, found %i)\n",
13156                      hweight32(pll->config.crtc_mask), enabled_crtcs);
13157
13158                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
13159                                        sizeof(dpll_hw_state)),
13160                      "pll hw state mismatch\n");
13161         }
13162 }
13163
13164 static void
13165 intel_modeset_check_state(struct drm_device *dev,
13166                           struct drm_atomic_state *old_state)
13167 {
13168         check_wm_state(dev);
13169         check_connector_state(dev, old_state);
13170         check_encoder_state(dev);
13171         check_crtc_state(dev, old_state);
13172         check_shared_dpll_state(dev);
13173 }
13174
13175 static void update_scanline_offset(struct intel_crtc *crtc)
13176 {
13177         struct drm_device *dev = crtc->base.dev;
13178
13179         /*
13180          * The scanline counter increments at the leading edge of hsync.
13181          *
13182          * On most platforms it starts counting from vtotal-1 on the
13183          * first active line. That means the scanline counter value is
13184          * always one less than what we would expect. Ie. just after
13185          * start of vblank, which also occurs at start of hsync (on the
13186          * last active line), the scanline counter will read vblank_start-1.
13187          *
13188          * On gen2 the scanline counter starts counting from 1 instead
13189          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13190          * to keep the value positive), instead of adding one.
13191          *
13192          * On HSW+ the behaviour of the scanline counter depends on the output
13193          * type. For DP ports it behaves like most other platforms, but on HDMI
13194          * there's an extra 1 line difference. So we need to add two instead of
13195          * one to the value.
13196          */
13197         if (IS_GEN2(dev)) {
13198                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13199                 int vtotal;
13200
13201                 vtotal = adjusted_mode->crtc_vtotal;
13202                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13203                         vtotal /= 2;
13204
13205                 crtc->scanline_offset = vtotal - 1;
13206         } else if (HAS_DDI(dev) &&
13207                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13208                 crtc->scanline_offset = 2;
13209         } else
13210                 crtc->scanline_offset = 1;
13211 }
13212
13213 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13214 {
13215         struct drm_device *dev = state->dev;
13216         struct drm_i915_private *dev_priv = to_i915(dev);
13217         struct intel_shared_dpll_config *shared_dpll = NULL;
13218         struct drm_crtc *crtc;
13219         struct drm_crtc_state *crtc_state;
13220         int i;
13221
13222         if (!dev_priv->display.crtc_compute_clock)
13223                 return;
13224
13225         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13226                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13227                 int old_dpll = to_intel_crtc_state(crtc->state)->shared_dpll;
13228
13229                 if (!needs_modeset(crtc_state))
13230                         continue;
13231
13232                 to_intel_crtc_state(crtc_state)->shared_dpll = DPLL_ID_PRIVATE;
13233
13234                 if (old_dpll == DPLL_ID_PRIVATE)
13235                         continue;
13236
13237                 if (!shared_dpll)
13238                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13239
13240                 shared_dpll[old_dpll].crtc_mask &= ~(1 << intel_crtc->pipe);
13241         }
13242 }
13243
13244 /*
13245  * This implements the workaround described in the "notes" section of the mode
13246  * set sequence documentation. When going from no pipes or single pipe to
13247  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13248  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13249  */
13250 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13251 {
13252         struct drm_crtc_state *crtc_state;
13253         struct intel_crtc *intel_crtc;
13254         struct drm_crtc *crtc;
13255         struct intel_crtc_state *first_crtc_state = NULL;
13256         struct intel_crtc_state *other_crtc_state = NULL;
13257         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13258         int i;
13259
13260         /* look at all crtc's that are going to be enabled in during modeset */
13261         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13262                 intel_crtc = to_intel_crtc(crtc);
13263
13264                 if (!crtc_state->active || !needs_modeset(crtc_state))
13265                         continue;
13266
13267                 if (first_crtc_state) {
13268                         other_crtc_state = to_intel_crtc_state(crtc_state);
13269                         break;
13270                 } else {
13271                         first_crtc_state = to_intel_crtc_state(crtc_state);
13272                         first_pipe = intel_crtc->pipe;
13273                 }
13274         }
13275
13276         /* No workaround needed? */
13277         if (!first_crtc_state)
13278                 return 0;
13279
13280         /* w/a possibly needed, check how many crtc's are already enabled. */
13281         for_each_intel_crtc(state->dev, intel_crtc) {
13282                 struct intel_crtc_state *pipe_config;
13283
13284                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13285                 if (IS_ERR(pipe_config))
13286                         return PTR_ERR(pipe_config);
13287
13288                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13289
13290                 if (!pipe_config->base.active ||
13291                     needs_modeset(&pipe_config->base))
13292                         continue;
13293
13294                 /* 2 or more enabled crtcs means no need for w/a */
13295                 if (enabled_pipe != INVALID_PIPE)
13296                         return 0;
13297
13298                 enabled_pipe = intel_crtc->pipe;
13299         }
13300
13301         if (enabled_pipe != INVALID_PIPE)
13302                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13303         else if (other_crtc_state)
13304                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13305
13306         return 0;
13307 }
13308
13309 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13310 {
13311         struct drm_crtc *crtc;
13312         struct drm_crtc_state *crtc_state;
13313         int ret = 0;
13314
13315         /* add all active pipes to the state */
13316         for_each_crtc(state->dev, crtc) {
13317                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13318                 if (IS_ERR(crtc_state))
13319                         return PTR_ERR(crtc_state);
13320
13321                 if (!crtc_state->active || needs_modeset(crtc_state))
13322                         continue;
13323
13324                 crtc_state->mode_changed = true;
13325
13326                 ret = drm_atomic_add_affected_connectors(state, crtc);
13327                 if (ret)
13328                         break;
13329
13330                 ret = drm_atomic_add_affected_planes(state, crtc);
13331                 if (ret)
13332                         break;
13333         }
13334
13335         return ret;
13336 }
13337
13338 static int intel_modeset_checks(struct drm_atomic_state *state)
13339 {
13340         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13341         struct drm_i915_private *dev_priv = state->dev->dev_private;
13342         struct drm_crtc *crtc;
13343         struct drm_crtc_state *crtc_state;
13344         int ret = 0, i;
13345
13346         if (!check_digital_port_conflicts(state)) {
13347                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13348                 return -EINVAL;
13349         }
13350
13351         intel_state->modeset = true;
13352         intel_state->active_crtcs = dev_priv->active_crtcs;
13353
13354         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13355                 if (crtc_state->active)
13356                         intel_state->active_crtcs |= 1 << i;
13357                 else
13358                         intel_state->active_crtcs &= ~(1 << i);
13359         }
13360
13361         /*
13362          * See if the config requires any additional preparation, e.g.
13363          * to adjust global state with pipes off.  We need to do this
13364          * here so we can get the modeset_pipe updated config for the new
13365          * mode set on this crtc.  For other crtcs we need to use the
13366          * adjusted_mode bits in the crtc directly.
13367          */
13368         if (dev_priv->display.modeset_calc_cdclk) {
13369                 ret = dev_priv->display.modeset_calc_cdclk(state);
13370
13371                 if (!ret && intel_state->dev_cdclk != dev_priv->cdclk_freq)
13372                         ret = intel_modeset_all_pipes(state);
13373
13374                 if (ret < 0)
13375                         return ret;
13376
13377                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13378                               intel_state->cdclk, intel_state->dev_cdclk);
13379         } else
13380                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13381
13382         intel_modeset_clear_plls(state);
13383
13384         if (IS_HASWELL(dev_priv))
13385                 return haswell_mode_set_planes_workaround(state);
13386
13387         return 0;
13388 }
13389
13390 /*
13391  * Handle calculation of various watermark data at the end of the atomic check
13392  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13393  * handlers to ensure that all derived state has been updated.
13394  */
13395 static void calc_watermark_data(struct drm_atomic_state *state)
13396 {
13397         struct drm_device *dev = state->dev;
13398         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13399         struct drm_crtc *crtc;
13400         struct drm_crtc_state *cstate;
13401         struct drm_plane *plane;
13402         struct drm_plane_state *pstate;
13403
13404         /*
13405          * Calculate watermark configuration details now that derived
13406          * plane/crtc state is all properly updated.
13407          */
13408         drm_for_each_crtc(crtc, dev) {
13409                 cstate = drm_atomic_get_existing_crtc_state(state, crtc) ?:
13410                         crtc->state;
13411
13412                 if (cstate->active)
13413                         intel_state->wm_config.num_pipes_active++;
13414         }
13415         drm_for_each_legacy_plane(plane, dev) {
13416                 pstate = drm_atomic_get_existing_plane_state(state, plane) ?:
13417                         plane->state;
13418
13419                 if (!to_intel_plane_state(pstate)->visible)
13420                         continue;
13421
13422                 intel_state->wm_config.sprites_enabled = true;
13423                 if (pstate->crtc_w != pstate->src_w >> 16 ||
13424                     pstate->crtc_h != pstate->src_h >> 16)
13425                         intel_state->wm_config.sprites_scaled = true;
13426         }
13427 }
13428
13429 /**
13430  * intel_atomic_check - validate state object
13431  * @dev: drm device
13432  * @state: state to validate
13433  */
13434 static int intel_atomic_check(struct drm_device *dev,
13435                               struct drm_atomic_state *state)
13436 {
13437         struct drm_i915_private *dev_priv = to_i915(dev);
13438         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13439         struct drm_crtc *crtc;
13440         struct drm_crtc_state *crtc_state;
13441         int ret, i;
13442         bool any_ms = false;
13443
13444         ret = drm_atomic_helper_check_modeset(dev, state);
13445         if (ret)
13446                 return ret;
13447
13448         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13449                 struct intel_crtc_state *pipe_config =
13450                         to_intel_crtc_state(crtc_state);
13451
13452                 memset(&to_intel_crtc(crtc)->atomic, 0,
13453                        sizeof(struct intel_crtc_atomic_commit));
13454
13455                 /* Catch I915_MODE_FLAG_INHERITED */
13456                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13457                         crtc_state->mode_changed = true;
13458
13459                 if (!crtc_state->enable) {
13460                         if (needs_modeset(crtc_state))
13461                                 any_ms = true;
13462                         continue;
13463                 }
13464
13465                 if (!needs_modeset(crtc_state))
13466                         continue;
13467
13468                 /* FIXME: For only active_changed we shouldn't need to do any
13469                  * state recomputation at all. */
13470
13471                 ret = drm_atomic_add_affected_connectors(state, crtc);
13472                 if (ret)
13473                         return ret;
13474
13475                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13476                 if (ret)
13477                         return ret;
13478
13479                 if (i915.fastboot &&
13480                     intel_pipe_config_compare(dev,
13481                                         to_intel_crtc_state(crtc->state),
13482                                         pipe_config, true)) {
13483                         crtc_state->mode_changed = false;
13484                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13485                 }
13486
13487                 if (needs_modeset(crtc_state)) {
13488                         any_ms = true;
13489
13490                         ret = drm_atomic_add_affected_planes(state, crtc);
13491                         if (ret)
13492                                 return ret;
13493                 }
13494
13495                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13496                                        needs_modeset(crtc_state) ?
13497                                        "[modeset]" : "[fastset]");
13498         }
13499
13500         if (any_ms) {
13501                 ret = intel_modeset_checks(state);
13502
13503                 if (ret)
13504                         return ret;
13505         } else
13506                 intel_state->cdclk = dev_priv->cdclk_freq;
13507
13508         ret = drm_atomic_helper_check_planes(dev, state);
13509         if (ret)
13510                 return ret;
13511
13512         intel_fbc_choose_crtc(dev_priv, state);
13513         calc_watermark_data(state);
13514
13515         return 0;
13516 }
13517
13518 static int intel_atomic_prepare_commit(struct drm_device *dev,
13519                                        struct drm_atomic_state *state,
13520                                        bool async)
13521 {
13522         struct drm_i915_private *dev_priv = dev->dev_private;
13523         struct drm_plane_state *plane_state;
13524         struct drm_crtc_state *crtc_state;
13525         struct drm_plane *plane;
13526         struct drm_crtc *crtc;
13527         int i, ret;
13528
13529         if (async) {
13530                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13531                 return -EINVAL;
13532         }
13533
13534         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13535                 ret = intel_crtc_wait_for_pending_flips(crtc);
13536                 if (ret)
13537                         return ret;
13538
13539                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13540                         flush_workqueue(dev_priv->wq);
13541         }
13542
13543         ret = mutex_lock_interruptible(&dev->struct_mutex);
13544         if (ret)
13545                 return ret;
13546
13547         ret = drm_atomic_helper_prepare_planes(dev, state);
13548         if (!ret && !async && !i915_reset_in_progress(&dev_priv->gpu_error)) {
13549                 u32 reset_counter;
13550
13551                 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
13552                 mutex_unlock(&dev->struct_mutex);
13553
13554                 for_each_plane_in_state(state, plane, plane_state, i) {
13555                         struct intel_plane_state *intel_plane_state =
13556                                 to_intel_plane_state(plane_state);
13557
13558                         if (!intel_plane_state->wait_req)
13559                                 continue;
13560
13561                         ret = __i915_wait_request(intel_plane_state->wait_req,
13562                                                   reset_counter, true,
13563                                                   NULL, NULL);
13564
13565                         /* Swallow -EIO errors to allow updates during hw lockup. */
13566                         if (ret == -EIO)
13567                                 ret = 0;
13568
13569                         if (ret)
13570                                 break;
13571                 }
13572
13573                 if (!ret)
13574                         return 0;
13575
13576                 mutex_lock(&dev->struct_mutex);
13577                 drm_atomic_helper_cleanup_planes(dev, state);
13578         }
13579
13580         mutex_unlock(&dev->struct_mutex);
13581         return ret;
13582 }
13583
13584 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13585                                           struct drm_i915_private *dev_priv,
13586                                           unsigned crtc_mask)
13587 {
13588         unsigned last_vblank_count[I915_MAX_PIPES];
13589         enum pipe pipe;
13590         int ret;
13591
13592         if (!crtc_mask)
13593                 return;
13594
13595         for_each_pipe(dev_priv, pipe) {
13596                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13597
13598                 if (!((1 << pipe) & crtc_mask))
13599                         continue;
13600
13601                 ret = drm_crtc_vblank_get(crtc);
13602                 if (WARN_ON(ret != 0)) {
13603                         crtc_mask &= ~(1 << pipe);
13604                         continue;
13605                 }
13606
13607                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13608         }
13609
13610         for_each_pipe(dev_priv, pipe) {
13611                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13612                 long lret;
13613
13614                 if (!((1 << pipe) & crtc_mask))
13615                         continue;
13616
13617                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13618                                 last_vblank_count[pipe] !=
13619                                         drm_crtc_vblank_count(crtc),
13620                                 msecs_to_jiffies(50));
13621
13622                 WARN_ON(!lret);
13623
13624                 drm_crtc_vblank_put(crtc);
13625         }
13626 }
13627
13628 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13629 {
13630         /* fb updated, need to unpin old fb */
13631         if (crtc_state->fb_changed)
13632                 return true;
13633
13634         /* wm changes, need vblank before final wm's */
13635         if (crtc_state->wm_changed)
13636                 return true;
13637
13638         /*
13639          * cxsr is re-enabled after vblank.
13640          * This is already handled by crtc_state->wm_changed,
13641          * but added for clarity.
13642          */
13643         if (crtc_state->disable_cxsr)
13644                 return true;
13645
13646         return false;
13647 }
13648
13649 /**
13650  * intel_atomic_commit - commit validated state object
13651  * @dev: DRM device
13652  * @state: the top-level driver state object
13653  * @async: asynchronous commit
13654  *
13655  * This function commits a top-level state object that has been validated
13656  * with drm_atomic_helper_check().
13657  *
13658  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13659  * we can only handle plane-related operations and do not yet support
13660  * asynchronous commit.
13661  *
13662  * RETURNS
13663  * Zero for success or -errno.
13664  */
13665 static int intel_atomic_commit(struct drm_device *dev,
13666                                struct drm_atomic_state *state,
13667                                bool async)
13668 {
13669         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13670         struct drm_i915_private *dev_priv = dev->dev_private;
13671         struct drm_crtc_state *crtc_state;
13672         struct drm_crtc *crtc;
13673         struct intel_crtc_state *intel_cstate;
13674         int ret = 0, i;
13675         bool hw_check = intel_state->modeset;
13676         unsigned long put_domains[I915_MAX_PIPES] = {};
13677         unsigned crtc_vblank_mask = 0;
13678
13679         ret = intel_atomic_prepare_commit(dev, state, async);
13680         if (ret) {
13681                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13682                 return ret;
13683         }
13684
13685         drm_atomic_helper_swap_state(dev, state);
13686         dev_priv->wm.config = to_intel_atomic_state(state)->wm_config;
13687
13688         if (intel_state->modeset) {
13689                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13690                        sizeof(intel_state->min_pixclk));
13691                 dev_priv->active_crtcs = intel_state->active_crtcs;
13692                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13693
13694                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13695         }
13696
13697         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13698                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13699
13700                 if (needs_modeset(crtc->state) ||
13701                     to_intel_crtc_state(crtc->state)->update_pipe) {
13702                         hw_check = true;
13703
13704                         put_domains[to_intel_crtc(crtc)->pipe] =
13705                                 modeset_get_crtc_power_domains(crtc,
13706                                         to_intel_crtc_state(crtc->state));
13707                 }
13708
13709                 if (!needs_modeset(crtc->state))
13710                         continue;
13711
13712                 intel_pre_plane_update(to_intel_crtc_state(crtc_state));
13713
13714                 if (crtc_state->active) {
13715                         intel_crtc_disable_planes(crtc, crtc_state->plane_mask);
13716                         dev_priv->display.crtc_disable(crtc);
13717                         intel_crtc->active = false;
13718                         intel_fbc_disable(intel_crtc);
13719                         intel_disable_shared_dpll(intel_crtc);
13720
13721                         /*
13722                          * Underruns don't always raise
13723                          * interrupts, so check manually.
13724                          */
13725                         intel_check_cpu_fifo_underruns(dev_priv);
13726                         intel_check_pch_fifo_underruns(dev_priv);
13727
13728                         if (!crtc->state->active)
13729                                 intel_update_watermarks(crtc);
13730                 }
13731         }
13732
13733         /* Only after disabling all output pipelines that will be changed can we
13734          * update the the output configuration. */
13735         intel_modeset_update_crtc_state(state);
13736
13737         if (intel_state->modeset) {
13738                 intel_shared_dpll_commit(state);
13739
13740                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13741
13742                 if (dev_priv->display.modeset_commit_cdclk &&
13743                     intel_state->dev_cdclk != dev_priv->cdclk_freq)
13744                         dev_priv->display.modeset_commit_cdclk(state);
13745         }
13746
13747         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13748         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13749                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13750                 bool modeset = needs_modeset(crtc->state);
13751                 struct intel_crtc_state *pipe_config =
13752                         to_intel_crtc_state(crtc->state);
13753                 bool update_pipe = !modeset && pipe_config->update_pipe;
13754
13755                 if (modeset && crtc->state->active) {
13756                         update_scanline_offset(to_intel_crtc(crtc));
13757                         dev_priv->display.crtc_enable(crtc);
13758                 }
13759
13760                 if (!modeset)
13761                         intel_pre_plane_update(to_intel_crtc_state(crtc_state));
13762
13763                 if (crtc->state->active && intel_crtc->atomic.update_fbc)
13764                         intel_fbc_enable(intel_crtc);
13765
13766                 if (crtc->state->active &&
13767                     (crtc->state->planes_changed || update_pipe))
13768                         drm_atomic_helper_commit_planes_on_crtc(crtc_state);
13769
13770                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13771                         crtc_vblank_mask |= 1 << i;
13772         }
13773
13774         /* FIXME: add subpixel order */
13775
13776         if (!state->legacy_cursor_update)
13777                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13778
13779         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13780                 intel_post_plane_update(to_intel_crtc(crtc));
13781
13782                 if (put_domains[i])
13783                         modeset_put_power_domains(dev_priv, put_domains[i]);
13784         }
13785
13786         if (intel_state->modeset)
13787                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13788
13789         /*
13790          * Now that the vblank has passed, we can go ahead and program the
13791          * optimal watermarks on platforms that need two-step watermark
13792          * programming.
13793          *
13794          * TODO: Move this (and other cleanup) to an async worker eventually.
13795          */
13796         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13797                 intel_cstate = to_intel_crtc_state(crtc->state);
13798
13799                 if (dev_priv->display.optimize_watermarks)
13800                         dev_priv->display.optimize_watermarks(intel_cstate);
13801         }
13802
13803         mutex_lock(&dev->struct_mutex);
13804         drm_atomic_helper_cleanup_planes(dev, state);
13805         mutex_unlock(&dev->struct_mutex);
13806
13807         if (hw_check)
13808                 intel_modeset_check_state(dev, state);
13809
13810         drm_atomic_state_free(state);
13811
13812         /* As one of the primary mmio accessors, KMS has a high likelihood
13813          * of triggering bugs in unclaimed access. After we finish
13814          * modesetting, see if an error has been flagged, and if so
13815          * enable debugging for the next modeset - and hope we catch
13816          * the culprit.
13817          *
13818          * XXX note that we assume display power is on at this point.
13819          * This might hold true now but we need to add pm helper to check
13820          * unclaimed only when the hardware is on, as atomic commits
13821          * can happen also when the device is completely off.
13822          */
13823         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13824
13825         return 0;
13826 }
13827
13828 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13829 {
13830         struct drm_device *dev = crtc->dev;
13831         struct drm_atomic_state *state;
13832         struct drm_crtc_state *crtc_state;
13833         int ret;
13834
13835         state = drm_atomic_state_alloc(dev);
13836         if (!state) {
13837                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13838                               crtc->base.id);
13839                 return;
13840         }
13841
13842         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13843
13844 retry:
13845         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13846         ret = PTR_ERR_OR_ZERO(crtc_state);
13847         if (!ret) {
13848                 if (!crtc_state->active)
13849                         goto out;
13850
13851                 crtc_state->mode_changed = true;
13852                 ret = drm_atomic_commit(state);
13853         }
13854
13855         if (ret == -EDEADLK) {
13856                 drm_atomic_state_clear(state);
13857                 drm_modeset_backoff(state->acquire_ctx);
13858                 goto retry;
13859         }
13860
13861         if (ret)
13862 out:
13863                 drm_atomic_state_free(state);
13864 }
13865
13866 #undef for_each_intel_crtc_masked
13867
13868 static const struct drm_crtc_funcs intel_crtc_funcs = {
13869         .gamma_set = intel_crtc_gamma_set,
13870         .set_config = drm_atomic_helper_set_config,
13871         .destroy = intel_crtc_destroy,
13872         .page_flip = intel_crtc_page_flip,
13873         .atomic_duplicate_state = intel_crtc_duplicate_state,
13874         .atomic_destroy_state = intel_crtc_destroy_state,
13875 };
13876
13877 static bool ibx_pch_dpll_get_hw_state(struct drm_i915_private *dev_priv,
13878                                       struct intel_shared_dpll *pll,
13879                                       struct intel_dpll_hw_state *hw_state)
13880 {
13881         uint32_t val;
13882
13883         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_PLLS))
13884                 return false;
13885
13886         val = I915_READ(PCH_DPLL(pll->id));
13887         hw_state->dpll = val;
13888         hw_state->fp0 = I915_READ(PCH_FP0(pll->id));
13889         hw_state->fp1 = I915_READ(PCH_FP1(pll->id));
13890
13891         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
13892
13893         return val & DPLL_VCO_ENABLE;
13894 }
13895
13896 static void ibx_pch_dpll_mode_set(struct drm_i915_private *dev_priv,
13897                                   struct intel_shared_dpll *pll)
13898 {
13899         I915_WRITE(PCH_FP0(pll->id), pll->config.hw_state.fp0);
13900         I915_WRITE(PCH_FP1(pll->id), pll->config.hw_state.fp1);
13901 }
13902
13903 static void ibx_pch_dpll_enable(struct drm_i915_private *dev_priv,
13904                                 struct intel_shared_dpll *pll)
13905 {
13906         /* PCH refclock must be enabled first */
13907         ibx_assert_pch_refclk_enabled(dev_priv);
13908
13909         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13910
13911         /* Wait for the clocks to stabilize. */
13912         POSTING_READ(PCH_DPLL(pll->id));
13913         udelay(150);
13914
13915         /* The pixel multiplier can only be updated once the
13916          * DPLL is enabled and the clocks are stable.
13917          *
13918          * So write it again.
13919          */
13920         I915_WRITE(PCH_DPLL(pll->id), pll->config.hw_state.dpll);
13921         POSTING_READ(PCH_DPLL(pll->id));
13922         udelay(200);
13923 }
13924
13925 static void ibx_pch_dpll_disable(struct drm_i915_private *dev_priv,
13926                                  struct intel_shared_dpll *pll)
13927 {
13928         struct drm_device *dev = dev_priv->dev;
13929         struct intel_crtc *crtc;
13930
13931         /* Make sure no transcoder isn't still depending on us. */
13932         for_each_intel_crtc(dev, crtc) {
13933                 if (intel_crtc_to_shared_dpll(crtc) == pll)
13934                         assert_pch_transcoder_disabled(dev_priv, crtc->pipe);
13935         }
13936
13937         I915_WRITE(PCH_DPLL(pll->id), 0);
13938         POSTING_READ(PCH_DPLL(pll->id));
13939         udelay(200);
13940 }
13941
13942 static char *ibx_pch_dpll_names[] = {
13943         "PCH DPLL A",
13944         "PCH DPLL B",
13945 };
13946
13947 static void ibx_pch_dpll_init(struct drm_device *dev)
13948 {
13949         struct drm_i915_private *dev_priv = dev->dev_private;
13950         int i;
13951
13952         dev_priv->num_shared_dpll = 2;
13953
13954         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13955                 dev_priv->shared_dplls[i].id = i;
13956                 dev_priv->shared_dplls[i].name = ibx_pch_dpll_names[i];
13957                 dev_priv->shared_dplls[i].mode_set = ibx_pch_dpll_mode_set;
13958                 dev_priv->shared_dplls[i].enable = ibx_pch_dpll_enable;
13959                 dev_priv->shared_dplls[i].disable = ibx_pch_dpll_disable;
13960                 dev_priv->shared_dplls[i].get_hw_state =
13961                         ibx_pch_dpll_get_hw_state;
13962         }
13963 }
13964
13965 static void intel_shared_dpll_init(struct drm_device *dev)
13966 {
13967         struct drm_i915_private *dev_priv = dev->dev_private;
13968
13969         if (HAS_DDI(dev))
13970                 intel_ddi_pll_init(dev);
13971         else if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
13972                 ibx_pch_dpll_init(dev);
13973         else
13974                 dev_priv->num_shared_dpll = 0;
13975
13976         BUG_ON(dev_priv->num_shared_dpll > I915_NUM_PLLS);
13977 }
13978
13979 /**
13980  * intel_prepare_plane_fb - Prepare fb for usage on plane
13981  * @plane: drm plane to prepare for
13982  * @fb: framebuffer to prepare for presentation
13983  *
13984  * Prepares a framebuffer for usage on a display plane.  Generally this
13985  * involves pinning the underlying object and updating the frontbuffer tracking
13986  * bits.  Some older platforms need special physical address handling for
13987  * cursor planes.
13988  *
13989  * Must be called with struct_mutex held.
13990  *
13991  * Returns 0 on success, negative error code on failure.
13992  */
13993 int
13994 intel_prepare_plane_fb(struct drm_plane *plane,
13995                        const struct drm_plane_state *new_state)
13996 {
13997         struct drm_device *dev = plane->dev;
13998         struct drm_framebuffer *fb = new_state->fb;
13999         struct intel_plane *intel_plane = to_intel_plane(plane);
14000         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14001         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
14002         int ret = 0;
14003
14004         if (!obj && !old_obj)
14005                 return 0;
14006
14007         if (old_obj) {
14008                 struct drm_crtc_state *crtc_state =
14009                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
14010
14011                 /* Big Hammer, we also need to ensure that any pending
14012                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
14013                  * current scanout is retired before unpinning the old
14014                  * framebuffer. Note that we rely on userspace rendering
14015                  * into the buffer attached to the pipe they are waiting
14016                  * on. If not, userspace generates a GPU hang with IPEHR
14017                  * point to the MI_WAIT_FOR_EVENT.
14018                  *
14019                  * This should only fail upon a hung GPU, in which case we
14020                  * can safely continue.
14021                  */
14022                 if (needs_modeset(crtc_state))
14023                         ret = i915_gem_object_wait_rendering(old_obj, true);
14024
14025                 /* Swallow -EIO errors to allow updates during hw lockup. */
14026                 if (ret && ret != -EIO)
14027                         return ret;
14028         }
14029
14030         /* For framebuffer backed by dmabuf, wait for fence */
14031         if (obj && obj->base.dma_buf) {
14032                 long lret;
14033
14034                 lret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
14035                                                            false, true,
14036                                                            MAX_SCHEDULE_TIMEOUT);
14037                 if (lret == -ERESTARTSYS)
14038                         return lret;
14039
14040                 WARN(lret < 0, "waiting returns %li\n", lret);
14041         }
14042
14043         if (!obj) {
14044                 ret = 0;
14045         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
14046             INTEL_INFO(dev)->cursor_needs_physical) {
14047                 int align = IS_I830(dev) ? 16 * 1024 : 256;
14048                 ret = i915_gem_object_attach_phys(obj, align);
14049                 if (ret)
14050                         DRM_DEBUG_KMS("failed to attach phys object\n");
14051         } else {
14052                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
14053         }
14054
14055         if (ret == 0) {
14056                 if (obj) {
14057                         struct intel_plane_state *plane_state =
14058                                 to_intel_plane_state(new_state);
14059
14060                         i915_gem_request_assign(&plane_state->wait_req,
14061                                                 obj->last_write_req);
14062                 }
14063
14064                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
14065         }
14066
14067         return ret;
14068 }
14069
14070 /**
14071  * intel_cleanup_plane_fb - Cleans up an fb after plane use
14072  * @plane: drm plane to clean up for
14073  * @fb: old framebuffer that was on plane
14074  *
14075  * Cleans up a framebuffer that has just been removed from a plane.
14076  *
14077  * Must be called with struct_mutex held.
14078  */
14079 void
14080 intel_cleanup_plane_fb(struct drm_plane *plane,
14081                        const struct drm_plane_state *old_state)
14082 {
14083         struct drm_device *dev = plane->dev;
14084         struct intel_plane *intel_plane = to_intel_plane(plane);
14085         struct intel_plane_state *old_intel_state;
14086         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
14087         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
14088
14089         old_intel_state = to_intel_plane_state(old_state);
14090
14091         if (!obj && !old_obj)
14092                 return;
14093
14094         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
14095             !INTEL_INFO(dev)->cursor_needs_physical))
14096                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
14097
14098         /* prepare_fb aborted? */
14099         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
14100             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
14101                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
14102
14103         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
14104 }
14105
14106 int
14107 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
14108 {
14109         int max_scale;
14110         struct drm_device *dev;
14111         struct drm_i915_private *dev_priv;
14112         int crtc_clock, cdclk;
14113
14114         if (!intel_crtc || !crtc_state->base.enable)
14115                 return DRM_PLANE_HELPER_NO_SCALING;
14116
14117         dev = intel_crtc->base.dev;
14118         dev_priv = dev->dev_private;
14119         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
14120         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
14121
14122         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
14123                 return DRM_PLANE_HELPER_NO_SCALING;
14124
14125         /*
14126          * skl max scale is lower of:
14127          *    close to 3 but not 3, -1 is for that purpose
14128          *            or
14129          *    cdclk/crtc_clock
14130          */
14131         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
14132
14133         return max_scale;
14134 }
14135
14136 static int
14137 intel_check_primary_plane(struct drm_plane *plane,
14138                           struct intel_crtc_state *crtc_state,
14139                           struct intel_plane_state *state)
14140 {
14141         struct drm_crtc *crtc = state->base.crtc;
14142         struct drm_framebuffer *fb = state->base.fb;
14143         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
14144         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
14145         bool can_position = false;
14146
14147         if (INTEL_INFO(plane->dev)->gen >= 9) {
14148                 /* use scaler when colorkey is not required */
14149                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
14150                         min_scale = 1;
14151                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
14152                 }
14153                 can_position = true;
14154         }
14155
14156         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14157                                              &state->dst, &state->clip,
14158                                              min_scale, max_scale,
14159                                              can_position, true,
14160                                              &state->visible);
14161 }
14162
14163 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
14164                                     struct drm_crtc_state *old_crtc_state)
14165 {
14166         struct drm_device *dev = crtc->dev;
14167         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14168         struct intel_crtc_state *old_intel_state =
14169                 to_intel_crtc_state(old_crtc_state);
14170         bool modeset = needs_modeset(crtc->state);
14171
14172         /* Perform vblank evasion around commit operation */
14173         intel_pipe_update_start(intel_crtc);
14174
14175         if (modeset)
14176                 return;
14177
14178         if (to_intel_crtc_state(crtc->state)->update_pipe)
14179                 intel_update_pipe_config(intel_crtc, old_intel_state);
14180         else if (INTEL_INFO(dev)->gen >= 9)
14181                 skl_detach_scalers(intel_crtc);
14182 }
14183
14184 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
14185                                      struct drm_crtc_state *old_crtc_state)
14186 {
14187         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14188
14189         intel_pipe_update_end(intel_crtc);
14190 }
14191
14192 /**
14193  * intel_plane_destroy - destroy a plane
14194  * @plane: plane to destroy
14195  *
14196  * Common destruction function for all types of planes (primary, cursor,
14197  * sprite).
14198  */
14199 void intel_plane_destroy(struct drm_plane *plane)
14200 {
14201         struct intel_plane *intel_plane = to_intel_plane(plane);
14202         drm_plane_cleanup(plane);
14203         kfree(intel_plane);
14204 }
14205
14206 const struct drm_plane_funcs intel_plane_funcs = {
14207         .update_plane = drm_atomic_helper_update_plane,
14208         .disable_plane = drm_atomic_helper_disable_plane,
14209         .destroy = intel_plane_destroy,
14210         .set_property = drm_atomic_helper_plane_set_property,
14211         .atomic_get_property = intel_plane_atomic_get_property,
14212         .atomic_set_property = intel_plane_atomic_set_property,
14213         .atomic_duplicate_state = intel_plane_duplicate_state,
14214         .atomic_destroy_state = intel_plane_destroy_state,
14215
14216 };
14217
14218 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
14219                                                     int pipe)
14220 {
14221         struct intel_plane *primary;
14222         struct intel_plane_state *state;
14223         const uint32_t *intel_primary_formats;
14224         unsigned int num_formats;
14225
14226         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14227         if (primary == NULL)
14228                 return NULL;
14229
14230         state = intel_create_plane_state(&primary->base);
14231         if (!state) {
14232                 kfree(primary);
14233                 return NULL;
14234         }
14235         primary->base.state = &state->base;
14236
14237         primary->can_scale = false;
14238         primary->max_downscale = 1;
14239         if (INTEL_INFO(dev)->gen >= 9) {
14240                 primary->can_scale = true;
14241                 state->scaler_id = -1;
14242         }
14243         primary->pipe = pipe;
14244         primary->plane = pipe;
14245         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14246         primary->check_plane = intel_check_primary_plane;
14247         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14248                 primary->plane = !pipe;
14249
14250         if (INTEL_INFO(dev)->gen >= 9) {
14251                 intel_primary_formats = skl_primary_formats;
14252                 num_formats = ARRAY_SIZE(skl_primary_formats);
14253
14254                 primary->update_plane = skylake_update_primary_plane;
14255                 primary->disable_plane = skylake_disable_primary_plane;
14256         } else if (HAS_PCH_SPLIT(dev)) {
14257                 intel_primary_formats = i965_primary_formats;
14258                 num_formats = ARRAY_SIZE(i965_primary_formats);
14259
14260                 primary->update_plane = ironlake_update_primary_plane;
14261                 primary->disable_plane = i9xx_disable_primary_plane;
14262         } else if (INTEL_INFO(dev)->gen >= 4) {
14263                 intel_primary_formats = i965_primary_formats;
14264                 num_formats = ARRAY_SIZE(i965_primary_formats);
14265
14266                 primary->update_plane = i9xx_update_primary_plane;
14267                 primary->disable_plane = i9xx_disable_primary_plane;
14268         } else {
14269                 intel_primary_formats = i8xx_primary_formats;
14270                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14271
14272                 primary->update_plane = i9xx_update_primary_plane;
14273                 primary->disable_plane = i9xx_disable_primary_plane;
14274         }
14275
14276         drm_universal_plane_init(dev, &primary->base, 0,
14277                                  &intel_plane_funcs,
14278                                  intel_primary_formats, num_formats,
14279                                  DRM_PLANE_TYPE_PRIMARY, NULL);
14280
14281         if (INTEL_INFO(dev)->gen >= 4)
14282                 intel_create_rotation_property(dev, primary);
14283
14284         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14285
14286         return &primary->base;
14287 }
14288
14289 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14290 {
14291         if (!dev->mode_config.rotation_property) {
14292                 unsigned long flags = BIT(DRM_ROTATE_0) |
14293                         BIT(DRM_ROTATE_180);
14294
14295                 if (INTEL_INFO(dev)->gen >= 9)
14296                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14297
14298                 dev->mode_config.rotation_property =
14299                         drm_mode_create_rotation_property(dev, flags);
14300         }
14301         if (dev->mode_config.rotation_property)
14302                 drm_object_attach_property(&plane->base.base,
14303                                 dev->mode_config.rotation_property,
14304                                 plane->base.state->rotation);
14305 }
14306
14307 static int
14308 intel_check_cursor_plane(struct drm_plane *plane,
14309                          struct intel_crtc_state *crtc_state,
14310                          struct intel_plane_state *state)
14311 {
14312         struct drm_crtc *crtc = crtc_state->base.crtc;
14313         struct drm_framebuffer *fb = state->base.fb;
14314         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14315         enum pipe pipe = to_intel_plane(plane)->pipe;
14316         unsigned stride;
14317         int ret;
14318
14319         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14320                                             &state->dst, &state->clip,
14321                                             DRM_PLANE_HELPER_NO_SCALING,
14322                                             DRM_PLANE_HELPER_NO_SCALING,
14323                                             true, true, &state->visible);
14324         if (ret)
14325                 return ret;
14326
14327         /* if we want to turn off the cursor ignore width and height */
14328         if (!obj)
14329                 return 0;
14330
14331         /* Check for which cursor types we support */
14332         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14333                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14334                           state->base.crtc_w, state->base.crtc_h);
14335                 return -EINVAL;
14336         }
14337
14338         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14339         if (obj->base.size < stride * state->base.crtc_h) {
14340                 DRM_DEBUG_KMS("buffer is too small\n");
14341                 return -ENOMEM;
14342         }
14343
14344         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14345                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14346                 return -EINVAL;
14347         }
14348
14349         /*
14350          * There's something wrong with the cursor on CHV pipe C.
14351          * If it straddles the left edge of the screen then
14352          * moving it away from the edge or disabling it often
14353          * results in a pipe underrun, and often that can lead to
14354          * dead pipe (constant underrun reported, and it scans
14355          * out just a solid color). To recover from that, the
14356          * display power well must be turned off and on again.
14357          * Refuse the put the cursor into that compromised position.
14358          */
14359         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14360             state->visible && state->base.crtc_x < 0) {
14361                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14362                 return -EINVAL;
14363         }
14364
14365         return 0;
14366 }
14367
14368 static void
14369 intel_disable_cursor_plane(struct drm_plane *plane,
14370                            struct drm_crtc *crtc)
14371 {
14372         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14373
14374         intel_crtc->cursor_addr = 0;
14375         intel_crtc_update_cursor(crtc, NULL);
14376 }
14377
14378 static void
14379 intel_update_cursor_plane(struct drm_plane *plane,
14380                           const struct intel_crtc_state *crtc_state,
14381                           const struct intel_plane_state *state)
14382 {
14383         struct drm_crtc *crtc = crtc_state->base.crtc;
14384         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14385         struct drm_device *dev = plane->dev;
14386         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14387         uint32_t addr;
14388
14389         if (!obj)
14390                 addr = 0;
14391         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14392                 addr = i915_gem_obj_ggtt_offset(obj);
14393         else
14394                 addr = obj->phys_handle->busaddr;
14395
14396         intel_crtc->cursor_addr = addr;
14397         intel_crtc_update_cursor(crtc, state);
14398 }
14399
14400 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14401                                                    int pipe)
14402 {
14403         struct intel_plane *cursor;
14404         struct intel_plane_state *state;
14405
14406         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14407         if (cursor == NULL)
14408                 return NULL;
14409
14410         state = intel_create_plane_state(&cursor->base);
14411         if (!state) {
14412                 kfree(cursor);
14413                 return NULL;
14414         }
14415         cursor->base.state = &state->base;
14416
14417         cursor->can_scale = false;
14418         cursor->max_downscale = 1;
14419         cursor->pipe = pipe;
14420         cursor->plane = pipe;
14421         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14422         cursor->check_plane = intel_check_cursor_plane;
14423         cursor->update_plane = intel_update_cursor_plane;
14424         cursor->disable_plane = intel_disable_cursor_plane;
14425
14426         drm_universal_plane_init(dev, &cursor->base, 0,
14427                                  &intel_plane_funcs,
14428                                  intel_cursor_formats,
14429                                  ARRAY_SIZE(intel_cursor_formats),
14430                                  DRM_PLANE_TYPE_CURSOR, NULL);
14431
14432         if (INTEL_INFO(dev)->gen >= 4) {
14433                 if (!dev->mode_config.rotation_property)
14434                         dev->mode_config.rotation_property =
14435                                 drm_mode_create_rotation_property(dev,
14436                                                         BIT(DRM_ROTATE_0) |
14437                                                         BIT(DRM_ROTATE_180));
14438                 if (dev->mode_config.rotation_property)
14439                         drm_object_attach_property(&cursor->base.base,
14440                                 dev->mode_config.rotation_property,
14441                                 state->base.rotation);
14442         }
14443
14444         if (INTEL_INFO(dev)->gen >=9)
14445                 state->scaler_id = -1;
14446
14447         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14448
14449         return &cursor->base;
14450 }
14451
14452 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14453         struct intel_crtc_state *crtc_state)
14454 {
14455         int i;
14456         struct intel_scaler *intel_scaler;
14457         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14458
14459         for (i = 0; i < intel_crtc->num_scalers; i++) {
14460                 intel_scaler = &scaler_state->scalers[i];
14461                 intel_scaler->in_use = 0;
14462                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14463         }
14464
14465         scaler_state->scaler_id = -1;
14466 }
14467
14468 static void intel_crtc_init(struct drm_device *dev, int pipe)
14469 {
14470         struct drm_i915_private *dev_priv = dev->dev_private;
14471         struct intel_crtc *intel_crtc;
14472         struct intel_crtc_state *crtc_state = NULL;
14473         struct drm_plane *primary = NULL;
14474         struct drm_plane *cursor = NULL;
14475         int i, ret;
14476
14477         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14478         if (intel_crtc == NULL)
14479                 return;
14480
14481         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14482         if (!crtc_state)
14483                 goto fail;
14484         intel_crtc->config = crtc_state;
14485         intel_crtc->base.state = &crtc_state->base;
14486         crtc_state->base.crtc = &intel_crtc->base;
14487
14488         /* initialize shared scalers */
14489         if (INTEL_INFO(dev)->gen >= 9) {
14490                 if (pipe == PIPE_C)
14491                         intel_crtc->num_scalers = 1;
14492                 else
14493                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14494
14495                 skl_init_scalers(dev, intel_crtc, crtc_state);
14496         }
14497
14498         primary = intel_primary_plane_create(dev, pipe);
14499         if (!primary)
14500                 goto fail;
14501
14502         cursor = intel_cursor_plane_create(dev, pipe);
14503         if (!cursor)
14504                 goto fail;
14505
14506         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14507                                         cursor, &intel_crtc_funcs, NULL);
14508         if (ret)
14509                 goto fail;
14510
14511         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
14512         for (i = 0; i < 256; i++) {
14513                 intel_crtc->lut_r[i] = i;
14514                 intel_crtc->lut_g[i] = i;
14515                 intel_crtc->lut_b[i] = i;
14516         }
14517
14518         /*
14519          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14520          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14521          */
14522         intel_crtc->pipe = pipe;
14523         intel_crtc->plane = pipe;
14524         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14525                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14526                 intel_crtc->plane = !pipe;
14527         }
14528
14529         intel_crtc->cursor_base = ~0;
14530         intel_crtc->cursor_cntl = ~0;
14531         intel_crtc->cursor_size = ~0;
14532
14533         intel_crtc->wm.cxsr_allowed = true;
14534
14535         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14536                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14537         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14538         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14539
14540         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14541
14542         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14543         return;
14544
14545 fail:
14546         if (primary)
14547                 drm_plane_cleanup(primary);
14548         if (cursor)
14549                 drm_plane_cleanup(cursor);
14550         kfree(crtc_state);
14551         kfree(intel_crtc);
14552 }
14553
14554 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14555 {
14556         struct drm_encoder *encoder = connector->base.encoder;
14557         struct drm_device *dev = connector->base.dev;
14558
14559         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14560
14561         if (!encoder || WARN_ON(!encoder->crtc))
14562                 return INVALID_PIPE;
14563
14564         return to_intel_crtc(encoder->crtc)->pipe;
14565 }
14566
14567 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14568                                 struct drm_file *file)
14569 {
14570         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14571         struct drm_crtc *drmmode_crtc;
14572         struct intel_crtc *crtc;
14573
14574         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14575
14576         if (!drmmode_crtc) {
14577                 DRM_ERROR("no such CRTC id\n");
14578                 return -ENOENT;
14579         }
14580
14581         crtc = to_intel_crtc(drmmode_crtc);
14582         pipe_from_crtc_id->pipe = crtc->pipe;
14583
14584         return 0;
14585 }
14586
14587 static int intel_encoder_clones(struct intel_encoder *encoder)
14588 {
14589         struct drm_device *dev = encoder->base.dev;
14590         struct intel_encoder *source_encoder;
14591         int index_mask = 0;
14592         int entry = 0;
14593
14594         for_each_intel_encoder(dev, source_encoder) {
14595                 if (encoders_cloneable(encoder, source_encoder))
14596                         index_mask |= (1 << entry);
14597
14598                 entry++;
14599         }
14600
14601         return index_mask;
14602 }
14603
14604 static bool has_edp_a(struct drm_device *dev)
14605 {
14606         struct drm_i915_private *dev_priv = dev->dev_private;
14607
14608         if (!IS_MOBILE(dev))
14609                 return false;
14610
14611         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14612                 return false;
14613
14614         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14615                 return false;
14616
14617         return true;
14618 }
14619
14620 static bool intel_crt_present(struct drm_device *dev)
14621 {
14622         struct drm_i915_private *dev_priv = dev->dev_private;
14623
14624         if (INTEL_INFO(dev)->gen >= 9)
14625                 return false;
14626
14627         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14628                 return false;
14629
14630         if (IS_CHERRYVIEW(dev))
14631                 return false;
14632
14633         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14634                 return false;
14635
14636         /* DDI E can't be used if DDI A requires 4 lanes */
14637         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14638                 return false;
14639
14640         if (!dev_priv->vbt.int_crt_support)
14641                 return false;
14642
14643         return true;
14644 }
14645
14646 static void intel_setup_outputs(struct drm_device *dev)
14647 {
14648         struct drm_i915_private *dev_priv = dev->dev_private;
14649         struct intel_encoder *encoder;
14650         bool dpd_is_edp = false;
14651
14652         intel_lvds_init(dev);
14653
14654         if (intel_crt_present(dev))
14655                 intel_crt_init(dev);
14656
14657         if (IS_BROXTON(dev)) {
14658                 /*
14659                  * FIXME: Broxton doesn't support port detection via the
14660                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14661                  * detect the ports.
14662                  */
14663                 intel_ddi_init(dev, PORT_A);
14664                 intel_ddi_init(dev, PORT_B);
14665                 intel_ddi_init(dev, PORT_C);
14666         } else if (HAS_DDI(dev)) {
14667                 int found;
14668
14669                 /*
14670                  * Haswell uses DDI functions to detect digital outputs.
14671                  * On SKL pre-D0 the strap isn't connected, so we assume
14672                  * it's there.
14673                  */
14674                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14675                 /* WaIgnoreDDIAStrap: skl */
14676                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14677                         intel_ddi_init(dev, PORT_A);
14678
14679                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14680                  * register */
14681                 found = I915_READ(SFUSE_STRAP);
14682
14683                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14684                         intel_ddi_init(dev, PORT_B);
14685                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14686                         intel_ddi_init(dev, PORT_C);
14687                 if (found & SFUSE_STRAP_DDID_DETECTED)
14688                         intel_ddi_init(dev, PORT_D);
14689                 /*
14690                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14691                  */
14692                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14693                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14694                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14695                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14696                         intel_ddi_init(dev, PORT_E);
14697
14698         } else if (HAS_PCH_SPLIT(dev)) {
14699                 int found;
14700                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14701
14702                 if (has_edp_a(dev))
14703                         intel_dp_init(dev, DP_A, PORT_A);
14704
14705                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14706                         /* PCH SDVOB multiplex with HDMIB */
14707                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14708                         if (!found)
14709                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14710                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14711                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14712                 }
14713
14714                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14715                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14716
14717                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14718                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14719
14720                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14721                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14722
14723                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14724                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14725         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14726                 /*
14727                  * The DP_DETECTED bit is the latched state of the DDC
14728                  * SDA pin at boot. However since eDP doesn't require DDC
14729                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14730                  * eDP ports may have been muxed to an alternate function.
14731                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14732                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14733                  * detect eDP ports.
14734                  */
14735                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14736                     !intel_dp_is_edp(dev, PORT_B))
14737                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14738                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14739                     intel_dp_is_edp(dev, PORT_B))
14740                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14741
14742                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14743                     !intel_dp_is_edp(dev, PORT_C))
14744                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14745                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14746                     intel_dp_is_edp(dev, PORT_C))
14747                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14748
14749                 if (IS_CHERRYVIEW(dev)) {
14750                         /* eDP not supported on port D, so don't check VBT */
14751                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14752                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14753                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14754                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14755                 }
14756
14757                 intel_dsi_init(dev);
14758         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14759                 bool found = false;
14760
14761                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14762                         DRM_DEBUG_KMS("probing SDVOB\n");
14763                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14764                         if (!found && IS_G4X(dev)) {
14765                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14766                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14767                         }
14768
14769                         if (!found && IS_G4X(dev))
14770                                 intel_dp_init(dev, DP_B, PORT_B);
14771                 }
14772
14773                 /* Before G4X SDVOC doesn't have its own detect register */
14774
14775                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14776                         DRM_DEBUG_KMS("probing SDVOC\n");
14777                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14778                 }
14779
14780                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14781
14782                         if (IS_G4X(dev)) {
14783                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14784                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14785                         }
14786                         if (IS_G4X(dev))
14787                                 intel_dp_init(dev, DP_C, PORT_C);
14788                 }
14789
14790                 if (IS_G4X(dev) &&
14791                     (I915_READ(DP_D) & DP_DETECTED))
14792                         intel_dp_init(dev, DP_D, PORT_D);
14793         } else if (IS_GEN2(dev))
14794                 intel_dvo_init(dev);
14795
14796         if (SUPPORTS_TV(dev))
14797                 intel_tv_init(dev);
14798
14799         intel_psr_init(dev);
14800
14801         for_each_intel_encoder(dev, encoder) {
14802                 encoder->base.possible_crtcs = encoder->crtc_mask;
14803                 encoder->base.possible_clones =
14804                         intel_encoder_clones(encoder);
14805         }
14806
14807         intel_init_pch_refclk(dev);
14808
14809         drm_helper_move_panel_connectors_to_head(dev);
14810 }
14811
14812 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14813 {
14814         struct drm_device *dev = fb->dev;
14815         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14816
14817         drm_framebuffer_cleanup(fb);
14818         mutex_lock(&dev->struct_mutex);
14819         WARN_ON(!intel_fb->obj->framebuffer_references--);
14820         drm_gem_object_unreference(&intel_fb->obj->base);
14821         mutex_unlock(&dev->struct_mutex);
14822         kfree(intel_fb);
14823 }
14824
14825 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14826                                                 struct drm_file *file,
14827                                                 unsigned int *handle)
14828 {
14829         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14830         struct drm_i915_gem_object *obj = intel_fb->obj;
14831
14832         if (obj->userptr.mm) {
14833                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14834                 return -EINVAL;
14835         }
14836
14837         return drm_gem_handle_create(file, &obj->base, handle);
14838 }
14839
14840 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14841                                         struct drm_file *file,
14842                                         unsigned flags, unsigned color,
14843                                         struct drm_clip_rect *clips,
14844                                         unsigned num_clips)
14845 {
14846         struct drm_device *dev = fb->dev;
14847         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14848         struct drm_i915_gem_object *obj = intel_fb->obj;
14849
14850         mutex_lock(&dev->struct_mutex);
14851         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14852         mutex_unlock(&dev->struct_mutex);
14853
14854         return 0;
14855 }
14856
14857 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14858         .destroy = intel_user_framebuffer_destroy,
14859         .create_handle = intel_user_framebuffer_create_handle,
14860         .dirty = intel_user_framebuffer_dirty,
14861 };
14862
14863 static
14864 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14865                          uint32_t pixel_format)
14866 {
14867         u32 gen = INTEL_INFO(dev)->gen;
14868
14869         if (gen >= 9) {
14870                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14871
14872                 /* "The stride in bytes must not exceed the of the size of 8K
14873                  *  pixels and 32K bytes."
14874                  */
14875                 return min(8192 * cpp, 32768);
14876         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14877                 return 32*1024;
14878         } else if (gen >= 4) {
14879                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14880                         return 16*1024;
14881                 else
14882                         return 32*1024;
14883         } else if (gen >= 3) {
14884                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14885                         return 8*1024;
14886                 else
14887                         return 16*1024;
14888         } else {
14889                 /* XXX DSPC is limited to 4k tiled */
14890                 return 8*1024;
14891         }
14892 }
14893
14894 static int intel_framebuffer_init(struct drm_device *dev,
14895                                   struct intel_framebuffer *intel_fb,
14896                                   struct drm_mode_fb_cmd2 *mode_cmd,
14897                                   struct drm_i915_gem_object *obj)
14898 {
14899         struct drm_i915_private *dev_priv = to_i915(dev);
14900         unsigned int aligned_height;
14901         int ret;
14902         u32 pitch_limit, stride_alignment;
14903
14904         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14905
14906         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14907                 /* Enforce that fb modifier and tiling mode match, but only for
14908                  * X-tiled. This is needed for FBC. */
14909                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14910                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14911                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14912                         return -EINVAL;
14913                 }
14914         } else {
14915                 if (obj->tiling_mode == I915_TILING_X)
14916                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14917                 else if (obj->tiling_mode == I915_TILING_Y) {
14918                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14919                         return -EINVAL;
14920                 }
14921         }
14922
14923         /* Passed in modifier sanity checking. */
14924         switch (mode_cmd->modifier[0]) {
14925         case I915_FORMAT_MOD_Y_TILED:
14926         case I915_FORMAT_MOD_Yf_TILED:
14927                 if (INTEL_INFO(dev)->gen < 9) {
14928                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14929                                   mode_cmd->modifier[0]);
14930                         return -EINVAL;
14931                 }
14932         case DRM_FORMAT_MOD_NONE:
14933         case I915_FORMAT_MOD_X_TILED:
14934                 break;
14935         default:
14936                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14937                           mode_cmd->modifier[0]);
14938                 return -EINVAL;
14939         }
14940
14941         stride_alignment = intel_fb_stride_alignment(dev_priv,
14942                                                      mode_cmd->modifier[0],
14943                                                      mode_cmd->pixel_format);
14944         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14945                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14946                           mode_cmd->pitches[0], stride_alignment);
14947                 return -EINVAL;
14948         }
14949
14950         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14951                                            mode_cmd->pixel_format);
14952         if (mode_cmd->pitches[0] > pitch_limit) {
14953                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14954                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14955                           "tiled" : "linear",
14956                           mode_cmd->pitches[0], pitch_limit);
14957                 return -EINVAL;
14958         }
14959
14960         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14961             mode_cmd->pitches[0] != obj->stride) {
14962                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14963                           mode_cmd->pitches[0], obj->stride);
14964                 return -EINVAL;
14965         }
14966
14967         /* Reject formats not supported by any plane early. */
14968         switch (mode_cmd->pixel_format) {
14969         case DRM_FORMAT_C8:
14970         case DRM_FORMAT_RGB565:
14971         case DRM_FORMAT_XRGB8888:
14972         case DRM_FORMAT_ARGB8888:
14973                 break;
14974         case DRM_FORMAT_XRGB1555:
14975                 if (INTEL_INFO(dev)->gen > 3) {
14976                         DRM_DEBUG("unsupported pixel format: %s\n",
14977                                   drm_get_format_name(mode_cmd->pixel_format));
14978                         return -EINVAL;
14979                 }
14980                 break;
14981         case DRM_FORMAT_ABGR8888:
14982                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14983                     INTEL_INFO(dev)->gen < 9) {
14984                         DRM_DEBUG("unsupported pixel format: %s\n",
14985                                   drm_get_format_name(mode_cmd->pixel_format));
14986                         return -EINVAL;
14987                 }
14988                 break;
14989         case DRM_FORMAT_XBGR8888:
14990         case DRM_FORMAT_XRGB2101010:
14991         case DRM_FORMAT_XBGR2101010:
14992                 if (INTEL_INFO(dev)->gen < 4) {
14993                         DRM_DEBUG("unsupported pixel format: %s\n",
14994                                   drm_get_format_name(mode_cmd->pixel_format));
14995                         return -EINVAL;
14996                 }
14997                 break;
14998         case DRM_FORMAT_ABGR2101010:
14999                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
15000                         DRM_DEBUG("unsupported pixel format: %s\n",
15001                                   drm_get_format_name(mode_cmd->pixel_format));
15002                         return -EINVAL;
15003                 }
15004                 break;
15005         case DRM_FORMAT_YUYV:
15006         case DRM_FORMAT_UYVY:
15007         case DRM_FORMAT_YVYU:
15008         case DRM_FORMAT_VYUY:
15009                 if (INTEL_INFO(dev)->gen < 5) {
15010                         DRM_DEBUG("unsupported pixel format: %s\n",
15011                                   drm_get_format_name(mode_cmd->pixel_format));
15012                         return -EINVAL;
15013                 }
15014                 break;
15015         default:
15016                 DRM_DEBUG("unsupported pixel format: %s\n",
15017                           drm_get_format_name(mode_cmd->pixel_format));
15018                 return -EINVAL;
15019         }
15020
15021         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
15022         if (mode_cmd->offsets[0] != 0)
15023                 return -EINVAL;
15024
15025         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
15026                                                mode_cmd->pixel_format,
15027                                                mode_cmd->modifier[0]);
15028         /* FIXME drm helper for size checks (especially planar formats)? */
15029         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
15030                 return -EINVAL;
15031
15032         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
15033         intel_fb->obj = obj;
15034
15035         intel_fill_fb_info(dev_priv, &intel_fb->base);
15036
15037         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
15038         if (ret) {
15039                 DRM_ERROR("framebuffer init failed %d\n", ret);
15040                 return ret;
15041         }
15042
15043         intel_fb->obj->framebuffer_references++;
15044
15045         return 0;
15046 }
15047
15048 static struct drm_framebuffer *
15049 intel_user_framebuffer_create(struct drm_device *dev,
15050                               struct drm_file *filp,
15051                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
15052 {
15053         struct drm_framebuffer *fb;
15054         struct drm_i915_gem_object *obj;
15055         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
15056
15057         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
15058                                                 mode_cmd.handles[0]));
15059         if (&obj->base == NULL)
15060                 return ERR_PTR(-ENOENT);
15061
15062         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
15063         if (IS_ERR(fb))
15064                 drm_gem_object_unreference_unlocked(&obj->base);
15065
15066         return fb;
15067 }
15068
15069 #ifndef CONFIG_DRM_FBDEV_EMULATION
15070 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
15071 {
15072 }
15073 #endif
15074
15075 static const struct drm_mode_config_funcs intel_mode_funcs = {
15076         .fb_create = intel_user_framebuffer_create,
15077         .output_poll_changed = intel_fbdev_output_poll_changed,
15078         .atomic_check = intel_atomic_check,
15079         .atomic_commit = intel_atomic_commit,
15080         .atomic_state_alloc = intel_atomic_state_alloc,
15081         .atomic_state_clear = intel_atomic_state_clear,
15082 };
15083
15084 /* Set up chip specific display functions */
15085 static void intel_init_display(struct drm_device *dev)
15086 {
15087         struct drm_i915_private *dev_priv = dev->dev_private;
15088
15089         if (HAS_PCH_SPLIT(dev) || IS_G4X(dev))
15090                 dev_priv->display.find_dpll = g4x_find_best_dpll;
15091         else if (IS_CHERRYVIEW(dev))
15092                 dev_priv->display.find_dpll = chv_find_best_dpll;
15093         else if (IS_VALLEYVIEW(dev))
15094                 dev_priv->display.find_dpll = vlv_find_best_dpll;
15095         else if (IS_PINEVIEW(dev))
15096                 dev_priv->display.find_dpll = pnv_find_best_dpll;
15097         else
15098                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
15099
15100         if (INTEL_INFO(dev)->gen >= 9) {
15101                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15102                 dev_priv->display.get_initial_plane_config =
15103                         skylake_get_initial_plane_config;
15104                 dev_priv->display.crtc_compute_clock =
15105                         haswell_crtc_compute_clock;
15106                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15107                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15108         } else if (HAS_DDI(dev)) {
15109                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
15110                 dev_priv->display.get_initial_plane_config =
15111                         ironlake_get_initial_plane_config;
15112                 dev_priv->display.crtc_compute_clock =
15113                         haswell_crtc_compute_clock;
15114                 dev_priv->display.crtc_enable = haswell_crtc_enable;
15115                 dev_priv->display.crtc_disable = haswell_crtc_disable;
15116         } else if (HAS_PCH_SPLIT(dev)) {
15117                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
15118                 dev_priv->display.get_initial_plane_config =
15119                         ironlake_get_initial_plane_config;
15120                 dev_priv->display.crtc_compute_clock =
15121                         ironlake_crtc_compute_clock;
15122                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
15123                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
15124         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
15125                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15126                 dev_priv->display.get_initial_plane_config =
15127                         i9xx_get_initial_plane_config;
15128                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15129                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
15130                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15131         } else {
15132                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
15133                 dev_priv->display.get_initial_plane_config =
15134                         i9xx_get_initial_plane_config;
15135                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
15136                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
15137                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
15138         }
15139
15140         /* Returns the core display clock speed */
15141         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
15142                 dev_priv->display.get_display_clock_speed =
15143                         skylake_get_display_clock_speed;
15144         else if (IS_BROXTON(dev))
15145                 dev_priv->display.get_display_clock_speed =
15146                         broxton_get_display_clock_speed;
15147         else if (IS_BROADWELL(dev))
15148                 dev_priv->display.get_display_clock_speed =
15149                         broadwell_get_display_clock_speed;
15150         else if (IS_HASWELL(dev))
15151                 dev_priv->display.get_display_clock_speed =
15152                         haswell_get_display_clock_speed;
15153         else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15154                 dev_priv->display.get_display_clock_speed =
15155                         valleyview_get_display_clock_speed;
15156         else if (IS_GEN5(dev))
15157                 dev_priv->display.get_display_clock_speed =
15158                         ilk_get_display_clock_speed;
15159         else if (IS_I945G(dev) || IS_BROADWATER(dev) ||
15160                  IS_GEN6(dev) || IS_IVYBRIDGE(dev))
15161                 dev_priv->display.get_display_clock_speed =
15162                         i945_get_display_clock_speed;
15163         else if (IS_GM45(dev))
15164                 dev_priv->display.get_display_clock_speed =
15165                         gm45_get_display_clock_speed;
15166         else if (IS_CRESTLINE(dev))
15167                 dev_priv->display.get_display_clock_speed =
15168                         i965gm_get_display_clock_speed;
15169         else if (IS_PINEVIEW(dev))
15170                 dev_priv->display.get_display_clock_speed =
15171                         pnv_get_display_clock_speed;
15172         else if (IS_G33(dev) || IS_G4X(dev))
15173                 dev_priv->display.get_display_clock_speed =
15174                         g33_get_display_clock_speed;
15175         else if (IS_I915G(dev))
15176                 dev_priv->display.get_display_clock_speed =
15177                         i915_get_display_clock_speed;
15178         else if (IS_I945GM(dev) || IS_845G(dev))
15179                 dev_priv->display.get_display_clock_speed =
15180                         i9xx_misc_get_display_clock_speed;
15181         else if (IS_I915GM(dev))
15182                 dev_priv->display.get_display_clock_speed =
15183                         i915gm_get_display_clock_speed;
15184         else if (IS_I865G(dev))
15185                 dev_priv->display.get_display_clock_speed =
15186                         i865_get_display_clock_speed;
15187         else if (IS_I85X(dev))
15188                 dev_priv->display.get_display_clock_speed =
15189                         i85x_get_display_clock_speed;
15190         else { /* 830 */
15191                 WARN(!IS_I830(dev), "Unknown platform. Assuming 133 MHz CDCLK\n");
15192                 dev_priv->display.get_display_clock_speed =
15193                         i830_get_display_clock_speed;
15194         }
15195
15196         if (IS_GEN5(dev)) {
15197                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15198         } else if (IS_GEN6(dev)) {
15199                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15200         } else if (IS_IVYBRIDGE(dev)) {
15201                 /* FIXME: detect B0+ stepping and use auto training */
15202                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15203         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
15204                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15205                 if (IS_BROADWELL(dev)) {
15206                         dev_priv->display.modeset_commit_cdclk =
15207                                 broadwell_modeset_commit_cdclk;
15208                         dev_priv->display.modeset_calc_cdclk =
15209                                 broadwell_modeset_calc_cdclk;
15210                 }
15211         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
15212                 dev_priv->display.modeset_commit_cdclk =
15213                         valleyview_modeset_commit_cdclk;
15214                 dev_priv->display.modeset_calc_cdclk =
15215                         valleyview_modeset_calc_cdclk;
15216         } else if (IS_BROXTON(dev)) {
15217                 dev_priv->display.modeset_commit_cdclk =
15218                         broxton_modeset_commit_cdclk;
15219                 dev_priv->display.modeset_calc_cdclk =
15220                         broxton_modeset_calc_cdclk;
15221         }
15222
15223         switch (INTEL_INFO(dev)->gen) {
15224         case 2:
15225                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15226                 break;
15227
15228         case 3:
15229                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15230                 break;
15231
15232         case 4:
15233         case 5:
15234                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15235                 break;
15236
15237         case 6:
15238                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15239                 break;
15240         case 7:
15241         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15242                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15243                 break;
15244         case 9:
15245                 /* Drop through - unsupported since execlist only. */
15246         default:
15247                 /* Default just returns -ENODEV to indicate unsupported */
15248                 dev_priv->display.queue_flip = intel_default_queue_flip;
15249         }
15250
15251         mutex_init(&dev_priv->pps_mutex);
15252 }
15253
15254 /*
15255  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15256  * resume, or other times.  This quirk makes sure that's the case for
15257  * affected systems.
15258  */
15259 static void quirk_pipea_force(struct drm_device *dev)
15260 {
15261         struct drm_i915_private *dev_priv = dev->dev_private;
15262
15263         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15264         DRM_INFO("applying pipe a force quirk\n");
15265 }
15266
15267 static void quirk_pipeb_force(struct drm_device *dev)
15268 {
15269         struct drm_i915_private *dev_priv = dev->dev_private;
15270
15271         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15272         DRM_INFO("applying pipe b force quirk\n");
15273 }
15274
15275 /*
15276  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15277  */
15278 static void quirk_ssc_force_disable(struct drm_device *dev)
15279 {
15280         struct drm_i915_private *dev_priv = dev->dev_private;
15281         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15282         DRM_INFO("applying lvds SSC disable quirk\n");
15283 }
15284
15285 /*
15286  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15287  * brightness value
15288  */
15289 static void quirk_invert_brightness(struct drm_device *dev)
15290 {
15291         struct drm_i915_private *dev_priv = dev->dev_private;
15292         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15293         DRM_INFO("applying inverted panel brightness quirk\n");
15294 }
15295
15296 /* Some VBT's incorrectly indicate no backlight is present */
15297 static void quirk_backlight_present(struct drm_device *dev)
15298 {
15299         struct drm_i915_private *dev_priv = dev->dev_private;
15300         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15301         DRM_INFO("applying backlight present quirk\n");
15302 }
15303
15304 struct intel_quirk {
15305         int device;
15306         int subsystem_vendor;
15307         int subsystem_device;
15308         void (*hook)(struct drm_device *dev);
15309 };
15310
15311 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15312 struct intel_dmi_quirk {
15313         void (*hook)(struct drm_device *dev);
15314         const struct dmi_system_id (*dmi_id_list)[];
15315 };
15316
15317 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15318 {
15319         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15320         return 1;
15321 }
15322
15323 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15324         {
15325                 .dmi_id_list = &(const struct dmi_system_id[]) {
15326                         {
15327                                 .callback = intel_dmi_reverse_brightness,
15328                                 .ident = "NCR Corporation",
15329                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15330                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15331                                 },
15332                         },
15333                         { }  /* terminating entry */
15334                 },
15335                 .hook = quirk_invert_brightness,
15336         },
15337 };
15338
15339 static struct intel_quirk intel_quirks[] = {
15340         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15341         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15342
15343         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15344         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15345
15346         /* 830 needs to leave pipe A & dpll A up */
15347         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15348
15349         /* 830 needs to leave pipe B & dpll B up */
15350         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15351
15352         /* Lenovo U160 cannot use SSC on LVDS */
15353         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15354
15355         /* Sony Vaio Y cannot use SSC on LVDS */
15356         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15357
15358         /* Acer Aspire 5734Z must invert backlight brightness */
15359         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15360
15361         /* Acer/eMachines G725 */
15362         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15363
15364         /* Acer/eMachines e725 */
15365         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15366
15367         /* Acer/Packard Bell NCL20 */
15368         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15369
15370         /* Acer Aspire 4736Z */
15371         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15372
15373         /* Acer Aspire 5336 */
15374         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15375
15376         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15377         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15378
15379         /* Acer C720 Chromebook (Core i3 4005U) */
15380         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15381
15382         /* Apple Macbook 2,1 (Core 2 T7400) */
15383         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15384
15385         /* Apple Macbook 4,1 */
15386         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15387
15388         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15389         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15390
15391         /* HP Chromebook 14 (Celeron 2955U) */
15392         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15393
15394         /* Dell Chromebook 11 */
15395         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15396
15397         /* Dell Chromebook 11 (2015 version) */
15398         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15399 };
15400
15401 static void intel_init_quirks(struct drm_device *dev)
15402 {
15403         struct pci_dev *d = dev->pdev;
15404         int i;
15405
15406         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15407                 struct intel_quirk *q = &intel_quirks[i];
15408
15409                 if (d->device == q->device &&
15410                     (d->subsystem_vendor == q->subsystem_vendor ||
15411                      q->subsystem_vendor == PCI_ANY_ID) &&
15412                     (d->subsystem_device == q->subsystem_device ||
15413                      q->subsystem_device == PCI_ANY_ID))
15414                         q->hook(dev);
15415         }
15416         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15417                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15418                         intel_dmi_quirks[i].hook(dev);
15419         }
15420 }
15421
15422 /* Disable the VGA plane that we never use */
15423 static void i915_disable_vga(struct drm_device *dev)
15424 {
15425         struct drm_i915_private *dev_priv = dev->dev_private;
15426         u8 sr1;
15427         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15428
15429         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15430         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15431         outb(SR01, VGA_SR_INDEX);
15432         sr1 = inb(VGA_SR_DATA);
15433         outb(sr1 | 1<<5, VGA_SR_DATA);
15434         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15435         udelay(300);
15436
15437         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15438         POSTING_READ(vga_reg);
15439 }
15440
15441 void intel_modeset_init_hw(struct drm_device *dev)
15442 {
15443         struct drm_i915_private *dev_priv = dev->dev_private;
15444
15445         intel_update_cdclk(dev);
15446
15447         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15448
15449         intel_init_clock_gating(dev);
15450         intel_enable_gt_powersave(dev);
15451 }
15452
15453 /*
15454  * Calculate what we think the watermarks should be for the state we've read
15455  * out of the hardware and then immediately program those watermarks so that
15456  * we ensure the hardware settings match our internal state.
15457  *
15458  * We can calculate what we think WM's should be by creating a duplicate of the
15459  * current state (which was constructed during hardware readout) and running it
15460  * through the atomic check code to calculate new watermark values in the
15461  * state object.
15462  */
15463 static void sanitize_watermarks(struct drm_device *dev)
15464 {
15465         struct drm_i915_private *dev_priv = to_i915(dev);
15466         struct drm_atomic_state *state;
15467         struct drm_crtc *crtc;
15468         struct drm_crtc_state *cstate;
15469         struct drm_modeset_acquire_ctx ctx;
15470         int ret;
15471         int i;
15472
15473         /* Only supported on platforms that use atomic watermark design */
15474         if (!dev_priv->display.optimize_watermarks)
15475                 return;
15476
15477         /*
15478          * We need to hold connection_mutex before calling duplicate_state so
15479          * that the connector loop is protected.
15480          */
15481         drm_modeset_acquire_init(&ctx, 0);
15482 retry:
15483         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15484         if (ret == -EDEADLK) {
15485                 drm_modeset_backoff(&ctx);
15486                 goto retry;
15487         } else if (WARN_ON(ret)) {
15488                 goto fail;
15489         }
15490
15491         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15492         if (WARN_ON(IS_ERR(state)))
15493                 goto fail;
15494
15495         /*
15496          * Hardware readout is the only time we don't want to calculate
15497          * intermediate watermarks (since we don't trust the current
15498          * watermarks).
15499          */
15500         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15501
15502         ret = intel_atomic_check(dev, state);
15503         if (ret) {
15504                 /*
15505                  * If we fail here, it means that the hardware appears to be
15506                  * programmed in a way that shouldn't be possible, given our
15507                  * understanding of watermark requirements.  This might mean a
15508                  * mistake in the hardware readout code or a mistake in the
15509                  * watermark calculations for a given platform.  Raise a WARN
15510                  * so that this is noticeable.
15511                  *
15512                  * If this actually happens, we'll have to just leave the
15513                  * BIOS-programmed watermarks untouched and hope for the best.
15514                  */
15515                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15516                 goto fail;
15517         }
15518
15519         /* Write calculated watermark values back */
15520         to_i915(dev)->wm.config = to_intel_atomic_state(state)->wm_config;
15521         for_each_crtc_in_state(state, crtc, cstate, i) {
15522                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15523
15524                 cs->wm.need_postvbl_update = true;
15525                 dev_priv->display.optimize_watermarks(cs);
15526         }
15527
15528         drm_atomic_state_free(state);
15529 fail:
15530         drm_modeset_drop_locks(&ctx);
15531         drm_modeset_acquire_fini(&ctx);
15532 }
15533
15534 void intel_modeset_init(struct drm_device *dev)
15535 {
15536         struct drm_i915_private *dev_priv = dev->dev_private;
15537         int sprite, ret;
15538         enum pipe pipe;
15539         struct intel_crtc *crtc;
15540
15541         drm_mode_config_init(dev);
15542
15543         dev->mode_config.min_width = 0;
15544         dev->mode_config.min_height = 0;
15545
15546         dev->mode_config.preferred_depth = 24;
15547         dev->mode_config.prefer_shadow = 1;
15548
15549         dev->mode_config.allow_fb_modifiers = true;
15550
15551         dev->mode_config.funcs = &intel_mode_funcs;
15552
15553         intel_init_quirks(dev);
15554
15555         intel_init_pm(dev);
15556
15557         if (INTEL_INFO(dev)->num_pipes == 0)
15558                 return;
15559
15560         /*
15561          * There may be no VBT; and if the BIOS enabled SSC we can
15562          * just keep using it to avoid unnecessary flicker.  Whereas if the
15563          * BIOS isn't using it, don't assume it will work even if the VBT
15564          * indicates as much.
15565          */
15566         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15567                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15568                                             DREF_SSC1_ENABLE);
15569
15570                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15571                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15572                                      bios_lvds_use_ssc ? "en" : "dis",
15573                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15574                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15575                 }
15576         }
15577
15578         intel_init_display(dev);
15579         intel_init_audio(dev);
15580
15581         if (IS_GEN2(dev)) {
15582                 dev->mode_config.max_width = 2048;
15583                 dev->mode_config.max_height = 2048;
15584         } else if (IS_GEN3(dev)) {
15585                 dev->mode_config.max_width = 4096;
15586                 dev->mode_config.max_height = 4096;
15587         } else {
15588                 dev->mode_config.max_width = 8192;
15589                 dev->mode_config.max_height = 8192;
15590         }
15591
15592         if (IS_845G(dev) || IS_I865G(dev)) {
15593                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15594                 dev->mode_config.cursor_height = 1023;
15595         } else if (IS_GEN2(dev)) {
15596                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15597                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15598         } else {
15599                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15600                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15601         }
15602
15603         dev->mode_config.fb_base = dev_priv->gtt.mappable_base;
15604
15605         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15606                       INTEL_INFO(dev)->num_pipes,
15607                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15608
15609         for_each_pipe(dev_priv, pipe) {
15610                 intel_crtc_init(dev, pipe);
15611                 for_each_sprite(dev_priv, pipe, sprite) {
15612                         ret = intel_plane_init(dev, pipe, sprite);
15613                         if (ret)
15614                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15615                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15616                 }
15617         }
15618
15619         intel_update_czclk(dev_priv);
15620         intel_update_cdclk(dev);
15621
15622         intel_shared_dpll_init(dev);
15623
15624         /* Just disable it once at startup */
15625         i915_disable_vga(dev);
15626         intel_setup_outputs(dev);
15627
15628         drm_modeset_lock_all(dev);
15629         intel_modeset_setup_hw_state(dev);
15630         drm_modeset_unlock_all(dev);
15631
15632         for_each_intel_crtc(dev, crtc) {
15633                 struct intel_initial_plane_config plane_config = {};
15634
15635                 if (!crtc->active)
15636                         continue;
15637
15638                 /*
15639                  * Note that reserving the BIOS fb up front prevents us
15640                  * from stuffing other stolen allocations like the ring
15641                  * on top.  This prevents some ugliness at boot time, and
15642                  * can even allow for smooth boot transitions if the BIOS
15643                  * fb is large enough for the active pipe configuration.
15644                  */
15645                 dev_priv->display.get_initial_plane_config(crtc,
15646                                                            &plane_config);
15647
15648                 /*
15649                  * If the fb is shared between multiple heads, we'll
15650                  * just get the first one.
15651                  */
15652                 intel_find_initial_plane_obj(crtc, &plane_config);
15653         }
15654
15655         /*
15656          * Make sure hardware watermarks really match the state we read out.
15657          * Note that we need to do this after reconstructing the BIOS fb's
15658          * since the watermark calculation done here will use pstate->fb.
15659          */
15660         sanitize_watermarks(dev);
15661 }
15662
15663 static void intel_enable_pipe_a(struct drm_device *dev)
15664 {
15665         struct intel_connector *connector;
15666         struct drm_connector *crt = NULL;
15667         struct intel_load_detect_pipe load_detect_temp;
15668         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15669
15670         /* We can't just switch on the pipe A, we need to set things up with a
15671          * proper mode and output configuration. As a gross hack, enable pipe A
15672          * by enabling the load detect pipe once. */
15673         for_each_intel_connector(dev, connector) {
15674                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15675                         crt = &connector->base;
15676                         break;
15677                 }
15678         }
15679
15680         if (!crt)
15681                 return;
15682
15683         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15684                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15685 }
15686
15687 static bool
15688 intel_check_plane_mapping(struct intel_crtc *crtc)
15689 {
15690         struct drm_device *dev = crtc->base.dev;
15691         struct drm_i915_private *dev_priv = dev->dev_private;
15692         u32 val;
15693
15694         if (INTEL_INFO(dev)->num_pipes == 1)
15695                 return true;
15696
15697         val = I915_READ(DSPCNTR(!crtc->plane));
15698
15699         if ((val & DISPLAY_PLANE_ENABLE) &&
15700             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15701                 return false;
15702
15703         return true;
15704 }
15705
15706 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15707 {
15708         struct drm_device *dev = crtc->base.dev;
15709         struct intel_encoder *encoder;
15710
15711         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15712                 return true;
15713
15714         return false;
15715 }
15716
15717 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15718 {
15719         struct drm_device *dev = encoder->base.dev;
15720         struct intel_connector *connector;
15721
15722         for_each_connector_on_encoder(dev, &encoder->base, connector)
15723                 return true;
15724
15725         return false;
15726 }
15727
15728 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15729 {
15730         struct drm_device *dev = crtc->base.dev;
15731         struct drm_i915_private *dev_priv = dev->dev_private;
15732         i915_reg_t reg = PIPECONF(crtc->config->cpu_transcoder);
15733
15734         /* Clear any frame start delays used for debugging left by the BIOS */
15735         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15736
15737         /* restore vblank interrupts to correct state */
15738         drm_crtc_vblank_reset(&crtc->base);
15739         if (crtc->active) {
15740                 struct intel_plane *plane;
15741
15742                 drm_crtc_vblank_on(&crtc->base);
15743
15744                 /* Disable everything but the primary plane */
15745                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15746                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15747                                 continue;
15748
15749                         plane->disable_plane(&plane->base, &crtc->base);
15750                 }
15751         }
15752
15753         /* We need to sanitize the plane -> pipe mapping first because this will
15754          * disable the crtc (and hence change the state) if it is wrong. Note
15755          * that gen4+ has a fixed plane -> pipe mapping.  */
15756         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15757                 bool plane;
15758
15759                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15760                               crtc->base.base.id);
15761
15762                 /* Pipe has the wrong plane attached and the plane is active.
15763                  * Temporarily change the plane mapping and disable everything
15764                  * ...  */
15765                 plane = crtc->plane;
15766                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15767                 crtc->plane = !plane;
15768                 intel_crtc_disable_noatomic(&crtc->base);
15769                 crtc->plane = plane;
15770         }
15771
15772         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15773             crtc->pipe == PIPE_A && !crtc->active) {
15774                 /* BIOS forgot to enable pipe A, this mostly happens after
15775                  * resume. Force-enable the pipe to fix this, the update_dpms
15776                  * call below we restore the pipe to the right state, but leave
15777                  * the required bits on. */
15778                 intel_enable_pipe_a(dev);
15779         }
15780
15781         /* Adjust the state of the output pipe according to whether we
15782          * have active connectors/encoders. */
15783         if (!intel_crtc_has_encoders(crtc))
15784                 intel_crtc_disable_noatomic(&crtc->base);
15785
15786         if (crtc->active != crtc->base.state->active) {
15787                 struct intel_encoder *encoder;
15788
15789                 /* This can happen either due to bugs in the get_hw_state
15790                  * functions or because of calls to intel_crtc_disable_noatomic,
15791                  * or because the pipe is force-enabled due to the
15792                  * pipe A quirk. */
15793                 DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was %s, now %s\n",
15794                               crtc->base.base.id,
15795                               crtc->base.state->enable ? "enabled" : "disabled",
15796                               crtc->active ? "enabled" : "disabled");
15797
15798                 WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, NULL) < 0);
15799                 crtc->base.state->active = crtc->active;
15800                 crtc->base.enabled = crtc->active;
15801                 crtc->base.state->connector_mask = 0;
15802                 crtc->base.state->encoder_mask = 0;
15803
15804                 /* Because we only establish the connector -> encoder ->
15805                  * crtc links if something is active, this means the
15806                  * crtc is now deactivated. Break the links. connector
15807                  * -> encoder links are only establish when things are
15808                  *  actually up, hence no need to break them. */
15809                 WARN_ON(crtc->active);
15810
15811                 for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15812                         encoder->base.crtc = NULL;
15813         }
15814
15815         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15816                 /*
15817                  * We start out with underrun reporting disabled to avoid races.
15818                  * For correct bookkeeping mark this on active crtcs.
15819                  *
15820                  * Also on gmch platforms we dont have any hardware bits to
15821                  * disable the underrun reporting. Which means we need to start
15822                  * out with underrun reporting disabled also on inactive pipes,
15823                  * since otherwise we'll complain about the garbage we read when
15824                  * e.g. coming up after runtime pm.
15825                  *
15826                  * No protection against concurrent access is required - at
15827                  * worst a fifo underrun happens which also sets this to false.
15828                  */
15829                 crtc->cpu_fifo_underrun_disabled = true;
15830                 crtc->pch_fifo_underrun_disabled = true;
15831         }
15832 }
15833
15834 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15835 {
15836         struct intel_connector *connector;
15837         struct drm_device *dev = encoder->base.dev;
15838
15839         /* We need to check both for a crtc link (meaning that the
15840          * encoder is active and trying to read from a pipe) and the
15841          * pipe itself being active. */
15842         bool has_active_crtc = encoder->base.crtc &&
15843                 to_intel_crtc(encoder->base.crtc)->active;
15844
15845         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15846                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15847                               encoder->base.base.id,
15848                               encoder->base.name);
15849
15850                 /* Connector is active, but has no active pipe. This is
15851                  * fallout from our resume register restoring. Disable
15852                  * the encoder manually again. */
15853                 if (encoder->base.crtc) {
15854                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15855                                       encoder->base.base.id,
15856                                       encoder->base.name);
15857                         encoder->disable(encoder);
15858                         if (encoder->post_disable)
15859                                 encoder->post_disable(encoder);
15860                 }
15861                 encoder->base.crtc = NULL;
15862
15863                 /* Inconsistent output/port/pipe state happens presumably due to
15864                  * a bug in one of the get_hw_state functions. Or someplace else
15865                  * in our code, like the register restore mess on resume. Clamp
15866                  * things to off as a safer default. */
15867                 for_each_intel_connector(dev, connector) {
15868                         if (connector->encoder != encoder)
15869                                 continue;
15870                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15871                         connector->base.encoder = NULL;
15872                 }
15873         }
15874         /* Enabled encoders without active connectors will be fixed in
15875          * the crtc fixup. */
15876 }
15877
15878 void i915_redisable_vga_power_on(struct drm_device *dev)
15879 {
15880         struct drm_i915_private *dev_priv = dev->dev_private;
15881         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15882
15883         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15884                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15885                 i915_disable_vga(dev);
15886         }
15887 }
15888
15889 void i915_redisable_vga(struct drm_device *dev)
15890 {
15891         struct drm_i915_private *dev_priv = dev->dev_private;
15892
15893         /* This function can be called both from intel_modeset_setup_hw_state or
15894          * at a very early point in our resume sequence, where the power well
15895          * structures are not yet restored. Since this function is at a very
15896          * paranoid "someone might have enabled VGA while we were not looking"
15897          * level, just check if the power well is enabled instead of trying to
15898          * follow the "don't touch the power well if we don't need it" policy
15899          * the rest of the driver uses. */
15900         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15901                 return;
15902
15903         i915_redisable_vga_power_on(dev);
15904
15905         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15906 }
15907
15908 static bool primary_get_hw_state(struct intel_plane *plane)
15909 {
15910         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15911
15912         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15913 }
15914
15915 /* FIXME read out full plane state for all planes */
15916 static void readout_plane_state(struct intel_crtc *crtc)
15917 {
15918         struct drm_plane *primary = crtc->base.primary;
15919         struct intel_plane_state *plane_state =
15920                 to_intel_plane_state(primary->state);
15921
15922         plane_state->visible = crtc->active &&
15923                 primary_get_hw_state(to_intel_plane(primary));
15924
15925         if (plane_state->visible)
15926                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15927 }
15928
15929 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15930 {
15931         struct drm_i915_private *dev_priv = dev->dev_private;
15932         enum pipe pipe;
15933         struct intel_crtc *crtc;
15934         struct intel_encoder *encoder;
15935         struct intel_connector *connector;
15936         int i;
15937
15938         dev_priv->active_crtcs = 0;
15939
15940         for_each_intel_crtc(dev, crtc) {
15941                 struct intel_crtc_state *crtc_state = crtc->config;
15942                 int pixclk = 0;
15943
15944                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, &crtc_state->base);
15945                 memset(crtc_state, 0, sizeof(*crtc_state));
15946                 crtc_state->base.crtc = &crtc->base;
15947
15948                 crtc_state->base.active = crtc_state->base.enable =
15949                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15950
15951                 crtc->base.enabled = crtc_state->base.enable;
15952                 crtc->active = crtc_state->base.active;
15953
15954                 if (crtc_state->base.active) {
15955                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15956
15957                         if (IS_BROADWELL(dev_priv)) {
15958                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15959
15960                                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15961                                 if (crtc_state->ips_enabled)
15962                                         pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15963                         } else if (IS_VALLEYVIEW(dev_priv) ||
15964                                    IS_CHERRYVIEW(dev_priv) ||
15965                                    IS_BROXTON(dev_priv))
15966                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15967                         else
15968                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15969                 }
15970
15971                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15972
15973                 readout_plane_state(crtc);
15974
15975                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15976                               crtc->base.base.id,
15977                               crtc->active ? "enabled" : "disabled");
15978         }
15979
15980         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15981                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15982
15983                 pll->on = pll->get_hw_state(dev_priv, pll,
15984                                             &pll->config.hw_state);
15985                 pll->active = 0;
15986                 pll->config.crtc_mask = 0;
15987                 for_each_intel_crtc(dev, crtc) {
15988                         if (crtc->active && intel_crtc_to_shared_dpll(crtc) == pll) {
15989                                 pll->active++;
15990                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15991                         }
15992                 }
15993
15994                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15995                               pll->name, pll->config.crtc_mask, pll->on);
15996
15997                 if (pll->config.crtc_mask)
15998                         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
15999         }
16000
16001         for_each_intel_encoder(dev, encoder) {
16002                 pipe = 0;
16003
16004                 if (encoder->get_hw_state(encoder, &pipe)) {
16005                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16006                         encoder->base.crtc = &crtc->base;
16007                         encoder->get_config(encoder, crtc->config);
16008                 } else {
16009                         encoder->base.crtc = NULL;
16010                 }
16011
16012                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
16013                               encoder->base.base.id,
16014                               encoder->base.name,
16015                               encoder->base.crtc ? "enabled" : "disabled",
16016                               pipe_name(pipe));
16017         }
16018
16019         for_each_intel_connector(dev, connector) {
16020                 if (connector->get_hw_state(connector)) {
16021                         connector->base.dpms = DRM_MODE_DPMS_ON;
16022
16023                         encoder = connector->encoder;
16024                         connector->base.encoder = &encoder->base;
16025
16026                         if (encoder->base.crtc &&
16027                             encoder->base.crtc->state->active) {
16028                                 /*
16029                                  * This has to be done during hardware readout
16030                                  * because anything calling .crtc_disable may
16031                                  * rely on the connector_mask being accurate.
16032                                  */
16033                                 encoder->base.crtc->state->connector_mask |=
16034                                         1 << drm_connector_index(&connector->base);
16035                                 encoder->base.crtc->state->encoder_mask |=
16036                                         1 << drm_encoder_index(&encoder->base);
16037                         }
16038
16039                 } else {
16040                         connector->base.dpms = DRM_MODE_DPMS_OFF;
16041                         connector->base.encoder = NULL;
16042                 }
16043                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
16044                               connector->base.base.id,
16045                               connector->base.name,
16046                               connector->base.encoder ? "enabled" : "disabled");
16047         }
16048
16049         for_each_intel_crtc(dev, crtc) {
16050                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
16051
16052                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
16053                 if (crtc->base.state->active) {
16054                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
16055                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
16056                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
16057
16058                         /*
16059                          * The initial mode needs to be set in order to keep
16060                          * the atomic core happy. It wants a valid mode if the
16061                          * crtc's enabled, so we do the above call.
16062                          *
16063                          * At this point some state updated by the connectors
16064                          * in their ->detect() callback has not run yet, so
16065                          * no recalculation can be done yet.
16066                          *
16067                          * Even if we could do a recalculation and modeset
16068                          * right now it would cause a double modeset if
16069                          * fbdev or userspace chooses a different initial mode.
16070                          *
16071                          * If that happens, someone indicated they wanted a
16072                          * mode change, which means it's safe to do a full
16073                          * recalculation.
16074                          */
16075                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
16076
16077                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
16078                         update_scanline_offset(crtc);
16079                 }
16080
16081                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
16082         }
16083 }
16084
16085 /* Scan out the current hw modeset state,
16086  * and sanitizes it to the current state
16087  */
16088 static void
16089 intel_modeset_setup_hw_state(struct drm_device *dev)
16090 {
16091         struct drm_i915_private *dev_priv = dev->dev_private;
16092         enum pipe pipe;
16093         struct intel_crtc *crtc;
16094         struct intel_encoder *encoder;
16095         int i;
16096
16097         intel_modeset_readout_hw_state(dev);
16098
16099         /* HW state is read out, now we need to sanitize this mess. */
16100         for_each_intel_encoder(dev, encoder) {
16101                 intel_sanitize_encoder(encoder);
16102         }
16103
16104         for_each_pipe(dev_priv, pipe) {
16105                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
16106                 intel_sanitize_crtc(crtc);
16107                 intel_dump_pipe_config(crtc, crtc->config,
16108                                        "[setup_hw_state]");
16109         }
16110
16111         intel_modeset_update_connector_atomic_state(dev);
16112
16113         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16114                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16115
16116                 if (!pll->on || pll->active)
16117                         continue;
16118
16119                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
16120
16121                 pll->disable(dev_priv, pll);
16122                 pll->on = false;
16123         }
16124
16125         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
16126                 vlv_wm_get_hw_state(dev);
16127         else if (IS_GEN9(dev))
16128                 skl_wm_get_hw_state(dev);
16129         else if (HAS_PCH_SPLIT(dev))
16130                 ilk_wm_get_hw_state(dev);
16131
16132         for_each_intel_crtc(dev, crtc) {
16133                 unsigned long put_domains;
16134
16135                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
16136                 if (WARN_ON(put_domains))
16137                         modeset_put_power_domains(dev_priv, put_domains);
16138         }
16139         intel_display_set_init_power(dev_priv, false);
16140
16141         intel_fbc_init_pipe_state(dev_priv);
16142 }
16143
16144 void intel_display_resume(struct drm_device *dev)
16145 {
16146         struct drm_i915_private *dev_priv = to_i915(dev);
16147         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16148         struct drm_modeset_acquire_ctx ctx;
16149         int ret;
16150         bool setup = false;
16151
16152         dev_priv->modeset_restore_state = NULL;
16153
16154         /*
16155          * This is a cludge because with real atomic modeset mode_config.mutex
16156          * won't be taken. Unfortunately some probed state like
16157          * audio_codec_enable is still protected by mode_config.mutex, so lock
16158          * it here for now.
16159          */
16160         mutex_lock(&dev->mode_config.mutex);
16161         drm_modeset_acquire_init(&ctx, 0);
16162
16163 retry:
16164         ret = drm_modeset_lock_all_ctx(dev, &ctx);
16165
16166         if (ret == 0 && !setup) {
16167                 setup = true;
16168
16169                 intel_modeset_setup_hw_state(dev);
16170                 i915_redisable_vga(dev);
16171         }
16172
16173         if (ret == 0 && state) {
16174                 struct drm_crtc_state *crtc_state;
16175                 struct drm_crtc *crtc;
16176                 int i;
16177
16178                 state->acquire_ctx = &ctx;
16179
16180                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
16181                         /*
16182                          * Force recalculation even if we restore
16183                          * current state. With fast modeset this may not result
16184                          * in a modeset when the state is compatible.
16185                          */
16186                         crtc_state->mode_changed = true;
16187                 }
16188
16189                 ret = drm_atomic_commit(state);
16190         }
16191
16192         if (ret == -EDEADLK) {
16193                 drm_modeset_backoff(&ctx);
16194                 goto retry;
16195         }
16196
16197         drm_modeset_drop_locks(&ctx);
16198         drm_modeset_acquire_fini(&ctx);
16199         mutex_unlock(&dev->mode_config.mutex);
16200
16201         if (ret) {
16202                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16203                 drm_atomic_state_free(state);
16204         }
16205 }
16206
16207 void intel_modeset_gem_init(struct drm_device *dev)
16208 {
16209         struct drm_crtc *c;
16210         struct drm_i915_gem_object *obj;
16211         int ret;
16212
16213         intel_init_gt_powersave(dev);
16214
16215         intel_modeset_init_hw(dev);
16216
16217         intel_setup_overlay(dev);
16218
16219         /*
16220          * Make sure any fbs we allocated at startup are properly
16221          * pinned & fenced.  When we do the allocation it's too early
16222          * for this.
16223          */
16224         for_each_crtc(dev, c) {
16225                 obj = intel_fb_obj(c->primary->fb);
16226                 if (obj == NULL)
16227                         continue;
16228
16229                 mutex_lock(&dev->struct_mutex);
16230                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
16231                                                  c->primary->state->rotation);
16232                 mutex_unlock(&dev->struct_mutex);
16233                 if (ret) {
16234                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
16235                                   to_intel_crtc(c)->pipe);
16236                         drm_framebuffer_unreference(c->primary->fb);
16237                         c->primary->fb = NULL;
16238                         c->primary->crtc = c->primary->state->crtc = NULL;
16239                         update_state_fb(c->primary);
16240                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
16241                 }
16242         }
16243
16244         intel_backlight_register(dev);
16245 }
16246
16247 void intel_connector_unregister(struct intel_connector *intel_connector)
16248 {
16249         struct drm_connector *connector = &intel_connector->base;
16250
16251         intel_panel_destroy_backlight(connector);
16252         drm_connector_unregister(connector);
16253 }
16254
16255 void intel_modeset_cleanup(struct drm_device *dev)
16256 {
16257         struct drm_i915_private *dev_priv = dev->dev_private;
16258         struct intel_connector *connector;
16259
16260         intel_disable_gt_powersave(dev);
16261
16262         intel_backlight_unregister(dev);
16263
16264         /*
16265          * Interrupts and polling as the first thing to avoid creating havoc.
16266          * Too much stuff here (turning of connectors, ...) would
16267          * experience fancy races otherwise.
16268          */
16269         intel_irq_uninstall(dev_priv);
16270
16271         /*
16272          * Due to the hpd irq storm handling the hotplug work can re-arm the
16273          * poll handlers. Hence disable polling after hpd handling is shut down.
16274          */
16275         drm_kms_helper_poll_fini(dev);
16276
16277         intel_unregister_dsm_handler();
16278
16279         intel_fbc_global_disable(dev_priv);
16280
16281         /* flush any delayed tasks or pending work */
16282         flush_scheduled_work();
16283
16284         /* destroy the backlight and sysfs files before encoders/connectors */
16285         for_each_intel_connector(dev, connector)
16286                 connector->unregister(connector);
16287
16288         drm_mode_config_cleanup(dev);
16289
16290         intel_cleanup_overlay(dev);
16291
16292         intel_cleanup_gt_powersave(dev);
16293
16294         intel_teardown_gmbus(dev);
16295 }
16296
16297 /*
16298  * Return which encoder is currently attached for connector.
16299  */
16300 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
16301 {
16302         return &intel_attached_encoder(connector)->base;
16303 }
16304
16305 void intel_connector_attach_encoder(struct intel_connector *connector,
16306                                     struct intel_encoder *encoder)
16307 {
16308         connector->encoder = encoder;
16309         drm_mode_connector_attach_encoder(&connector->base,
16310                                           &encoder->base);
16311 }
16312
16313 /*
16314  * set vga decode state - true == enable VGA decode
16315  */
16316 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16317 {
16318         struct drm_i915_private *dev_priv = dev->dev_private;
16319         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16320         u16 gmch_ctrl;
16321
16322         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16323                 DRM_ERROR("failed to read control word\n");
16324                 return -EIO;
16325         }
16326
16327         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16328                 return 0;
16329
16330         if (state)
16331                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16332         else
16333                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16334
16335         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16336                 DRM_ERROR("failed to write control word\n");
16337                 return -EIO;
16338         }
16339
16340         return 0;
16341 }
16342
16343 struct intel_display_error_state {
16344
16345         u32 power_well_driver;
16346
16347         int num_transcoders;
16348
16349         struct intel_cursor_error_state {
16350                 u32 control;
16351                 u32 position;
16352                 u32 base;
16353                 u32 size;
16354         } cursor[I915_MAX_PIPES];
16355
16356         struct intel_pipe_error_state {
16357                 bool power_domain_on;
16358                 u32 source;
16359                 u32 stat;
16360         } pipe[I915_MAX_PIPES];
16361
16362         struct intel_plane_error_state {
16363                 u32 control;
16364                 u32 stride;
16365                 u32 size;
16366                 u32 pos;
16367                 u32 addr;
16368                 u32 surface;
16369                 u32 tile_offset;
16370         } plane[I915_MAX_PIPES];
16371
16372         struct intel_transcoder_error_state {
16373                 bool power_domain_on;
16374                 enum transcoder cpu_transcoder;
16375
16376                 u32 conf;
16377
16378                 u32 htotal;
16379                 u32 hblank;
16380                 u32 hsync;
16381                 u32 vtotal;
16382                 u32 vblank;
16383                 u32 vsync;
16384         } transcoder[4];
16385 };
16386
16387 struct intel_display_error_state *
16388 intel_display_capture_error_state(struct drm_device *dev)
16389 {
16390         struct drm_i915_private *dev_priv = dev->dev_private;
16391         struct intel_display_error_state *error;
16392         int transcoders[] = {
16393                 TRANSCODER_A,
16394                 TRANSCODER_B,
16395                 TRANSCODER_C,
16396                 TRANSCODER_EDP,
16397         };
16398         int i;
16399
16400         if (INTEL_INFO(dev)->num_pipes == 0)
16401                 return NULL;
16402
16403         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16404         if (error == NULL)
16405                 return NULL;
16406
16407         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16408                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16409
16410         for_each_pipe(dev_priv, i) {
16411                 error->pipe[i].power_domain_on =
16412                         __intel_display_power_is_enabled(dev_priv,
16413                                                          POWER_DOMAIN_PIPE(i));
16414                 if (!error->pipe[i].power_domain_on)
16415                         continue;
16416
16417                 error->cursor[i].control = I915_READ(CURCNTR(i));
16418                 error->cursor[i].position = I915_READ(CURPOS(i));
16419                 error->cursor[i].base = I915_READ(CURBASE(i));
16420
16421                 error->plane[i].control = I915_READ(DSPCNTR(i));
16422                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16423                 if (INTEL_INFO(dev)->gen <= 3) {
16424                         error->plane[i].size = I915_READ(DSPSIZE(i));
16425                         error->plane[i].pos = I915_READ(DSPPOS(i));
16426                 }
16427                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16428                         error->plane[i].addr = I915_READ(DSPADDR(i));
16429                 if (INTEL_INFO(dev)->gen >= 4) {
16430                         error->plane[i].surface = I915_READ(DSPSURF(i));
16431                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16432                 }
16433
16434                 error->pipe[i].source = I915_READ(PIPESRC(i));
16435
16436                 if (HAS_GMCH_DISPLAY(dev))
16437                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16438         }
16439
16440         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
16441         if (HAS_DDI(dev_priv->dev))
16442                 error->num_transcoders++; /* Account for eDP. */
16443
16444         for (i = 0; i < error->num_transcoders; i++) {
16445                 enum transcoder cpu_transcoder = transcoders[i];
16446
16447                 error->transcoder[i].power_domain_on =
16448                         __intel_display_power_is_enabled(dev_priv,
16449                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16450                 if (!error->transcoder[i].power_domain_on)
16451                         continue;
16452
16453                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16454
16455                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16456                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16457                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16458                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16459                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16460                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16461                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16462         }
16463
16464         return error;
16465 }
16466
16467 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16468
16469 void
16470 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16471                                 struct drm_device *dev,
16472                                 struct intel_display_error_state *error)
16473 {
16474         struct drm_i915_private *dev_priv = dev->dev_private;
16475         int i;
16476
16477         if (!error)
16478                 return;
16479
16480         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16481         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16482                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16483                            error->power_well_driver);
16484         for_each_pipe(dev_priv, i) {
16485                 err_printf(m, "Pipe [%d]:\n", i);
16486                 err_printf(m, "  Power: %s\n",
16487                            onoff(error->pipe[i].power_domain_on));
16488                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16489                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16490
16491                 err_printf(m, "Plane [%d]:\n", i);
16492                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16493                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16494                 if (INTEL_INFO(dev)->gen <= 3) {
16495                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16496                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16497                 }
16498                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16499                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16500                 if (INTEL_INFO(dev)->gen >= 4) {
16501                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16502                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16503                 }
16504
16505                 err_printf(m, "Cursor [%d]:\n", i);
16506                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16507                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16508                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16509         }
16510
16511         for (i = 0; i < error->num_transcoders; i++) {
16512                 err_printf(m, "CPU transcoder: %c\n",
16513                            transcoder_name(error->transcoder[i].cpu_transcoder));
16514                 err_printf(m, "  Power: %s\n",
16515                            onoff(error->transcoder[i].power_domain_on));
16516                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16517                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16518                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16519                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16520                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16521                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16522                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16523         }
16524 }