]> git.karo-electronics.de Git - linux-beck.git/blob - drivers/gpu/drm/i915/intel_display.c
drm/i915: Remove stallcheck special handling, v3.
[linux-beck.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 "intel_dsi.h"
40 #include "i915_trace.h"
41 #include <drm/drm_atomic.h>
42 #include <drm/drm_atomic_helper.h>
43 #include <drm/drm_dp_helper.h>
44 #include <drm/drm_crtc_helper.h>
45 #include <drm/drm_plane_helper.h>
46 #include <drm/drm_rect.h>
47 #include <linux/dma_remapping.h>
48 #include <linux/reservation.h>
49 #include <linux/dma-buf.h>
50
51 /* Primary plane formats for gen <= 3 */
52 static const uint32_t i8xx_primary_formats[] = {
53         DRM_FORMAT_C8,
54         DRM_FORMAT_RGB565,
55         DRM_FORMAT_XRGB1555,
56         DRM_FORMAT_XRGB8888,
57 };
58
59 /* Primary plane formats for gen >= 4 */
60 static const uint32_t i965_primary_formats[] = {
61         DRM_FORMAT_C8,
62         DRM_FORMAT_RGB565,
63         DRM_FORMAT_XRGB8888,
64         DRM_FORMAT_XBGR8888,
65         DRM_FORMAT_XRGB2101010,
66         DRM_FORMAT_XBGR2101010,
67 };
68
69 static const uint32_t skl_primary_formats[] = {
70         DRM_FORMAT_C8,
71         DRM_FORMAT_RGB565,
72         DRM_FORMAT_XRGB8888,
73         DRM_FORMAT_XBGR8888,
74         DRM_FORMAT_ARGB8888,
75         DRM_FORMAT_ABGR8888,
76         DRM_FORMAT_XRGB2101010,
77         DRM_FORMAT_XBGR2101010,
78         DRM_FORMAT_YUYV,
79         DRM_FORMAT_YVYU,
80         DRM_FORMAT_UYVY,
81         DRM_FORMAT_VYUY,
82 };
83
84 /* Cursor formats */
85 static const uint32_t intel_cursor_formats[] = {
86         DRM_FORMAT_ARGB8888,
87 };
88
89 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
90                                 struct intel_crtc_state *pipe_config);
91 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
92                                    struct intel_crtc_state *pipe_config);
93
94 static int intel_framebuffer_init(struct drm_device *dev,
95                                   struct intel_framebuffer *ifb,
96                                   struct drm_mode_fb_cmd2 *mode_cmd,
97                                   struct drm_i915_gem_object *obj);
98 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
99 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
100 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
101 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
102                                          struct intel_link_m_n *m_n,
103                                          struct intel_link_m_n *m2_n2);
104 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
105 static void haswell_set_pipeconf(struct drm_crtc *crtc);
106 static void haswell_set_pipemisc(struct drm_crtc *crtc);
107 static void vlv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void chv_prepare_pll(struct intel_crtc *crtc,
110                             const struct intel_crtc_state *pipe_config);
111 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
112 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
113 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
114         struct intel_crtc_state *crtc_state);
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_noatomic(struct drm_crtc *crtc);
120 static int ilk_max_pixel_rate(struct drm_atomic_state *state);
121
122 struct intel_limit {
123         struct {
124                 int min, max;
125         } dot, vco, n, m, m1, m2, p, p1;
126
127         struct {
128                 int dot_limit;
129                 int p2_slow, p2_fast;
130         } p2;
131 };
132
133 /* returns HPLL frequency in kHz */
134 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
135 {
136         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
137
138         /* Obtain SKU information */
139         mutex_lock(&dev_priv->sb_lock);
140         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
141                 CCK_FUSE_HPLL_FREQ_MASK;
142         mutex_unlock(&dev_priv->sb_lock);
143
144         return vco_freq[hpll_freq] * 1000;
145 }
146
147 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
148                       const char *name, u32 reg, int ref_freq)
149 {
150         u32 val;
151         int divider;
152
153         mutex_lock(&dev_priv->sb_lock);
154         val = vlv_cck_read(dev_priv, reg);
155         mutex_unlock(&dev_priv->sb_lock);
156
157         divider = val & CCK_FREQUENCY_VALUES;
158
159         WARN((val & CCK_FREQUENCY_STATUS) !=
160              (divider << CCK_FREQUENCY_STATUS_SHIFT),
161              "%s change in progress\n", name);
162
163         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
164 }
165
166 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
167                                   const char *name, u32 reg)
168 {
169         if (dev_priv->hpll_freq == 0)
170                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
171
172         return vlv_get_cck_clock(dev_priv, name, reg,
173                                  dev_priv->hpll_freq);
174 }
175
176 static int
177 intel_pch_rawclk(struct drm_i915_private *dev_priv)
178 {
179         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
180 }
181
182 static int
183 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
184 {
185         /* RAWCLK_FREQ_VLV register updated from power well code */
186         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
187                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
188 }
189
190 static int
191 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
192 {
193         uint32_t clkcfg;
194
195         /* hrawclock is 1/4 the FSB frequency */
196         clkcfg = I915_READ(CLKCFG);
197         switch (clkcfg & CLKCFG_FSB_MASK) {
198         case CLKCFG_FSB_400:
199                 return 100000;
200         case CLKCFG_FSB_533:
201                 return 133333;
202         case CLKCFG_FSB_667:
203                 return 166667;
204         case CLKCFG_FSB_800:
205                 return 200000;
206         case CLKCFG_FSB_1067:
207                 return 266667;
208         case CLKCFG_FSB_1333:
209                 return 333333;
210         /* these two are just a guess; one of them might be right */
211         case CLKCFG_FSB_1600:
212         case CLKCFG_FSB_1600_ALT:
213                 return 400000;
214         default:
215                 return 133333;
216         }
217 }
218
219 void intel_update_rawclk(struct drm_i915_private *dev_priv)
220 {
221         if (HAS_PCH_SPLIT(dev_priv))
222                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
223         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
224                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
225         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
226                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
227         else
228                 return; /* no rawclk on other platforms, or no need to know it */
229
230         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
231 }
232
233 static void intel_update_czclk(struct drm_i915_private *dev_priv)
234 {
235         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
236                 return;
237
238         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
239                                                       CCK_CZ_CLOCK_CONTROL);
240
241         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
242 }
243
244 static inline u32 /* units of 100MHz */
245 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
246                     const struct intel_crtc_state *pipe_config)
247 {
248         if (HAS_DDI(dev_priv))
249                 return pipe_config->port_clock; /* SPLL */
250         else if (IS_GEN5(dev_priv))
251                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
252         else
253                 return 270000;
254 }
255
256 static const struct intel_limit intel_limits_i8xx_dac = {
257         .dot = { .min = 25000, .max = 350000 },
258         .vco = { .min = 908000, .max = 1512000 },
259         .n = { .min = 2, .max = 16 },
260         .m = { .min = 96, .max = 140 },
261         .m1 = { .min = 18, .max = 26 },
262         .m2 = { .min = 6, .max = 16 },
263         .p = { .min = 4, .max = 128 },
264         .p1 = { .min = 2, .max = 33 },
265         .p2 = { .dot_limit = 165000,
266                 .p2_slow = 4, .p2_fast = 2 },
267 };
268
269 static const struct intel_limit intel_limits_i8xx_dvo = {
270         .dot = { .min = 25000, .max = 350000 },
271         .vco = { .min = 908000, .max = 1512000 },
272         .n = { .min = 2, .max = 16 },
273         .m = { .min = 96, .max = 140 },
274         .m1 = { .min = 18, .max = 26 },
275         .m2 = { .min = 6, .max = 16 },
276         .p = { .min = 4, .max = 128 },
277         .p1 = { .min = 2, .max = 33 },
278         .p2 = { .dot_limit = 165000,
279                 .p2_slow = 4, .p2_fast = 4 },
280 };
281
282 static const struct intel_limit intel_limits_i8xx_lvds = {
283         .dot = { .min = 25000, .max = 350000 },
284         .vco = { .min = 908000, .max = 1512000 },
285         .n = { .min = 2, .max = 16 },
286         .m = { .min = 96, .max = 140 },
287         .m1 = { .min = 18, .max = 26 },
288         .m2 = { .min = 6, .max = 16 },
289         .p = { .min = 4, .max = 128 },
290         .p1 = { .min = 1, .max = 6 },
291         .p2 = { .dot_limit = 165000,
292                 .p2_slow = 14, .p2_fast = 7 },
293 };
294
295 static const struct intel_limit intel_limits_i9xx_sdvo = {
296         .dot = { .min = 20000, .max = 400000 },
297         .vco = { .min = 1400000, .max = 2800000 },
298         .n = { .min = 1, .max = 6 },
299         .m = { .min = 70, .max = 120 },
300         .m1 = { .min = 8, .max = 18 },
301         .m2 = { .min = 3, .max = 7 },
302         .p = { .min = 5, .max = 80 },
303         .p1 = { .min = 1, .max = 8 },
304         .p2 = { .dot_limit = 200000,
305                 .p2_slow = 10, .p2_fast = 5 },
306 };
307
308 static const struct intel_limit intel_limits_i9xx_lvds = {
309         .dot = { .min = 20000, .max = 400000 },
310         .vco = { .min = 1400000, .max = 2800000 },
311         .n = { .min = 1, .max = 6 },
312         .m = { .min = 70, .max = 120 },
313         .m1 = { .min = 8, .max = 18 },
314         .m2 = { .min = 3, .max = 7 },
315         .p = { .min = 7, .max = 98 },
316         .p1 = { .min = 1, .max = 8 },
317         .p2 = { .dot_limit = 112000,
318                 .p2_slow = 14, .p2_fast = 7 },
319 };
320
321
322 static const struct intel_limit intel_limits_g4x_sdvo = {
323         .dot = { .min = 25000, .max = 270000 },
324         .vco = { .min = 1750000, .max = 3500000},
325         .n = { .min = 1, .max = 4 },
326         .m = { .min = 104, .max = 138 },
327         .m1 = { .min = 17, .max = 23 },
328         .m2 = { .min = 5, .max = 11 },
329         .p = { .min = 10, .max = 30 },
330         .p1 = { .min = 1, .max = 3},
331         .p2 = { .dot_limit = 270000,
332                 .p2_slow = 10,
333                 .p2_fast = 10
334         },
335 };
336
337 static const struct intel_limit intel_limits_g4x_hdmi = {
338         .dot = { .min = 22000, .max = 400000 },
339         .vco = { .min = 1750000, .max = 3500000},
340         .n = { .min = 1, .max = 4 },
341         .m = { .min = 104, .max = 138 },
342         .m1 = { .min = 16, .max = 23 },
343         .m2 = { .min = 5, .max = 11 },
344         .p = { .min = 5, .max = 80 },
345         .p1 = { .min = 1, .max = 8},
346         .p2 = { .dot_limit = 165000,
347                 .p2_slow = 10, .p2_fast = 5 },
348 };
349
350 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
351         .dot = { .min = 20000, .max = 115000 },
352         .vco = { .min = 1750000, .max = 3500000 },
353         .n = { .min = 1, .max = 3 },
354         .m = { .min = 104, .max = 138 },
355         .m1 = { .min = 17, .max = 23 },
356         .m2 = { .min = 5, .max = 11 },
357         .p = { .min = 28, .max = 112 },
358         .p1 = { .min = 2, .max = 8 },
359         .p2 = { .dot_limit = 0,
360                 .p2_slow = 14, .p2_fast = 14
361         },
362 };
363
364 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
365         .dot = { .min = 80000, .max = 224000 },
366         .vco = { .min = 1750000, .max = 3500000 },
367         .n = { .min = 1, .max = 3 },
368         .m = { .min = 104, .max = 138 },
369         .m1 = { .min = 17, .max = 23 },
370         .m2 = { .min = 5, .max = 11 },
371         .p = { .min = 14, .max = 42 },
372         .p1 = { .min = 2, .max = 6 },
373         .p2 = { .dot_limit = 0,
374                 .p2_slow = 7, .p2_fast = 7
375         },
376 };
377
378 static const struct intel_limit intel_limits_pineview_sdvo = {
379         .dot = { .min = 20000, .max = 400000},
380         .vco = { .min = 1700000, .max = 3500000 },
381         /* Pineview's Ncounter is a ring counter */
382         .n = { .min = 3, .max = 6 },
383         .m = { .min = 2, .max = 256 },
384         /* Pineview only has one combined m divider, which we treat as m2. */
385         .m1 = { .min = 0, .max = 0 },
386         .m2 = { .min = 0, .max = 254 },
387         .p = { .min = 5, .max = 80 },
388         .p1 = { .min = 1, .max = 8 },
389         .p2 = { .dot_limit = 200000,
390                 .p2_slow = 10, .p2_fast = 5 },
391 };
392
393 static const struct intel_limit intel_limits_pineview_lvds = {
394         .dot = { .min = 20000, .max = 400000 },
395         .vco = { .min = 1700000, .max = 3500000 },
396         .n = { .min = 3, .max = 6 },
397         .m = { .min = 2, .max = 256 },
398         .m1 = { .min = 0, .max = 0 },
399         .m2 = { .min = 0, .max = 254 },
400         .p = { .min = 7, .max = 112 },
401         .p1 = { .min = 1, .max = 8 },
402         .p2 = { .dot_limit = 112000,
403                 .p2_slow = 14, .p2_fast = 14 },
404 };
405
406 /* Ironlake / Sandybridge
407  *
408  * We calculate clock using (register_value + 2) for N/M1/M2, so here
409  * the range value for them is (actual_value - 2).
410  */
411 static const struct intel_limit intel_limits_ironlake_dac = {
412         .dot = { .min = 25000, .max = 350000 },
413         .vco = { .min = 1760000, .max = 3510000 },
414         .n = { .min = 1, .max = 5 },
415         .m = { .min = 79, .max = 127 },
416         .m1 = { .min = 12, .max = 22 },
417         .m2 = { .min = 5, .max = 9 },
418         .p = { .min = 5, .max = 80 },
419         .p1 = { .min = 1, .max = 8 },
420         .p2 = { .dot_limit = 225000,
421                 .p2_slow = 10, .p2_fast = 5 },
422 };
423
424 static const struct intel_limit intel_limits_ironlake_single_lvds = {
425         .dot = { .min = 25000, .max = 350000 },
426         .vco = { .min = 1760000, .max = 3510000 },
427         .n = { .min = 1, .max = 3 },
428         .m = { .min = 79, .max = 118 },
429         .m1 = { .min = 12, .max = 22 },
430         .m2 = { .min = 5, .max = 9 },
431         .p = { .min = 28, .max = 112 },
432         .p1 = { .min = 2, .max = 8 },
433         .p2 = { .dot_limit = 225000,
434                 .p2_slow = 14, .p2_fast = 14 },
435 };
436
437 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
438         .dot = { .min = 25000, .max = 350000 },
439         .vco = { .min = 1760000, .max = 3510000 },
440         .n = { .min = 1, .max = 3 },
441         .m = { .min = 79, .max = 127 },
442         .m1 = { .min = 12, .max = 22 },
443         .m2 = { .min = 5, .max = 9 },
444         .p = { .min = 14, .max = 56 },
445         .p1 = { .min = 2, .max = 8 },
446         .p2 = { .dot_limit = 225000,
447                 .p2_slow = 7, .p2_fast = 7 },
448 };
449
450 /* LVDS 100mhz refclk limits. */
451 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
452         .dot = { .min = 25000, .max = 350000 },
453         .vco = { .min = 1760000, .max = 3510000 },
454         .n = { .min = 1, .max = 2 },
455         .m = { .min = 79, .max = 126 },
456         .m1 = { .min = 12, .max = 22 },
457         .m2 = { .min = 5, .max = 9 },
458         .p = { .min = 28, .max = 112 },
459         .p1 = { .min = 2, .max = 8 },
460         .p2 = { .dot_limit = 225000,
461                 .p2_slow = 14, .p2_fast = 14 },
462 };
463
464 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
465         .dot = { .min = 25000, .max = 350000 },
466         .vco = { .min = 1760000, .max = 3510000 },
467         .n = { .min = 1, .max = 3 },
468         .m = { .min = 79, .max = 126 },
469         .m1 = { .min = 12, .max = 22 },
470         .m2 = { .min = 5, .max = 9 },
471         .p = { .min = 14, .max = 42 },
472         .p1 = { .min = 2, .max = 6 },
473         .p2 = { .dot_limit = 225000,
474                 .p2_slow = 7, .p2_fast = 7 },
475 };
476
477 static const struct intel_limit intel_limits_vlv = {
478          /*
479           * These are the data rate limits (measured in fast clocks)
480           * since those are the strictest limits we have. The fast
481           * clock and actual rate limits are more relaxed, so checking
482           * them would make no difference.
483           */
484         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
485         .vco = { .min = 4000000, .max = 6000000 },
486         .n = { .min = 1, .max = 7 },
487         .m1 = { .min = 2, .max = 3 },
488         .m2 = { .min = 11, .max = 156 },
489         .p1 = { .min = 2, .max = 3 },
490         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
491 };
492
493 static const struct intel_limit intel_limits_chv = {
494         /*
495          * These are the data rate limits (measured in fast clocks)
496          * since those are the strictest limits we have.  The fast
497          * clock and actual rate limits are more relaxed, so checking
498          * them would make no difference.
499          */
500         .dot = { .min = 25000 * 5, .max = 540000 * 5},
501         .vco = { .min = 4800000, .max = 6480000 },
502         .n = { .min = 1, .max = 1 },
503         .m1 = { .min = 2, .max = 2 },
504         .m2 = { .min = 24 << 22, .max = 175 << 22 },
505         .p1 = { .min = 2, .max = 4 },
506         .p2 = { .p2_slow = 1, .p2_fast = 14 },
507 };
508
509 static const struct intel_limit intel_limits_bxt = {
510         /* FIXME: find real dot limits */
511         .dot = { .min = 0, .max = INT_MAX },
512         .vco = { .min = 4800000, .max = 6700000 },
513         .n = { .min = 1, .max = 1 },
514         .m1 = { .min = 2, .max = 2 },
515         /* FIXME: find real m2 limits */
516         .m2 = { .min = 2 << 22, .max = 255 << 22 },
517         .p1 = { .min = 2, .max = 4 },
518         .p2 = { .p2_slow = 1, .p2_fast = 20 },
519 };
520
521 static bool
522 needs_modeset(struct drm_crtc_state *state)
523 {
524         return drm_atomic_crtc_needs_modeset(state);
525 }
526
527 /**
528  * Returns whether any output on the specified pipe is of the specified type
529  */
530 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
531 {
532         struct drm_device *dev = crtc->base.dev;
533         struct intel_encoder *encoder;
534
535         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
536                 if (encoder->type == type)
537                         return true;
538
539         return false;
540 }
541
542 /**
543  * Returns whether any output on the specified pipe will have the specified
544  * type after a staged modeset is complete, i.e., the same as
545  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
546  * encoder->crtc.
547  */
548 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
549                                       int type)
550 {
551         struct drm_atomic_state *state = crtc_state->base.state;
552         struct drm_connector *connector;
553         struct drm_connector_state *connector_state;
554         struct intel_encoder *encoder;
555         int i, num_connectors = 0;
556
557         for_each_connector_in_state(state, connector, connector_state, i) {
558                 if (connector_state->crtc != crtc_state->base.crtc)
559                         continue;
560
561                 num_connectors++;
562
563                 encoder = to_intel_encoder(connector_state->best_encoder);
564                 if (encoder->type == type)
565                         return true;
566         }
567
568         WARN_ON(num_connectors == 0);
569
570         return false;
571 }
572
573 /*
574  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
575  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
576  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
577  * The helpers' return value is the rate of the clock that is fed to the
578  * display engine's pipe which can be the above fast dot clock rate or a
579  * divided-down version of it.
580  */
581 /* m1 is reserved as 0 in Pineview, n is a ring counter */
582 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
583 {
584         clock->m = clock->m2 + 2;
585         clock->p = clock->p1 * clock->p2;
586         if (WARN_ON(clock->n == 0 || clock->p == 0))
587                 return 0;
588         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
589         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
590
591         return clock->dot;
592 }
593
594 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
595 {
596         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
597 }
598
599 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
600 {
601         clock->m = i9xx_dpll_compute_m(clock);
602         clock->p = clock->p1 * clock->p2;
603         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
604                 return 0;
605         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
606         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
607
608         return clock->dot;
609 }
610
611 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
612 {
613         clock->m = clock->m1 * clock->m2;
614         clock->p = clock->p1 * clock->p2;
615         if (WARN_ON(clock->n == 0 || clock->p == 0))
616                 return 0;
617         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
618         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
619
620         return clock->dot / 5;
621 }
622
623 int chv_calc_dpll_params(int refclk, struct dpll *clock)
624 {
625         clock->m = clock->m1 * clock->m2;
626         clock->p = clock->p1 * clock->p2;
627         if (WARN_ON(clock->n == 0 || clock->p == 0))
628                 return 0;
629         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
630                         clock->n << 22);
631         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
632
633         return clock->dot / 5;
634 }
635
636 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
637 /**
638  * Returns whether the given set of divisors are valid for a given refclk with
639  * the given connectors.
640  */
641
642 static bool intel_PLL_is_valid(struct drm_device *dev,
643                                const struct intel_limit *limit,
644                                const struct dpll *clock)
645 {
646         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
647                 INTELPllInvalid("n out of range\n");
648         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
649                 INTELPllInvalid("p1 out of range\n");
650         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
651                 INTELPllInvalid("m2 out of range\n");
652         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
653                 INTELPllInvalid("m1 out of range\n");
654
655         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
656             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
657                 if (clock->m1 <= clock->m2)
658                         INTELPllInvalid("m1 <= m2\n");
659
660         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
661                 if (clock->p < limit->p.min || limit->p.max < clock->p)
662                         INTELPllInvalid("p out of range\n");
663                 if (clock->m < limit->m.min || limit->m.max < clock->m)
664                         INTELPllInvalid("m out of range\n");
665         }
666
667         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
668                 INTELPllInvalid("vco out of range\n");
669         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
670          * connector, etc., rather than just a single range.
671          */
672         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
673                 INTELPllInvalid("dot out of range\n");
674
675         return true;
676 }
677
678 static int
679 i9xx_select_p2_div(const struct intel_limit *limit,
680                    const struct intel_crtc_state *crtc_state,
681                    int target)
682 {
683         struct drm_device *dev = crtc_state->base.crtc->dev;
684
685         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
686                 /*
687                  * For LVDS just rely on its current settings for dual-channel.
688                  * We haven't figured out how to reliably set up different
689                  * single/dual channel state, if we even can.
690                  */
691                 if (intel_is_dual_link_lvds(dev))
692                         return limit->p2.p2_fast;
693                 else
694                         return limit->p2.p2_slow;
695         } else {
696                 if (target < limit->p2.dot_limit)
697                         return limit->p2.p2_slow;
698                 else
699                         return limit->p2.p2_fast;
700         }
701 }
702
703 /*
704  * Returns a set of divisors for the desired target clock with the given
705  * refclk, or FALSE.  The returned values represent the clock equation:
706  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
707  *
708  * Target and reference clocks are specified in kHz.
709  *
710  * If match_clock is provided, then best_clock P divider must match the P
711  * divider from @match_clock used for LVDS downclocking.
712  */
713 static bool
714 i9xx_find_best_dpll(const struct intel_limit *limit,
715                     struct intel_crtc_state *crtc_state,
716                     int target, int refclk, struct dpll *match_clock,
717                     struct dpll *best_clock)
718 {
719         struct drm_device *dev = crtc_state->base.crtc->dev;
720         struct dpll clock;
721         int err = target;
722
723         memset(best_clock, 0, sizeof(*best_clock));
724
725         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
726
727         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
728              clock.m1++) {
729                 for (clock.m2 = limit->m2.min;
730                      clock.m2 <= limit->m2.max; clock.m2++) {
731                         if (clock.m2 >= clock.m1)
732                                 break;
733                         for (clock.n = limit->n.min;
734                              clock.n <= limit->n.max; clock.n++) {
735                                 for (clock.p1 = limit->p1.min;
736                                         clock.p1 <= limit->p1.max; clock.p1++) {
737                                         int this_err;
738
739                                         i9xx_calc_dpll_params(refclk, &clock);
740                                         if (!intel_PLL_is_valid(dev, limit,
741                                                                 &clock))
742                                                 continue;
743                                         if (match_clock &&
744                                             clock.p != match_clock->p)
745                                                 continue;
746
747                                         this_err = abs(clock.dot - target);
748                                         if (this_err < err) {
749                                                 *best_clock = clock;
750                                                 err = this_err;
751                                         }
752                                 }
753                         }
754                 }
755         }
756
757         return (err != target);
758 }
759
760 /*
761  * Returns a set of divisors for the desired target clock with the given
762  * refclk, or FALSE.  The returned values represent the clock equation:
763  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
764  *
765  * Target and reference clocks are specified in kHz.
766  *
767  * If match_clock is provided, then best_clock P divider must match the P
768  * divider from @match_clock used for LVDS downclocking.
769  */
770 static bool
771 pnv_find_best_dpll(const struct intel_limit *limit,
772                    struct intel_crtc_state *crtc_state,
773                    int target, int refclk, struct dpll *match_clock,
774                    struct dpll *best_clock)
775 {
776         struct drm_device *dev = crtc_state->base.crtc->dev;
777         struct dpll clock;
778         int err = target;
779
780         memset(best_clock, 0, sizeof(*best_clock));
781
782         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
783
784         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
785              clock.m1++) {
786                 for (clock.m2 = limit->m2.min;
787                      clock.m2 <= limit->m2.max; clock.m2++) {
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                                         pnv_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 /*
816  * Returns a set of divisors for the desired target clock with the given
817  * refclk, or FALSE.  The returned values represent the clock equation:
818  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
819  *
820  * Target and reference clocks are specified in kHz.
821  *
822  * If match_clock is provided, then best_clock P divider must match the P
823  * divider from @match_clock used for LVDS downclocking.
824  */
825 static bool
826 g4x_find_best_dpll(const struct intel_limit *limit,
827                    struct intel_crtc_state *crtc_state,
828                    int target, int refclk, struct dpll *match_clock,
829                    struct dpll *best_clock)
830 {
831         struct drm_device *dev = crtc_state->base.crtc->dev;
832         struct dpll clock;
833         int max_n;
834         bool found = false;
835         /* approximately equals target * 0.00585 */
836         int err_most = (target >> 8) + (target >> 9);
837
838         memset(best_clock, 0, sizeof(*best_clock));
839
840         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
841
842         max_n = limit->n.max;
843         /* based on hardware requirement, prefer smaller n to precision */
844         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
845                 /* based on hardware requirement, prefere larger m1,m2 */
846                 for (clock.m1 = limit->m1.max;
847                      clock.m1 >= limit->m1.min; clock.m1--) {
848                         for (clock.m2 = limit->m2.max;
849                              clock.m2 >= limit->m2.min; clock.m2--) {
850                                 for (clock.p1 = limit->p1.max;
851                                      clock.p1 >= limit->p1.min; clock.p1--) {
852                                         int this_err;
853
854                                         i9xx_calc_dpll_params(refclk, &clock);
855                                         if (!intel_PLL_is_valid(dev, limit,
856                                                                 &clock))
857                                                 continue;
858
859                                         this_err = abs(clock.dot - target);
860                                         if (this_err < err_most) {
861                                                 *best_clock = clock;
862                                                 err_most = this_err;
863                                                 max_n = clock.n;
864                                                 found = true;
865                                         }
866                                 }
867                         }
868                 }
869         }
870         return found;
871 }
872
873 /*
874  * Check if the calculated PLL configuration is more optimal compared to the
875  * best configuration and error found so far. Return the calculated error.
876  */
877 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
878                                const struct dpll *calculated_clock,
879                                const struct dpll *best_clock,
880                                unsigned int best_error_ppm,
881                                unsigned int *error_ppm)
882 {
883         /*
884          * For CHV ignore the error and consider only the P value.
885          * Prefer a bigger P value based on HW requirements.
886          */
887         if (IS_CHERRYVIEW(dev)) {
888                 *error_ppm = 0;
889
890                 return calculated_clock->p > best_clock->p;
891         }
892
893         if (WARN_ON_ONCE(!target_freq))
894                 return false;
895
896         *error_ppm = div_u64(1000000ULL *
897                                 abs(target_freq - calculated_clock->dot),
898                              target_freq);
899         /*
900          * Prefer a better P value over a better (smaller) error if the error
901          * is small. Ensure this preference for future configurations too by
902          * setting the error to 0.
903          */
904         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
905                 *error_ppm = 0;
906
907                 return true;
908         }
909
910         return *error_ppm + 10 < best_error_ppm;
911 }
912
913 /*
914  * Returns a set of divisors for the desired target clock with the given
915  * refclk, or FALSE.  The returned values represent the clock equation:
916  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
917  */
918 static bool
919 vlv_find_best_dpll(const struct intel_limit *limit,
920                    struct intel_crtc_state *crtc_state,
921                    int target, int refclk, struct dpll *match_clock,
922                    struct dpll *best_clock)
923 {
924         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
925         struct drm_device *dev = crtc->base.dev;
926         struct dpll clock;
927         unsigned int bestppm = 1000000;
928         /* min update 19.2 MHz */
929         int max_n = min(limit->n.max, refclk / 19200);
930         bool found = false;
931
932         target *= 5; /* fast clock */
933
934         memset(best_clock, 0, sizeof(*best_clock));
935
936         /* based on hardware requirement, prefer smaller n to precision */
937         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
938                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
939                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
940                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
941                                 clock.p = clock.p1 * clock.p2;
942                                 /* based on hardware requirement, prefer bigger m1,m2 values */
943                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
944                                         unsigned int ppm;
945
946                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
947                                                                      refclk * clock.m1);
948
949                                         vlv_calc_dpll_params(refclk, &clock);
950
951                                         if (!intel_PLL_is_valid(dev, limit,
952                                                                 &clock))
953                                                 continue;
954
955                                         if (!vlv_PLL_is_optimal(dev, target,
956                                                                 &clock,
957                                                                 best_clock,
958                                                                 bestppm, &ppm))
959                                                 continue;
960
961                                         *best_clock = clock;
962                                         bestppm = ppm;
963                                         found = true;
964                                 }
965                         }
966                 }
967         }
968
969         return found;
970 }
971
972 /*
973  * Returns a set of divisors for the desired target clock with the given
974  * refclk, or FALSE.  The returned values represent the clock equation:
975  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
976  */
977 static bool
978 chv_find_best_dpll(const struct intel_limit *limit,
979                    struct intel_crtc_state *crtc_state,
980                    int target, int refclk, struct dpll *match_clock,
981                    struct dpll *best_clock)
982 {
983         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
984         struct drm_device *dev = crtc->base.dev;
985         unsigned int best_error_ppm;
986         struct dpll clock;
987         uint64_t m2;
988         int found = false;
989
990         memset(best_clock, 0, sizeof(*best_clock));
991         best_error_ppm = 1000000;
992
993         /*
994          * Based on hardware doc, the n always set to 1, and m1 always
995          * set to 2.  If requires to support 200Mhz refclk, we need to
996          * revisit this because n may not 1 anymore.
997          */
998         clock.n = 1, clock.m1 = 2;
999         target *= 5;    /* fast clock */
1000
1001         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
1002                 for (clock.p2 = limit->p2.p2_fast;
1003                                 clock.p2 >= limit->p2.p2_slow;
1004                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1005                         unsigned int error_ppm;
1006
1007                         clock.p = clock.p1 * clock.p2;
1008
1009                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1010                                         clock.n) << 22, refclk * clock.m1);
1011
1012                         if (m2 > INT_MAX/clock.m1)
1013                                 continue;
1014
1015                         clock.m2 = m2;
1016
1017                         chv_calc_dpll_params(refclk, &clock);
1018
1019                         if (!intel_PLL_is_valid(dev, limit, &clock))
1020                                 continue;
1021
1022                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1023                                                 best_error_ppm, &error_ppm))
1024                                 continue;
1025
1026                         *best_clock = clock;
1027                         best_error_ppm = error_ppm;
1028                         found = true;
1029                 }
1030         }
1031
1032         return found;
1033 }
1034
1035 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1036                         struct dpll *best_clock)
1037 {
1038         int refclk = 100000;
1039         const struct intel_limit *limit = &intel_limits_bxt;
1040
1041         return chv_find_best_dpll(limit, crtc_state,
1042                                   target_clock, refclk, NULL, best_clock);
1043 }
1044
1045 bool intel_crtc_active(struct drm_crtc *crtc)
1046 {
1047         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1048
1049         /* Be paranoid as we can arrive here with only partial
1050          * state retrieved from the hardware during setup.
1051          *
1052          * We can ditch the adjusted_mode.crtc_clock check as soon
1053          * as Haswell has gained clock readout/fastboot support.
1054          *
1055          * We can ditch the crtc->primary->fb check as soon as we can
1056          * properly reconstruct framebuffers.
1057          *
1058          * FIXME: The intel_crtc->active here should be switched to
1059          * crtc->state->active once we have proper CRTC states wired up
1060          * for atomic.
1061          */
1062         return intel_crtc->active && crtc->primary->state->fb &&
1063                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1064 }
1065
1066 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1067                                              enum pipe pipe)
1068 {
1069         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1070         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1071
1072         return intel_crtc->config->cpu_transcoder;
1073 }
1074
1075 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1076 {
1077         struct drm_i915_private *dev_priv = dev->dev_private;
1078         i915_reg_t reg = PIPEDSL(pipe);
1079         u32 line1, line2;
1080         u32 line_mask;
1081
1082         if (IS_GEN2(dev))
1083                 line_mask = DSL_LINEMASK_GEN2;
1084         else
1085                 line_mask = DSL_LINEMASK_GEN3;
1086
1087         line1 = I915_READ(reg) & line_mask;
1088         msleep(5);
1089         line2 = I915_READ(reg) & line_mask;
1090
1091         return line1 == line2;
1092 }
1093
1094 /*
1095  * intel_wait_for_pipe_off - wait for pipe to turn off
1096  * @crtc: crtc whose pipe to wait for
1097  *
1098  * After disabling a pipe, we can't wait for vblank in the usual way,
1099  * spinning on the vblank interrupt status bit, since we won't actually
1100  * see an interrupt when the pipe is disabled.
1101  *
1102  * On Gen4 and above:
1103  *   wait for the pipe register state bit to turn off
1104  *
1105  * Otherwise:
1106  *   wait for the display line value to settle (it usually
1107  *   ends up stopping at the start of the next frame).
1108  *
1109  */
1110 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1111 {
1112         struct drm_device *dev = crtc->base.dev;
1113         struct drm_i915_private *dev_priv = dev->dev_private;
1114         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1115         enum pipe pipe = crtc->pipe;
1116
1117         if (INTEL_INFO(dev)->gen >= 4) {
1118                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1119
1120                 /* Wait for the Pipe State to go off */
1121                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1122                              100))
1123                         WARN(1, "pipe_off wait timed out\n");
1124         } else {
1125                 /* Wait for the display line to settle */
1126                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1127                         WARN(1, "pipe_off wait timed out\n");
1128         }
1129 }
1130
1131 /* Only for pre-ILK configs */
1132 void assert_pll(struct drm_i915_private *dev_priv,
1133                 enum pipe pipe, bool state)
1134 {
1135         u32 val;
1136         bool cur_state;
1137
1138         val = I915_READ(DPLL(pipe));
1139         cur_state = !!(val & DPLL_VCO_ENABLE);
1140         I915_STATE_WARN(cur_state != state,
1141              "PLL state assertion failure (expected %s, current %s)\n",
1142                         onoff(state), onoff(cur_state));
1143 }
1144
1145 /* XXX: the dsi pll is shared between MIPI DSI ports */
1146 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1147 {
1148         u32 val;
1149         bool cur_state;
1150
1151         mutex_lock(&dev_priv->sb_lock);
1152         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1153         mutex_unlock(&dev_priv->sb_lock);
1154
1155         cur_state = val & DSI_PLL_VCO_EN;
1156         I915_STATE_WARN(cur_state != state,
1157              "DSI PLL state assertion failure (expected %s, current %s)\n",
1158                         onoff(state), onoff(cur_state));
1159 }
1160
1161 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1162                           enum pipe pipe, bool state)
1163 {
1164         bool cur_state;
1165         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1166                                                                       pipe);
1167
1168         if (HAS_DDI(dev_priv)) {
1169                 /* DDI does not have a specific FDI_TX register */
1170                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1171                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1172         } else {
1173                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1174                 cur_state = !!(val & FDI_TX_ENABLE);
1175         }
1176         I915_STATE_WARN(cur_state != state,
1177              "FDI TX state assertion failure (expected %s, current %s)\n",
1178                         onoff(state), onoff(cur_state));
1179 }
1180 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1181 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1182
1183 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1184                           enum pipe pipe, bool state)
1185 {
1186         u32 val;
1187         bool cur_state;
1188
1189         val = I915_READ(FDI_RX_CTL(pipe));
1190         cur_state = !!(val & FDI_RX_ENABLE);
1191         I915_STATE_WARN(cur_state != state,
1192              "FDI RX state assertion failure (expected %s, current %s)\n",
1193                         onoff(state), onoff(cur_state));
1194 }
1195 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1196 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1197
1198 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1199                                       enum pipe pipe)
1200 {
1201         u32 val;
1202
1203         /* ILK FDI PLL is always enabled */
1204         if (IS_GEN5(dev_priv))
1205                 return;
1206
1207         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1208         if (HAS_DDI(dev_priv))
1209                 return;
1210
1211         val = I915_READ(FDI_TX_CTL(pipe));
1212         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1213 }
1214
1215 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1216                        enum pipe pipe, bool state)
1217 {
1218         u32 val;
1219         bool cur_state;
1220
1221         val = I915_READ(FDI_RX_CTL(pipe));
1222         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1223         I915_STATE_WARN(cur_state != state,
1224              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1225                         onoff(state), onoff(cur_state));
1226 }
1227
1228 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1229                            enum pipe pipe)
1230 {
1231         struct drm_device *dev = dev_priv->dev;
1232         i915_reg_t pp_reg;
1233         u32 val;
1234         enum pipe panel_pipe = PIPE_A;
1235         bool locked = true;
1236
1237         if (WARN_ON(HAS_DDI(dev)))
1238                 return;
1239
1240         if (HAS_PCH_SPLIT(dev)) {
1241                 u32 port_sel;
1242
1243                 pp_reg = PCH_PP_CONTROL;
1244                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1245
1246                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1247                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1248                         panel_pipe = PIPE_B;
1249                 /* XXX: else fix for eDP */
1250         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1251                 /* presumably write lock depends on pipe, not port select */
1252                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1253                 panel_pipe = pipe;
1254         } else {
1255                 pp_reg = PP_CONTROL;
1256                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1257                         panel_pipe = PIPE_B;
1258         }
1259
1260         val = I915_READ(pp_reg);
1261         if (!(val & PANEL_POWER_ON) ||
1262             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1263                 locked = false;
1264
1265         I915_STATE_WARN(panel_pipe == pipe && locked,
1266              "panel assertion failure, pipe %c regs locked\n",
1267              pipe_name(pipe));
1268 }
1269
1270 static void assert_cursor(struct drm_i915_private *dev_priv,
1271                           enum pipe pipe, bool state)
1272 {
1273         struct drm_device *dev = dev_priv->dev;
1274         bool cur_state;
1275
1276         if (IS_845G(dev) || IS_I865G(dev))
1277                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1278         else
1279                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1280
1281         I915_STATE_WARN(cur_state != state,
1282              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1283                         pipe_name(pipe), onoff(state), onoff(cur_state));
1284 }
1285 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1286 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1287
1288 void assert_pipe(struct drm_i915_private *dev_priv,
1289                  enum pipe pipe, bool state)
1290 {
1291         bool cur_state;
1292         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1293                                                                       pipe);
1294         enum intel_display_power_domain power_domain;
1295
1296         /* if we need the pipe quirk it must be always on */
1297         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1298             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1299                 state = true;
1300
1301         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1302         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1303                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1304                 cur_state = !!(val & PIPECONF_ENABLE);
1305
1306                 intel_display_power_put(dev_priv, power_domain);
1307         } else {
1308                 cur_state = false;
1309         }
1310
1311         I915_STATE_WARN(cur_state != state,
1312              "pipe %c assertion failure (expected %s, current %s)\n",
1313                         pipe_name(pipe), onoff(state), onoff(cur_state));
1314 }
1315
1316 static void assert_plane(struct drm_i915_private *dev_priv,
1317                          enum plane plane, bool state)
1318 {
1319         u32 val;
1320         bool cur_state;
1321
1322         val = I915_READ(DSPCNTR(plane));
1323         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1324         I915_STATE_WARN(cur_state != state,
1325              "plane %c assertion failure (expected %s, current %s)\n",
1326                         plane_name(plane), onoff(state), onoff(cur_state));
1327 }
1328
1329 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1330 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1331
1332 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1333                                    enum pipe pipe)
1334 {
1335         struct drm_device *dev = dev_priv->dev;
1336         int i;
1337
1338         /* Primary planes are fixed to pipes on gen4+ */
1339         if (INTEL_INFO(dev)->gen >= 4) {
1340                 u32 val = I915_READ(DSPCNTR(pipe));
1341                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1342                      "plane %c assertion failure, should be disabled but not\n",
1343                      plane_name(pipe));
1344                 return;
1345         }
1346
1347         /* Need to check both planes against the pipe */
1348         for_each_pipe(dev_priv, i) {
1349                 u32 val = I915_READ(DSPCNTR(i));
1350                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1351                         DISPPLANE_SEL_PIPE_SHIFT;
1352                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1353                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1354                      plane_name(i), pipe_name(pipe));
1355         }
1356 }
1357
1358 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1359                                     enum pipe pipe)
1360 {
1361         struct drm_device *dev = dev_priv->dev;
1362         int sprite;
1363
1364         if (INTEL_INFO(dev)->gen >= 9) {
1365                 for_each_sprite(dev_priv, pipe, sprite) {
1366                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1367                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1368                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1369                              sprite, pipe_name(pipe));
1370                 }
1371         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1372                 for_each_sprite(dev_priv, pipe, sprite) {
1373                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1374                         I915_STATE_WARN(val & SP_ENABLE,
1375                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1376                              sprite_name(pipe, sprite), pipe_name(pipe));
1377                 }
1378         } else if (INTEL_INFO(dev)->gen >= 7) {
1379                 u32 val = I915_READ(SPRCTL(pipe));
1380                 I915_STATE_WARN(val & SPRITE_ENABLE,
1381                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1382                      plane_name(pipe), pipe_name(pipe));
1383         } else if (INTEL_INFO(dev)->gen >= 5) {
1384                 u32 val = I915_READ(DVSCNTR(pipe));
1385                 I915_STATE_WARN(val & DVS_ENABLE,
1386                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1387                      plane_name(pipe), pipe_name(pipe));
1388         }
1389 }
1390
1391 static void assert_vblank_disabled(struct drm_crtc *crtc)
1392 {
1393         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1394                 drm_crtc_vblank_put(crtc);
1395 }
1396
1397 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1398                                     enum pipe pipe)
1399 {
1400         u32 val;
1401         bool enabled;
1402
1403         val = I915_READ(PCH_TRANSCONF(pipe));
1404         enabled = !!(val & TRANS_ENABLE);
1405         I915_STATE_WARN(enabled,
1406              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1407              pipe_name(pipe));
1408 }
1409
1410 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1411                             enum pipe pipe, u32 port_sel, u32 val)
1412 {
1413         if ((val & DP_PORT_EN) == 0)
1414                 return false;
1415
1416         if (HAS_PCH_CPT(dev_priv)) {
1417                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1418                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1419                         return false;
1420         } else if (IS_CHERRYVIEW(dev_priv)) {
1421                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1422                         return false;
1423         } else {
1424                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1425                         return false;
1426         }
1427         return true;
1428 }
1429
1430 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1431                               enum pipe pipe, u32 val)
1432 {
1433         if ((val & SDVO_ENABLE) == 0)
1434                 return false;
1435
1436         if (HAS_PCH_CPT(dev_priv)) {
1437                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1438                         return false;
1439         } else if (IS_CHERRYVIEW(dev_priv)) {
1440                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1441                         return false;
1442         } else {
1443                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1444                         return false;
1445         }
1446         return true;
1447 }
1448
1449 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1450                               enum pipe pipe, u32 val)
1451 {
1452         if ((val & LVDS_PORT_EN) == 0)
1453                 return false;
1454
1455         if (HAS_PCH_CPT(dev_priv)) {
1456                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1457                         return false;
1458         } else {
1459                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1460                         return false;
1461         }
1462         return true;
1463 }
1464
1465 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1466                               enum pipe pipe, u32 val)
1467 {
1468         if ((val & ADPA_DAC_ENABLE) == 0)
1469                 return false;
1470         if (HAS_PCH_CPT(dev_priv)) {
1471                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1472                         return false;
1473         } else {
1474                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1475                         return false;
1476         }
1477         return true;
1478 }
1479
1480 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1481                                    enum pipe pipe, i915_reg_t reg,
1482                                    u32 port_sel)
1483 {
1484         u32 val = I915_READ(reg);
1485         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1486              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1487              i915_mmio_reg_offset(reg), pipe_name(pipe));
1488
1489         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1490              && (val & DP_PIPEB_SELECT),
1491              "IBX PCH dp port still using transcoder B\n");
1492 }
1493
1494 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1495                                      enum pipe pipe, i915_reg_t reg)
1496 {
1497         u32 val = I915_READ(reg);
1498         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1499              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1500              i915_mmio_reg_offset(reg), pipe_name(pipe));
1501
1502         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1503              && (val & SDVO_PIPE_B_SELECT),
1504              "IBX PCH hdmi port still using transcoder B\n");
1505 }
1506
1507 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1508                                       enum pipe pipe)
1509 {
1510         u32 val;
1511
1512         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1513         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1514         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1515
1516         val = I915_READ(PCH_ADPA);
1517         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1518              "PCH VGA enabled on transcoder %c, should be disabled\n",
1519              pipe_name(pipe));
1520
1521         val = I915_READ(PCH_LVDS);
1522         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1523              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1524              pipe_name(pipe));
1525
1526         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1527         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1528         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1529 }
1530
1531 static void _vlv_enable_pll(struct intel_crtc *crtc,
1532                             const struct intel_crtc_state *pipe_config)
1533 {
1534         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1535         enum pipe pipe = crtc->pipe;
1536
1537         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1538         POSTING_READ(DPLL(pipe));
1539         udelay(150);
1540
1541         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1542                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1543 }
1544
1545 static void vlv_enable_pll(struct intel_crtc *crtc,
1546                            const struct intel_crtc_state *pipe_config)
1547 {
1548         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1549         enum pipe pipe = crtc->pipe;
1550
1551         assert_pipe_disabled(dev_priv, pipe);
1552
1553         /* PLL is protected by panel, make sure we can write it */
1554         assert_panel_unlocked(dev_priv, pipe);
1555
1556         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1557                 _vlv_enable_pll(crtc, pipe_config);
1558
1559         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1560         POSTING_READ(DPLL_MD(pipe));
1561 }
1562
1563
1564 static void _chv_enable_pll(struct intel_crtc *crtc,
1565                             const struct intel_crtc_state *pipe_config)
1566 {
1567         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1568         enum pipe pipe = crtc->pipe;
1569         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1570         u32 tmp;
1571
1572         mutex_lock(&dev_priv->sb_lock);
1573
1574         /* Enable back the 10bit clock to display controller */
1575         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1576         tmp |= DPIO_DCLKP_EN;
1577         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1578
1579         mutex_unlock(&dev_priv->sb_lock);
1580
1581         /*
1582          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1583          */
1584         udelay(1);
1585
1586         /* Enable PLL */
1587         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1588
1589         /* Check PLL is locked */
1590         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1591                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1592 }
1593
1594 static void chv_enable_pll(struct intel_crtc *crtc,
1595                            const struct intel_crtc_state *pipe_config)
1596 {
1597         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1598         enum pipe pipe = crtc->pipe;
1599
1600         assert_pipe_disabled(dev_priv, pipe);
1601
1602         /* PLL is protected by panel, make sure we can write it */
1603         assert_panel_unlocked(dev_priv, pipe);
1604
1605         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1606                 _chv_enable_pll(crtc, pipe_config);
1607
1608         if (pipe != PIPE_A) {
1609                 /*
1610                  * WaPixelRepeatModeFixForC0:chv
1611                  *
1612                  * DPLLCMD is AWOL. Use chicken bits to propagate
1613                  * the value from DPLLBMD to either pipe B or C.
1614                  */
1615                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1616                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1617                 I915_WRITE(CBR4_VLV, 0);
1618                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1619
1620                 /*
1621                  * DPLLB VGA mode also seems to cause problems.
1622                  * We should always have it disabled.
1623                  */
1624                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1625         } else {
1626                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1627                 POSTING_READ(DPLL_MD(pipe));
1628         }
1629 }
1630
1631 static int intel_num_dvo_pipes(struct drm_device *dev)
1632 {
1633         struct intel_crtc *crtc;
1634         int count = 0;
1635
1636         for_each_intel_crtc(dev, crtc)
1637                 count += crtc->base.state->active &&
1638                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1639
1640         return count;
1641 }
1642
1643 static void i9xx_enable_pll(struct intel_crtc *crtc)
1644 {
1645         struct drm_device *dev = crtc->base.dev;
1646         struct drm_i915_private *dev_priv = dev->dev_private;
1647         i915_reg_t reg = DPLL(crtc->pipe);
1648         u32 dpll = crtc->config->dpll_hw_state.dpll;
1649
1650         assert_pipe_disabled(dev_priv, crtc->pipe);
1651
1652         /* PLL is protected by panel, make sure we can write it */
1653         if (IS_MOBILE(dev) && !IS_I830(dev))
1654                 assert_panel_unlocked(dev_priv, crtc->pipe);
1655
1656         /* Enable DVO 2x clock on both PLLs if necessary */
1657         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1658                 /*
1659                  * It appears to be important that we don't enable this
1660                  * for the current pipe before otherwise configuring the
1661                  * PLL. No idea how this should be handled if multiple
1662                  * DVO outputs are enabled simultaneosly.
1663                  */
1664                 dpll |= DPLL_DVO_2X_MODE;
1665                 I915_WRITE(DPLL(!crtc->pipe),
1666                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1667         }
1668
1669         /*
1670          * Apparently we need to have VGA mode enabled prior to changing
1671          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1672          * dividers, even though the register value does change.
1673          */
1674         I915_WRITE(reg, 0);
1675
1676         I915_WRITE(reg, dpll);
1677
1678         /* Wait for the clocks to stabilize. */
1679         POSTING_READ(reg);
1680         udelay(150);
1681
1682         if (INTEL_INFO(dev)->gen >= 4) {
1683                 I915_WRITE(DPLL_MD(crtc->pipe),
1684                            crtc->config->dpll_hw_state.dpll_md);
1685         } else {
1686                 /* The pixel multiplier can only be updated once the
1687                  * DPLL is enabled and the clocks are stable.
1688                  *
1689                  * So write it again.
1690                  */
1691                 I915_WRITE(reg, dpll);
1692         }
1693
1694         /* We do this three times for luck */
1695         I915_WRITE(reg, dpll);
1696         POSTING_READ(reg);
1697         udelay(150); /* wait for warmup */
1698         I915_WRITE(reg, dpll);
1699         POSTING_READ(reg);
1700         udelay(150); /* wait for warmup */
1701         I915_WRITE(reg, dpll);
1702         POSTING_READ(reg);
1703         udelay(150); /* wait for warmup */
1704 }
1705
1706 /**
1707  * i9xx_disable_pll - disable a PLL
1708  * @dev_priv: i915 private structure
1709  * @pipe: pipe PLL to disable
1710  *
1711  * Disable the PLL for @pipe, making sure the pipe is off first.
1712  *
1713  * Note!  This is for pre-ILK only.
1714  */
1715 static void i9xx_disable_pll(struct intel_crtc *crtc)
1716 {
1717         struct drm_device *dev = crtc->base.dev;
1718         struct drm_i915_private *dev_priv = dev->dev_private;
1719         enum pipe pipe = crtc->pipe;
1720
1721         /* Disable DVO 2x clock on both PLLs if necessary */
1722         if (IS_I830(dev) &&
1723             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1724             !intel_num_dvo_pipes(dev)) {
1725                 I915_WRITE(DPLL(PIPE_B),
1726                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1727                 I915_WRITE(DPLL(PIPE_A),
1728                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1729         }
1730
1731         /* Don't disable pipe or pipe PLLs if needed */
1732         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1733             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1734                 return;
1735
1736         /* Make sure the pipe isn't still relying on us */
1737         assert_pipe_disabled(dev_priv, pipe);
1738
1739         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1740         POSTING_READ(DPLL(pipe));
1741 }
1742
1743 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1744 {
1745         u32 val;
1746
1747         /* Make sure the pipe isn't still relying on us */
1748         assert_pipe_disabled(dev_priv, pipe);
1749
1750         val = DPLL_INTEGRATED_REF_CLK_VLV |
1751                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1752         if (pipe != PIPE_A)
1753                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1754
1755         I915_WRITE(DPLL(pipe), val);
1756         POSTING_READ(DPLL(pipe));
1757 }
1758
1759 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1760 {
1761         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1762         u32 val;
1763
1764         /* Make sure the pipe isn't still relying on us */
1765         assert_pipe_disabled(dev_priv, pipe);
1766
1767         val = DPLL_SSC_REF_CLK_CHV |
1768                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1769         if (pipe != PIPE_A)
1770                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1771
1772         I915_WRITE(DPLL(pipe), val);
1773         POSTING_READ(DPLL(pipe));
1774
1775         mutex_lock(&dev_priv->sb_lock);
1776
1777         /* Disable 10bit clock to display controller */
1778         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1779         val &= ~DPIO_DCLKP_EN;
1780         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1781
1782         mutex_unlock(&dev_priv->sb_lock);
1783 }
1784
1785 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1786                          struct intel_digital_port *dport,
1787                          unsigned int expected_mask)
1788 {
1789         u32 port_mask;
1790         i915_reg_t dpll_reg;
1791
1792         switch (dport->port) {
1793         case PORT_B:
1794                 port_mask = DPLL_PORTB_READY_MASK;
1795                 dpll_reg = DPLL(0);
1796                 break;
1797         case PORT_C:
1798                 port_mask = DPLL_PORTC_READY_MASK;
1799                 dpll_reg = DPLL(0);
1800                 expected_mask <<= 4;
1801                 break;
1802         case PORT_D:
1803                 port_mask = DPLL_PORTD_READY_MASK;
1804                 dpll_reg = DPIO_PHY_STATUS;
1805                 break;
1806         default:
1807                 BUG();
1808         }
1809
1810         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1811                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1812                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1813 }
1814
1815 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1816                                            enum pipe pipe)
1817 {
1818         struct drm_device *dev = dev_priv->dev;
1819         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1820         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1821         i915_reg_t reg;
1822         uint32_t val, pipeconf_val;
1823
1824         /* Make sure PCH DPLL is enabled */
1825         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1826
1827         /* FDI must be feeding us bits for PCH ports */
1828         assert_fdi_tx_enabled(dev_priv, pipe);
1829         assert_fdi_rx_enabled(dev_priv, pipe);
1830
1831         if (HAS_PCH_CPT(dev)) {
1832                 /* Workaround: Set the timing override bit before enabling the
1833                  * pch transcoder. */
1834                 reg = TRANS_CHICKEN2(pipe);
1835                 val = I915_READ(reg);
1836                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1837                 I915_WRITE(reg, val);
1838         }
1839
1840         reg = PCH_TRANSCONF(pipe);
1841         val = I915_READ(reg);
1842         pipeconf_val = I915_READ(PIPECONF(pipe));
1843
1844         if (HAS_PCH_IBX(dev_priv)) {
1845                 /*
1846                  * Make the BPC in transcoder be consistent with
1847                  * that in pipeconf reg. For HDMI we must use 8bpc
1848                  * here for both 8bpc and 12bpc.
1849                  */
1850                 val &= ~PIPECONF_BPC_MASK;
1851                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1852                         val |= PIPECONF_8BPC;
1853                 else
1854                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1855         }
1856
1857         val &= ~TRANS_INTERLACE_MASK;
1858         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1859                 if (HAS_PCH_IBX(dev_priv) &&
1860                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1861                         val |= TRANS_LEGACY_INTERLACED_ILK;
1862                 else
1863                         val |= TRANS_INTERLACED;
1864         else
1865                 val |= TRANS_PROGRESSIVE;
1866
1867         I915_WRITE(reg, val | TRANS_ENABLE);
1868         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1869                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1870 }
1871
1872 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1873                                       enum transcoder cpu_transcoder)
1874 {
1875         u32 val, pipeconf_val;
1876
1877         /* FDI must be feeding us bits for PCH ports */
1878         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1879         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1880
1881         /* Workaround: set timing override bit. */
1882         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1883         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1884         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1885
1886         val = TRANS_ENABLE;
1887         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1888
1889         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1890             PIPECONF_INTERLACED_ILK)
1891                 val |= TRANS_INTERLACED;
1892         else
1893                 val |= TRANS_PROGRESSIVE;
1894
1895         I915_WRITE(LPT_TRANSCONF, val);
1896         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1897                 DRM_ERROR("Failed to enable PCH transcoder\n");
1898 }
1899
1900 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1901                                             enum pipe pipe)
1902 {
1903         struct drm_device *dev = dev_priv->dev;
1904         i915_reg_t reg;
1905         uint32_t val;
1906
1907         /* FDI relies on the transcoder */
1908         assert_fdi_tx_disabled(dev_priv, pipe);
1909         assert_fdi_rx_disabled(dev_priv, pipe);
1910
1911         /* Ports must be off as well */
1912         assert_pch_ports_disabled(dev_priv, pipe);
1913
1914         reg = PCH_TRANSCONF(pipe);
1915         val = I915_READ(reg);
1916         val &= ~TRANS_ENABLE;
1917         I915_WRITE(reg, val);
1918         /* wait for PCH transcoder off, transcoder state */
1919         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1920                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1921
1922         if (HAS_PCH_CPT(dev)) {
1923                 /* Workaround: Clear the timing override chicken bit again. */
1924                 reg = TRANS_CHICKEN2(pipe);
1925                 val = I915_READ(reg);
1926                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1927                 I915_WRITE(reg, val);
1928         }
1929 }
1930
1931 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1932 {
1933         u32 val;
1934
1935         val = I915_READ(LPT_TRANSCONF);
1936         val &= ~TRANS_ENABLE;
1937         I915_WRITE(LPT_TRANSCONF, val);
1938         /* wait for PCH transcoder off, transcoder state */
1939         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1940                 DRM_ERROR("Failed to disable PCH transcoder\n");
1941
1942         /* Workaround: clear timing override bit. */
1943         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1944         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1945         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1946 }
1947
1948 /**
1949  * intel_enable_pipe - enable a pipe, asserting requirements
1950  * @crtc: crtc responsible for the pipe
1951  *
1952  * Enable @crtc's pipe, making sure that various hardware specific requirements
1953  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1954  */
1955 static void intel_enable_pipe(struct intel_crtc *crtc)
1956 {
1957         struct drm_device *dev = crtc->base.dev;
1958         struct drm_i915_private *dev_priv = dev->dev_private;
1959         enum pipe pipe = crtc->pipe;
1960         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1961         enum pipe pch_transcoder;
1962         i915_reg_t reg;
1963         u32 val;
1964
1965         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1966
1967         assert_planes_disabled(dev_priv, pipe);
1968         assert_cursor_disabled(dev_priv, pipe);
1969         assert_sprites_disabled(dev_priv, pipe);
1970
1971         if (HAS_PCH_LPT(dev_priv))
1972                 pch_transcoder = TRANSCODER_A;
1973         else
1974                 pch_transcoder = pipe;
1975
1976         /*
1977          * A pipe without a PLL won't actually be able to drive bits from
1978          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1979          * need the check.
1980          */
1981         if (HAS_GMCH_DISPLAY(dev_priv))
1982                 if (crtc->config->has_dsi_encoder)
1983                         assert_dsi_pll_enabled(dev_priv);
1984                 else
1985                         assert_pll_enabled(dev_priv, pipe);
1986         else {
1987                 if (crtc->config->has_pch_encoder) {
1988                         /* if driving the PCH, we need FDI enabled */
1989                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1990                         assert_fdi_tx_pll_enabled(dev_priv,
1991                                                   (enum pipe) cpu_transcoder);
1992                 }
1993                 /* FIXME: assert CPU port conditions for SNB+ */
1994         }
1995
1996         reg = PIPECONF(cpu_transcoder);
1997         val = I915_READ(reg);
1998         if (val & PIPECONF_ENABLE) {
1999                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2000                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2001                 return;
2002         }
2003
2004         I915_WRITE(reg, val | PIPECONF_ENABLE);
2005         POSTING_READ(reg);
2006
2007         /*
2008          * Until the pipe starts DSL will read as 0, which would cause
2009          * an apparent vblank timestamp jump, which messes up also the
2010          * frame count when it's derived from the timestamps. So let's
2011          * wait for the pipe to start properly before we call
2012          * drm_crtc_vblank_on()
2013          */
2014         if (dev->max_vblank_count == 0 &&
2015             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2016                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2017 }
2018
2019 /**
2020  * intel_disable_pipe - disable a pipe, asserting requirements
2021  * @crtc: crtc whose pipes is to be disabled
2022  *
2023  * Disable the pipe of @crtc, making sure that various hardware
2024  * specific requirements are met, if applicable, e.g. plane
2025  * disabled, panel fitter off, etc.
2026  *
2027  * Will wait until the pipe has shut down before returning.
2028  */
2029 static void intel_disable_pipe(struct intel_crtc *crtc)
2030 {
2031         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2032         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2033         enum pipe pipe = crtc->pipe;
2034         i915_reg_t reg;
2035         u32 val;
2036
2037         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2038
2039         /*
2040          * Make sure planes won't keep trying to pump pixels to us,
2041          * or we might hang the display.
2042          */
2043         assert_planes_disabled(dev_priv, pipe);
2044         assert_cursor_disabled(dev_priv, pipe);
2045         assert_sprites_disabled(dev_priv, pipe);
2046
2047         reg = PIPECONF(cpu_transcoder);
2048         val = I915_READ(reg);
2049         if ((val & PIPECONF_ENABLE) == 0)
2050                 return;
2051
2052         /*
2053          * Double wide has implications for planes
2054          * so best keep it disabled when not needed.
2055          */
2056         if (crtc->config->double_wide)
2057                 val &= ~PIPECONF_DOUBLE_WIDE;
2058
2059         /* Don't disable pipe or pipe PLLs if needed */
2060         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2061             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2062                 val &= ~PIPECONF_ENABLE;
2063
2064         I915_WRITE(reg, val);
2065         if ((val & PIPECONF_ENABLE) == 0)
2066                 intel_wait_for_pipe_off(crtc);
2067 }
2068
2069 static bool need_vtd_wa(struct drm_device *dev)
2070 {
2071 #ifdef CONFIG_INTEL_IOMMU
2072         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2073                 return true;
2074 #endif
2075         return false;
2076 }
2077
2078 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2079 {
2080         return IS_GEN2(dev_priv) ? 2048 : 4096;
2081 }
2082
2083 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2084                                            uint64_t fb_modifier, unsigned int cpp)
2085 {
2086         switch (fb_modifier) {
2087         case DRM_FORMAT_MOD_NONE:
2088                 return cpp;
2089         case I915_FORMAT_MOD_X_TILED:
2090                 if (IS_GEN2(dev_priv))
2091                         return 128;
2092                 else
2093                         return 512;
2094         case I915_FORMAT_MOD_Y_TILED:
2095                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2096                         return 128;
2097                 else
2098                         return 512;
2099         case I915_FORMAT_MOD_Yf_TILED:
2100                 switch (cpp) {
2101                 case 1:
2102                         return 64;
2103                 case 2:
2104                 case 4:
2105                         return 128;
2106                 case 8:
2107                 case 16:
2108                         return 256;
2109                 default:
2110                         MISSING_CASE(cpp);
2111                         return cpp;
2112                 }
2113                 break;
2114         default:
2115                 MISSING_CASE(fb_modifier);
2116                 return cpp;
2117         }
2118 }
2119
2120 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2121                                uint64_t fb_modifier, unsigned int cpp)
2122 {
2123         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2124                 return 1;
2125         else
2126                 return intel_tile_size(dev_priv) /
2127                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2128 }
2129
2130 /* Return the tile dimensions in pixel units */
2131 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2132                             unsigned int *tile_width,
2133                             unsigned int *tile_height,
2134                             uint64_t fb_modifier,
2135                             unsigned int cpp)
2136 {
2137         unsigned int tile_width_bytes =
2138                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2139
2140         *tile_width = tile_width_bytes / cpp;
2141         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2142 }
2143
2144 unsigned int
2145 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2146                       uint32_t pixel_format, uint64_t fb_modifier)
2147 {
2148         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2149         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2150
2151         return ALIGN(height, tile_height);
2152 }
2153
2154 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2155 {
2156         unsigned int size = 0;
2157         int i;
2158
2159         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2160                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2161
2162         return size;
2163 }
2164
2165 static void
2166 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2167                         const struct drm_framebuffer *fb,
2168                         unsigned int rotation)
2169 {
2170         if (intel_rotation_90_or_270(rotation)) {
2171                 *view = i915_ggtt_view_rotated;
2172                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2173         } else {
2174                 *view = i915_ggtt_view_normal;
2175         }
2176 }
2177
2178 static void
2179 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2180                    struct drm_framebuffer *fb)
2181 {
2182         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2183         unsigned int tile_size, tile_width, tile_height, cpp;
2184
2185         tile_size = intel_tile_size(dev_priv);
2186
2187         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2188         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2189                         fb->modifier[0], cpp);
2190
2191         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2192         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2193
2194         if (info->pixel_format == DRM_FORMAT_NV12) {
2195                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2196                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2197                                 fb->modifier[1], cpp);
2198
2199                 info->uv_offset = fb->offsets[1];
2200                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2201                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2202         }
2203 }
2204
2205 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2206 {
2207         if (INTEL_INFO(dev_priv)->gen >= 9)
2208                 return 256 * 1024;
2209         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2210                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2211                 return 128 * 1024;
2212         else if (INTEL_INFO(dev_priv)->gen >= 4)
2213                 return 4 * 1024;
2214         else
2215                 return 0;
2216 }
2217
2218 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2219                                          uint64_t fb_modifier)
2220 {
2221         switch (fb_modifier) {
2222         case DRM_FORMAT_MOD_NONE:
2223                 return intel_linear_alignment(dev_priv);
2224         case I915_FORMAT_MOD_X_TILED:
2225                 if (INTEL_INFO(dev_priv)->gen >= 9)
2226                         return 256 * 1024;
2227                 return 0;
2228         case I915_FORMAT_MOD_Y_TILED:
2229         case I915_FORMAT_MOD_Yf_TILED:
2230                 return 1 * 1024 * 1024;
2231         default:
2232                 MISSING_CASE(fb_modifier);
2233                 return 0;
2234         }
2235 }
2236
2237 int
2238 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2239                            unsigned int rotation)
2240 {
2241         struct drm_device *dev = fb->dev;
2242         struct drm_i915_private *dev_priv = dev->dev_private;
2243         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2244         struct i915_ggtt_view view;
2245         u32 alignment;
2246         int ret;
2247
2248         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2249
2250         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2251
2252         intel_fill_fb_ggtt_view(&view, fb, rotation);
2253
2254         /* Note that the w/a also requires 64 PTE of padding following the
2255          * bo. We currently fill all unused PTE with the shadow page and so
2256          * we should always have valid PTE following the scanout preventing
2257          * the VT-d warning.
2258          */
2259         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2260                 alignment = 256 * 1024;
2261
2262         /*
2263          * Global gtt pte registers are special registers which actually forward
2264          * writes to a chunk of system memory. Which means that there is no risk
2265          * that the register values disappear as soon as we call
2266          * intel_runtime_pm_put(), so it is correct to wrap only the
2267          * pin/unpin/fence and not more.
2268          */
2269         intel_runtime_pm_get(dev_priv);
2270
2271         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2272                                                    &view);
2273         if (ret)
2274                 goto err_pm;
2275
2276         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2277          * fence, whereas 965+ only requires a fence if using
2278          * framebuffer compression.  For simplicity, we always install
2279          * a fence as the cost is not that onerous.
2280          */
2281         if (view.type == I915_GGTT_VIEW_NORMAL) {
2282                 ret = i915_gem_object_get_fence(obj);
2283                 if (ret == -EDEADLK) {
2284                         /*
2285                          * -EDEADLK means there are no free fences
2286                          * no pending flips.
2287                          *
2288                          * This is propagated to atomic, but it uses
2289                          * -EDEADLK to force a locking recovery, so
2290                          * change the returned error to -EBUSY.
2291                          */
2292                         ret = -EBUSY;
2293                         goto err_unpin;
2294                 } else if (ret)
2295                         goto err_unpin;
2296
2297                 i915_gem_object_pin_fence(obj);
2298         }
2299
2300         intel_runtime_pm_put(dev_priv);
2301         return 0;
2302
2303 err_unpin:
2304         i915_gem_object_unpin_from_display_plane(obj, &view);
2305 err_pm:
2306         intel_runtime_pm_put(dev_priv);
2307         return ret;
2308 }
2309
2310 void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2311 {
2312         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2313         struct i915_ggtt_view view;
2314
2315         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2316
2317         intel_fill_fb_ggtt_view(&view, fb, rotation);
2318
2319         if (view.type == I915_GGTT_VIEW_NORMAL)
2320                 i915_gem_object_unpin_fence(obj);
2321
2322         i915_gem_object_unpin_from_display_plane(obj, &view);
2323 }
2324
2325 /*
2326  * Adjust the tile offset by moving the difference into
2327  * the x/y offsets.
2328  *
2329  * Input tile dimensions and pitch must already be
2330  * rotated to match x and y, and in pixel units.
2331  */
2332 static u32 intel_adjust_tile_offset(int *x, int *y,
2333                                     unsigned int tile_width,
2334                                     unsigned int tile_height,
2335                                     unsigned int tile_size,
2336                                     unsigned int pitch_tiles,
2337                                     u32 old_offset,
2338                                     u32 new_offset)
2339 {
2340         unsigned int tiles;
2341
2342         WARN_ON(old_offset & (tile_size - 1));
2343         WARN_ON(new_offset & (tile_size - 1));
2344         WARN_ON(new_offset > old_offset);
2345
2346         tiles = (old_offset - new_offset) / tile_size;
2347
2348         *y += tiles / pitch_tiles * tile_height;
2349         *x += tiles % pitch_tiles * tile_width;
2350
2351         return new_offset;
2352 }
2353
2354 /*
2355  * Computes the linear offset to the base tile and adjusts
2356  * x, y. bytes per pixel is assumed to be a power-of-two.
2357  *
2358  * In the 90/270 rotated case, x and y are assumed
2359  * to be already rotated to match the rotated GTT view, and
2360  * pitch is the tile_height aligned framebuffer height.
2361  */
2362 u32 intel_compute_tile_offset(int *x, int *y,
2363                               const struct drm_framebuffer *fb, int plane,
2364                               unsigned int pitch,
2365                               unsigned int rotation)
2366 {
2367         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2368         uint64_t fb_modifier = fb->modifier[plane];
2369         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2370         u32 offset, offset_aligned, alignment;
2371
2372         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2373         if (alignment)
2374                 alignment--;
2375
2376         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2377                 unsigned int tile_size, tile_width, tile_height;
2378                 unsigned int tile_rows, tiles, pitch_tiles;
2379
2380                 tile_size = intel_tile_size(dev_priv);
2381                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2382                                 fb_modifier, cpp);
2383
2384                 if (intel_rotation_90_or_270(rotation)) {
2385                         pitch_tiles = pitch / tile_height;
2386                         swap(tile_width, tile_height);
2387                 } else {
2388                         pitch_tiles = pitch / (tile_width * cpp);
2389                 }
2390
2391                 tile_rows = *y / tile_height;
2392                 *y %= tile_height;
2393
2394                 tiles = *x / tile_width;
2395                 *x %= tile_width;
2396
2397                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2398                 offset_aligned = offset & ~alignment;
2399
2400                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2401                                          tile_size, pitch_tiles,
2402                                          offset, offset_aligned);
2403         } else {
2404                 offset = *y * pitch + *x * cpp;
2405                 offset_aligned = offset & ~alignment;
2406
2407                 *y = (offset & alignment) / pitch;
2408                 *x = ((offset & alignment) - *y * pitch) / cpp;
2409         }
2410
2411         return offset_aligned;
2412 }
2413
2414 static int i9xx_format_to_fourcc(int format)
2415 {
2416         switch (format) {
2417         case DISPPLANE_8BPP:
2418                 return DRM_FORMAT_C8;
2419         case DISPPLANE_BGRX555:
2420                 return DRM_FORMAT_XRGB1555;
2421         case DISPPLANE_BGRX565:
2422                 return DRM_FORMAT_RGB565;
2423         default:
2424         case DISPPLANE_BGRX888:
2425                 return DRM_FORMAT_XRGB8888;
2426         case DISPPLANE_RGBX888:
2427                 return DRM_FORMAT_XBGR8888;
2428         case DISPPLANE_BGRX101010:
2429                 return DRM_FORMAT_XRGB2101010;
2430         case DISPPLANE_RGBX101010:
2431                 return DRM_FORMAT_XBGR2101010;
2432         }
2433 }
2434
2435 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2436 {
2437         switch (format) {
2438         case PLANE_CTL_FORMAT_RGB_565:
2439                 return DRM_FORMAT_RGB565;
2440         default:
2441         case PLANE_CTL_FORMAT_XRGB_8888:
2442                 if (rgb_order) {
2443                         if (alpha)
2444                                 return DRM_FORMAT_ABGR8888;
2445                         else
2446                                 return DRM_FORMAT_XBGR8888;
2447                 } else {
2448                         if (alpha)
2449                                 return DRM_FORMAT_ARGB8888;
2450                         else
2451                                 return DRM_FORMAT_XRGB8888;
2452                 }
2453         case PLANE_CTL_FORMAT_XRGB_2101010:
2454                 if (rgb_order)
2455                         return DRM_FORMAT_XBGR2101010;
2456                 else
2457                         return DRM_FORMAT_XRGB2101010;
2458         }
2459 }
2460
2461 static bool
2462 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2463                               struct intel_initial_plane_config *plane_config)
2464 {
2465         struct drm_device *dev = crtc->base.dev;
2466         struct drm_i915_private *dev_priv = to_i915(dev);
2467         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2468         struct drm_i915_gem_object *obj = NULL;
2469         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2470         struct drm_framebuffer *fb = &plane_config->fb->base;
2471         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2472         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2473                                     PAGE_SIZE);
2474
2475         size_aligned -= base_aligned;
2476
2477         if (plane_config->size == 0)
2478                 return false;
2479
2480         /* If the FB is too big, just don't use it since fbdev is not very
2481          * important and we should probably use that space with FBC or other
2482          * features. */
2483         if (size_aligned * 2 > ggtt->stolen_usable_size)
2484                 return false;
2485
2486         mutex_lock(&dev->struct_mutex);
2487
2488         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2489                                                              base_aligned,
2490                                                              base_aligned,
2491                                                              size_aligned);
2492         if (!obj) {
2493                 mutex_unlock(&dev->struct_mutex);
2494                 return false;
2495         }
2496
2497         obj->tiling_mode = plane_config->tiling;
2498         if (obj->tiling_mode == I915_TILING_X)
2499                 obj->stride = fb->pitches[0];
2500
2501         mode_cmd.pixel_format = fb->pixel_format;
2502         mode_cmd.width = fb->width;
2503         mode_cmd.height = fb->height;
2504         mode_cmd.pitches[0] = fb->pitches[0];
2505         mode_cmd.modifier[0] = fb->modifier[0];
2506         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2507
2508         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2509                                    &mode_cmd, obj)) {
2510                 DRM_DEBUG_KMS("intel fb init failed\n");
2511                 goto out_unref_obj;
2512         }
2513
2514         mutex_unlock(&dev->struct_mutex);
2515
2516         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2517         return true;
2518
2519 out_unref_obj:
2520         drm_gem_object_unreference(&obj->base);
2521         mutex_unlock(&dev->struct_mutex);
2522         return false;
2523 }
2524
2525 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2526 static void
2527 update_state_fb(struct drm_plane *plane)
2528 {
2529         if (plane->fb == plane->state->fb)
2530                 return;
2531
2532         if (plane->state->fb)
2533                 drm_framebuffer_unreference(plane->state->fb);
2534         plane->state->fb = plane->fb;
2535         if (plane->state->fb)
2536                 drm_framebuffer_reference(plane->state->fb);
2537 }
2538
2539 static void
2540 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2541                              struct intel_initial_plane_config *plane_config)
2542 {
2543         struct drm_device *dev = intel_crtc->base.dev;
2544         struct drm_i915_private *dev_priv = dev->dev_private;
2545         struct drm_crtc *c;
2546         struct intel_crtc *i;
2547         struct drm_i915_gem_object *obj;
2548         struct drm_plane *primary = intel_crtc->base.primary;
2549         struct drm_plane_state *plane_state = primary->state;
2550         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2551         struct intel_plane *intel_plane = to_intel_plane(primary);
2552         struct intel_plane_state *intel_state =
2553                 to_intel_plane_state(plane_state);
2554         struct drm_framebuffer *fb;
2555
2556         if (!plane_config->fb)
2557                 return;
2558
2559         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2560                 fb = &plane_config->fb->base;
2561                 goto valid_fb;
2562         }
2563
2564         kfree(plane_config->fb);
2565
2566         /*
2567          * Failed to alloc the obj, check to see if we should share
2568          * an fb with another CRTC instead
2569          */
2570         for_each_crtc(dev, c) {
2571                 i = to_intel_crtc(c);
2572
2573                 if (c == &intel_crtc->base)
2574                         continue;
2575
2576                 if (!i->active)
2577                         continue;
2578
2579                 fb = c->primary->fb;
2580                 if (!fb)
2581                         continue;
2582
2583                 obj = intel_fb_obj(fb);
2584                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2585                         drm_framebuffer_reference(fb);
2586                         goto valid_fb;
2587                 }
2588         }
2589
2590         /*
2591          * We've failed to reconstruct the BIOS FB.  Current display state
2592          * indicates that the primary plane is visible, but has a NULL FB,
2593          * which will lead to problems later if we don't fix it up.  The
2594          * simplest solution is to just disable the primary plane now and
2595          * pretend the BIOS never had it enabled.
2596          */
2597         to_intel_plane_state(plane_state)->visible = false;
2598         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2599         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2600         intel_plane->disable_plane(primary, &intel_crtc->base);
2601
2602         return;
2603
2604 valid_fb:
2605         plane_state->src_x = 0;
2606         plane_state->src_y = 0;
2607         plane_state->src_w = fb->width << 16;
2608         plane_state->src_h = fb->height << 16;
2609
2610         plane_state->crtc_x = 0;
2611         plane_state->crtc_y = 0;
2612         plane_state->crtc_w = fb->width;
2613         plane_state->crtc_h = fb->height;
2614
2615         intel_state->src.x1 = plane_state->src_x;
2616         intel_state->src.y1 = plane_state->src_y;
2617         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2618         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2619         intel_state->dst.x1 = plane_state->crtc_x;
2620         intel_state->dst.y1 = plane_state->crtc_y;
2621         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2622         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2623
2624         obj = intel_fb_obj(fb);
2625         if (obj->tiling_mode != I915_TILING_NONE)
2626                 dev_priv->preserve_bios_swizzle = true;
2627
2628         drm_framebuffer_reference(fb);
2629         primary->fb = primary->state->fb = fb;
2630         primary->crtc = primary->state->crtc = &intel_crtc->base;
2631         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2632         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2633 }
2634
2635 static void i9xx_update_primary_plane(struct drm_plane *primary,
2636                                       const struct intel_crtc_state *crtc_state,
2637                                       const struct intel_plane_state *plane_state)
2638 {
2639         struct drm_device *dev = primary->dev;
2640         struct drm_i915_private *dev_priv = dev->dev_private;
2641         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2642         struct drm_framebuffer *fb = plane_state->base.fb;
2643         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2644         int plane = intel_crtc->plane;
2645         u32 linear_offset;
2646         u32 dspcntr;
2647         i915_reg_t reg = DSPCNTR(plane);
2648         unsigned int rotation = plane_state->base.rotation;
2649         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2650         int x = plane_state->src.x1 >> 16;
2651         int y = plane_state->src.y1 >> 16;
2652
2653         dspcntr = DISPPLANE_GAMMA_ENABLE;
2654
2655         dspcntr |= DISPLAY_PLANE_ENABLE;
2656
2657         if (INTEL_INFO(dev)->gen < 4) {
2658                 if (intel_crtc->pipe == PIPE_B)
2659                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2660
2661                 /* pipesrc and dspsize control the size that is scaled from,
2662                  * which should always be the user's requested size.
2663                  */
2664                 I915_WRITE(DSPSIZE(plane),
2665                            ((crtc_state->pipe_src_h - 1) << 16) |
2666                            (crtc_state->pipe_src_w - 1));
2667                 I915_WRITE(DSPPOS(plane), 0);
2668         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2669                 I915_WRITE(PRIMSIZE(plane),
2670                            ((crtc_state->pipe_src_h - 1) << 16) |
2671                            (crtc_state->pipe_src_w - 1));
2672                 I915_WRITE(PRIMPOS(plane), 0);
2673                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2674         }
2675
2676         switch (fb->pixel_format) {
2677         case DRM_FORMAT_C8:
2678                 dspcntr |= DISPPLANE_8BPP;
2679                 break;
2680         case DRM_FORMAT_XRGB1555:
2681                 dspcntr |= DISPPLANE_BGRX555;
2682                 break;
2683         case DRM_FORMAT_RGB565:
2684                 dspcntr |= DISPPLANE_BGRX565;
2685                 break;
2686         case DRM_FORMAT_XRGB8888:
2687                 dspcntr |= DISPPLANE_BGRX888;
2688                 break;
2689         case DRM_FORMAT_XBGR8888:
2690                 dspcntr |= DISPPLANE_RGBX888;
2691                 break;
2692         case DRM_FORMAT_XRGB2101010:
2693                 dspcntr |= DISPPLANE_BGRX101010;
2694                 break;
2695         case DRM_FORMAT_XBGR2101010:
2696                 dspcntr |= DISPPLANE_RGBX101010;
2697                 break;
2698         default:
2699                 BUG();
2700         }
2701
2702         if (INTEL_INFO(dev)->gen >= 4 &&
2703             obj->tiling_mode != I915_TILING_NONE)
2704                 dspcntr |= DISPPLANE_TILED;
2705
2706         if (IS_G4X(dev))
2707                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2708
2709         linear_offset = y * fb->pitches[0] + x * cpp;
2710
2711         if (INTEL_INFO(dev)->gen >= 4) {
2712                 intel_crtc->dspaddr_offset =
2713                         intel_compute_tile_offset(&x, &y, fb, 0,
2714                                                   fb->pitches[0], rotation);
2715                 linear_offset -= intel_crtc->dspaddr_offset;
2716         } else {
2717                 intel_crtc->dspaddr_offset = linear_offset;
2718         }
2719
2720         if (rotation == BIT(DRM_ROTATE_180)) {
2721                 dspcntr |= DISPPLANE_ROTATE_180;
2722
2723                 x += (crtc_state->pipe_src_w - 1);
2724                 y += (crtc_state->pipe_src_h - 1);
2725
2726                 /* Finding the last pixel of the last line of the display
2727                 data and adding to linear_offset*/
2728                 linear_offset +=
2729                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2730                         (crtc_state->pipe_src_w - 1) * cpp;
2731         }
2732
2733         intel_crtc->adjusted_x = x;
2734         intel_crtc->adjusted_y = y;
2735
2736         I915_WRITE(reg, dspcntr);
2737
2738         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2739         if (INTEL_INFO(dev)->gen >= 4) {
2740                 I915_WRITE(DSPSURF(plane),
2741                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2742                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2743                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2744         } else
2745                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2746         POSTING_READ(reg);
2747 }
2748
2749 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2750                                        struct drm_crtc *crtc)
2751 {
2752         struct drm_device *dev = crtc->dev;
2753         struct drm_i915_private *dev_priv = dev->dev_private;
2754         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2755         int plane = intel_crtc->plane;
2756
2757         I915_WRITE(DSPCNTR(plane), 0);
2758         if (INTEL_INFO(dev_priv)->gen >= 4)
2759                 I915_WRITE(DSPSURF(plane), 0);
2760         else
2761                 I915_WRITE(DSPADDR(plane), 0);
2762         POSTING_READ(DSPCNTR(plane));
2763 }
2764
2765 static void ironlake_update_primary_plane(struct drm_plane *primary,
2766                                           const struct intel_crtc_state *crtc_state,
2767                                           const struct intel_plane_state *plane_state)
2768 {
2769         struct drm_device *dev = primary->dev;
2770         struct drm_i915_private *dev_priv = dev->dev_private;
2771         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2772         struct drm_framebuffer *fb = plane_state->base.fb;
2773         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2774         int plane = intel_crtc->plane;
2775         u32 linear_offset;
2776         u32 dspcntr;
2777         i915_reg_t reg = DSPCNTR(plane);
2778         unsigned int rotation = plane_state->base.rotation;
2779         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2780         int x = plane_state->src.x1 >> 16;
2781         int y = plane_state->src.y1 >> 16;
2782
2783         dspcntr = DISPPLANE_GAMMA_ENABLE;
2784         dspcntr |= DISPLAY_PLANE_ENABLE;
2785
2786         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2787                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2788
2789         switch (fb->pixel_format) {
2790         case DRM_FORMAT_C8:
2791                 dspcntr |= DISPPLANE_8BPP;
2792                 break;
2793         case DRM_FORMAT_RGB565:
2794                 dspcntr |= DISPPLANE_BGRX565;
2795                 break;
2796         case DRM_FORMAT_XRGB8888:
2797                 dspcntr |= DISPPLANE_BGRX888;
2798                 break;
2799         case DRM_FORMAT_XBGR8888:
2800                 dspcntr |= DISPPLANE_RGBX888;
2801                 break;
2802         case DRM_FORMAT_XRGB2101010:
2803                 dspcntr |= DISPPLANE_BGRX101010;
2804                 break;
2805         case DRM_FORMAT_XBGR2101010:
2806                 dspcntr |= DISPPLANE_RGBX101010;
2807                 break;
2808         default:
2809                 BUG();
2810         }
2811
2812         if (obj->tiling_mode != I915_TILING_NONE)
2813                 dspcntr |= DISPPLANE_TILED;
2814
2815         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2816                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2817
2818         linear_offset = y * fb->pitches[0] + x * cpp;
2819         intel_crtc->dspaddr_offset =
2820                 intel_compute_tile_offset(&x, &y, fb, 0,
2821                                           fb->pitches[0], rotation);
2822         linear_offset -= intel_crtc->dspaddr_offset;
2823         if (rotation == BIT(DRM_ROTATE_180)) {
2824                 dspcntr |= DISPPLANE_ROTATE_180;
2825
2826                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2827                         x += (crtc_state->pipe_src_w - 1);
2828                         y += (crtc_state->pipe_src_h - 1);
2829
2830                         /* Finding the last pixel of the last line of the display
2831                         data and adding to linear_offset*/
2832                         linear_offset +=
2833                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2834                                 (crtc_state->pipe_src_w - 1) * cpp;
2835                 }
2836         }
2837
2838         intel_crtc->adjusted_x = x;
2839         intel_crtc->adjusted_y = y;
2840
2841         I915_WRITE(reg, dspcntr);
2842
2843         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2844         I915_WRITE(DSPSURF(plane),
2845                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2846         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2847                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2848         } else {
2849                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2850                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2851         }
2852         POSTING_READ(reg);
2853 }
2854
2855 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2856                               uint64_t fb_modifier, uint32_t pixel_format)
2857 {
2858         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2859                 return 64;
2860         } else {
2861                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2862
2863                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2864         }
2865 }
2866
2867 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2868                            struct drm_i915_gem_object *obj,
2869                            unsigned int plane)
2870 {
2871         struct i915_ggtt_view view;
2872         struct i915_vma *vma;
2873         u64 offset;
2874
2875         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2876                                 intel_plane->base.state->rotation);
2877
2878         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2879         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2880                 view.type))
2881                 return -1;
2882
2883         offset = vma->node.start;
2884
2885         if (plane == 1) {
2886                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2887                           PAGE_SIZE;
2888         }
2889
2890         WARN_ON(upper_32_bits(offset));
2891
2892         return lower_32_bits(offset);
2893 }
2894
2895 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2896 {
2897         struct drm_device *dev = intel_crtc->base.dev;
2898         struct drm_i915_private *dev_priv = dev->dev_private;
2899
2900         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2901         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2902         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2903 }
2904
2905 /*
2906  * This function detaches (aka. unbinds) unused scalers in hardware
2907  */
2908 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2909 {
2910         struct intel_crtc_scaler_state *scaler_state;
2911         int i;
2912
2913         scaler_state = &intel_crtc->config->scaler_state;
2914
2915         /* loop through and disable scalers that aren't in use */
2916         for (i = 0; i < intel_crtc->num_scalers; i++) {
2917                 if (!scaler_state->scalers[i].in_use)
2918                         skl_detach_scaler(intel_crtc, i);
2919         }
2920 }
2921
2922 u32 skl_plane_ctl_format(uint32_t pixel_format)
2923 {
2924         switch (pixel_format) {
2925         case DRM_FORMAT_C8:
2926                 return PLANE_CTL_FORMAT_INDEXED;
2927         case DRM_FORMAT_RGB565:
2928                 return PLANE_CTL_FORMAT_RGB_565;
2929         case DRM_FORMAT_XBGR8888:
2930                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2931         case DRM_FORMAT_XRGB8888:
2932                 return PLANE_CTL_FORMAT_XRGB_8888;
2933         /*
2934          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2935          * to be already pre-multiplied. We need to add a knob (or a different
2936          * DRM_FORMAT) for user-space to configure that.
2937          */
2938         case DRM_FORMAT_ABGR8888:
2939                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2940                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2941         case DRM_FORMAT_ARGB8888:
2942                 return PLANE_CTL_FORMAT_XRGB_8888 |
2943                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2944         case DRM_FORMAT_XRGB2101010:
2945                 return PLANE_CTL_FORMAT_XRGB_2101010;
2946         case DRM_FORMAT_XBGR2101010:
2947                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2948         case DRM_FORMAT_YUYV:
2949                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2950         case DRM_FORMAT_YVYU:
2951                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2952         case DRM_FORMAT_UYVY:
2953                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2954         case DRM_FORMAT_VYUY:
2955                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2956         default:
2957                 MISSING_CASE(pixel_format);
2958         }
2959
2960         return 0;
2961 }
2962
2963 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2964 {
2965         switch (fb_modifier) {
2966         case DRM_FORMAT_MOD_NONE:
2967                 break;
2968         case I915_FORMAT_MOD_X_TILED:
2969                 return PLANE_CTL_TILED_X;
2970         case I915_FORMAT_MOD_Y_TILED:
2971                 return PLANE_CTL_TILED_Y;
2972         case I915_FORMAT_MOD_Yf_TILED:
2973                 return PLANE_CTL_TILED_YF;
2974         default:
2975                 MISSING_CASE(fb_modifier);
2976         }
2977
2978         return 0;
2979 }
2980
2981 u32 skl_plane_ctl_rotation(unsigned int rotation)
2982 {
2983         switch (rotation) {
2984         case BIT(DRM_ROTATE_0):
2985                 break;
2986         /*
2987          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2988          * while i915 HW rotation is clockwise, thats why this swapping.
2989          */
2990         case BIT(DRM_ROTATE_90):
2991                 return PLANE_CTL_ROTATE_270;
2992         case BIT(DRM_ROTATE_180):
2993                 return PLANE_CTL_ROTATE_180;
2994         case BIT(DRM_ROTATE_270):
2995                 return PLANE_CTL_ROTATE_90;
2996         default:
2997                 MISSING_CASE(rotation);
2998         }
2999
3000         return 0;
3001 }
3002
3003 static void skylake_update_primary_plane(struct drm_plane *plane,
3004                                          const struct intel_crtc_state *crtc_state,
3005                                          const struct intel_plane_state *plane_state)
3006 {
3007         struct drm_device *dev = plane->dev;
3008         struct drm_i915_private *dev_priv = dev->dev_private;
3009         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3010         struct drm_framebuffer *fb = plane_state->base.fb;
3011         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3012         int pipe = intel_crtc->pipe;
3013         u32 plane_ctl, stride_div, stride;
3014         u32 tile_height, plane_offset, plane_size;
3015         unsigned int rotation = plane_state->base.rotation;
3016         int x_offset, y_offset;
3017         u32 surf_addr;
3018         int scaler_id = plane_state->scaler_id;
3019         int src_x = plane_state->src.x1 >> 16;
3020         int src_y = plane_state->src.y1 >> 16;
3021         int src_w = drm_rect_width(&plane_state->src) >> 16;
3022         int src_h = drm_rect_height(&plane_state->src) >> 16;
3023         int dst_x = plane_state->dst.x1;
3024         int dst_y = plane_state->dst.y1;
3025         int dst_w = drm_rect_width(&plane_state->dst);
3026         int dst_h = drm_rect_height(&plane_state->dst);
3027
3028         plane_ctl = PLANE_CTL_ENABLE |
3029                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3030                     PLANE_CTL_PIPE_CSC_ENABLE;
3031
3032         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3033         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3034         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3035         plane_ctl |= skl_plane_ctl_rotation(rotation);
3036
3037         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3038                                                fb->pixel_format);
3039         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3040
3041         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3042
3043         if (intel_rotation_90_or_270(rotation)) {
3044                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3045
3046                 /* stride = Surface height in tiles */
3047                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3048                 stride = DIV_ROUND_UP(fb->height, tile_height);
3049                 x_offset = stride * tile_height - src_y - src_h;
3050                 y_offset = src_x;
3051                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3052         } else {
3053                 stride = fb->pitches[0] / stride_div;
3054                 x_offset = src_x;
3055                 y_offset = src_y;
3056                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3057         }
3058         plane_offset = y_offset << 16 | x_offset;
3059
3060         intel_crtc->adjusted_x = x_offset;
3061         intel_crtc->adjusted_y = y_offset;
3062
3063         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3064         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3065         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3066         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3067
3068         if (scaler_id >= 0) {
3069                 uint32_t ps_ctrl = 0;
3070
3071                 WARN_ON(!dst_w || !dst_h);
3072                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3073                         crtc_state->scaler_state.scalers[scaler_id].mode;
3074                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3075                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3076                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3077                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3078                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3079         } else {
3080                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3081         }
3082
3083         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3084
3085         POSTING_READ(PLANE_SURF(pipe, 0));
3086 }
3087
3088 static void skylake_disable_primary_plane(struct drm_plane *primary,
3089                                           struct drm_crtc *crtc)
3090 {
3091         struct drm_device *dev = crtc->dev;
3092         struct drm_i915_private *dev_priv = dev->dev_private;
3093         int pipe = to_intel_crtc(crtc)->pipe;
3094
3095         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3096         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3097         POSTING_READ(PLANE_SURF(pipe, 0));
3098 }
3099
3100 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3101 static int
3102 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3103                            int x, int y, enum mode_set_atomic state)
3104 {
3105         /* Support for kgdboc is disabled, this needs a major rework. */
3106         DRM_ERROR("legacy panic handler not supported any more.\n");
3107
3108         return -ENODEV;
3109 }
3110
3111 static void intel_complete_page_flips(struct drm_i915_private *dev_priv)
3112 {
3113         struct drm_crtc *crtc;
3114
3115         for_each_crtc(dev_priv->dev, crtc) {
3116                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3117                 enum plane plane = intel_crtc->plane;
3118
3119                 intel_prepare_page_flip(dev_priv, plane);
3120                 intel_finish_page_flip_plane(dev_priv, plane);
3121         }
3122 }
3123
3124 static void intel_update_primary_planes(struct drm_device *dev)
3125 {
3126         struct drm_crtc *crtc;
3127
3128         for_each_crtc(dev, crtc) {
3129                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3130                 struct intel_plane_state *plane_state;
3131
3132                 drm_modeset_lock_crtc(crtc, &plane->base);
3133                 plane_state = to_intel_plane_state(plane->base.state);
3134
3135                 if (plane_state->visible)
3136                         plane->update_plane(&plane->base,
3137                                             to_intel_crtc_state(crtc->state),
3138                                             plane_state);
3139
3140                 drm_modeset_unlock_crtc(crtc);
3141         }
3142 }
3143
3144 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3145 {
3146         /* no reset support for gen2 */
3147         if (IS_GEN2(dev_priv))
3148                 return;
3149
3150         /* reset doesn't touch the display */
3151         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
3152                 return;
3153
3154         drm_modeset_lock_all(dev_priv->dev);
3155         /*
3156          * Disabling the crtcs gracefully seems nicer. Also the
3157          * g33 docs say we should at least disable all the planes.
3158          */
3159         intel_display_suspend(dev_priv->dev);
3160 }
3161
3162 void intel_finish_reset(struct drm_i915_private *dev_priv)
3163 {
3164         /*
3165          * Flips in the rings will be nuked by the reset,
3166          * so complete all pending flips so that user space
3167          * will get its events and not get stuck.
3168          */
3169         intel_complete_page_flips(dev_priv);
3170
3171         /* no reset support for gen2 */
3172         if (IS_GEN2(dev_priv))
3173                 return;
3174
3175         /* reset doesn't touch the display */
3176         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv)) {
3177                 /*
3178                  * Flips in the rings have been nuked by the reset,
3179                  * so update the base address of all primary
3180                  * planes to the the last fb to make sure we're
3181                  * showing the correct fb after a reset.
3182                  *
3183                  * FIXME: Atomic will make this obsolete since we won't schedule
3184                  * CS-based flips (which might get lost in gpu resets) any more.
3185                  */
3186                 intel_update_primary_planes(dev_priv->dev);
3187                 return;
3188         }
3189
3190         /*
3191          * The display has been reset as well,
3192          * so need a full re-initialization.
3193          */
3194         intel_runtime_pm_disable_interrupts(dev_priv);
3195         intel_runtime_pm_enable_interrupts(dev_priv);
3196
3197         intel_modeset_init_hw(dev_priv->dev);
3198
3199         spin_lock_irq(&dev_priv->irq_lock);
3200         if (dev_priv->display.hpd_irq_setup)
3201                 dev_priv->display.hpd_irq_setup(dev_priv);
3202         spin_unlock_irq(&dev_priv->irq_lock);
3203
3204         intel_display_resume(dev_priv->dev);
3205
3206         intel_hpd_init(dev_priv);
3207
3208         drm_modeset_unlock_all(dev_priv->dev);
3209 }
3210
3211 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3212 {
3213         struct drm_device *dev = crtc->dev;
3214         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3215         unsigned reset_counter;
3216         bool pending;
3217
3218         reset_counter = i915_reset_counter(&to_i915(dev)->gpu_error);
3219         if (intel_crtc->reset_counter != reset_counter)
3220                 return false;
3221
3222         spin_lock_irq(&dev->event_lock);
3223         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3224         spin_unlock_irq(&dev->event_lock);
3225
3226         return pending;
3227 }
3228
3229 static void intel_update_pipe_config(struct intel_crtc *crtc,
3230                                      struct intel_crtc_state *old_crtc_state)
3231 {
3232         struct drm_device *dev = crtc->base.dev;
3233         struct drm_i915_private *dev_priv = dev->dev_private;
3234         struct intel_crtc_state *pipe_config =
3235                 to_intel_crtc_state(crtc->base.state);
3236
3237         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3238         crtc->base.mode = crtc->base.state->mode;
3239
3240         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3241                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3242                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3243
3244         /*
3245          * Update pipe size and adjust fitter if needed: the reason for this is
3246          * that in compute_mode_changes we check the native mode (not the pfit
3247          * mode) to see if we can flip rather than do a full mode set. In the
3248          * fastboot case, we'll flip, but if we don't update the pipesrc and
3249          * pfit state, we'll end up with a big fb scanned out into the wrong
3250          * sized surface.
3251          */
3252
3253         I915_WRITE(PIPESRC(crtc->pipe),
3254                    ((pipe_config->pipe_src_w - 1) << 16) |
3255                    (pipe_config->pipe_src_h - 1));
3256
3257         /* on skylake this is done by detaching scalers */
3258         if (INTEL_INFO(dev)->gen >= 9) {
3259                 skl_detach_scalers(crtc);
3260
3261                 if (pipe_config->pch_pfit.enabled)
3262                         skylake_pfit_enable(crtc);
3263         } else if (HAS_PCH_SPLIT(dev)) {
3264                 if (pipe_config->pch_pfit.enabled)
3265                         ironlake_pfit_enable(crtc);
3266                 else if (old_crtc_state->pch_pfit.enabled)
3267                         ironlake_pfit_disable(crtc, true);
3268         }
3269 }
3270
3271 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3272 {
3273         struct drm_device *dev = crtc->dev;
3274         struct drm_i915_private *dev_priv = dev->dev_private;
3275         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3276         int pipe = intel_crtc->pipe;
3277         i915_reg_t reg;
3278         u32 temp;
3279
3280         /* enable normal train */
3281         reg = FDI_TX_CTL(pipe);
3282         temp = I915_READ(reg);
3283         if (IS_IVYBRIDGE(dev)) {
3284                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3285                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3286         } else {
3287                 temp &= ~FDI_LINK_TRAIN_NONE;
3288                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3289         }
3290         I915_WRITE(reg, temp);
3291
3292         reg = FDI_RX_CTL(pipe);
3293         temp = I915_READ(reg);
3294         if (HAS_PCH_CPT(dev)) {
3295                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3296                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3297         } else {
3298                 temp &= ~FDI_LINK_TRAIN_NONE;
3299                 temp |= FDI_LINK_TRAIN_NONE;
3300         }
3301         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3302
3303         /* wait one idle pattern time */
3304         POSTING_READ(reg);
3305         udelay(1000);
3306
3307         /* IVB wants error correction enabled */
3308         if (IS_IVYBRIDGE(dev))
3309                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3310                            FDI_FE_ERRC_ENABLE);
3311 }
3312
3313 /* The FDI link training functions for ILK/Ibexpeak. */
3314 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3315 {
3316         struct drm_device *dev = crtc->dev;
3317         struct drm_i915_private *dev_priv = dev->dev_private;
3318         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3319         int pipe = intel_crtc->pipe;
3320         i915_reg_t reg;
3321         u32 temp, tries;
3322
3323         /* FDI needs bits from pipe first */
3324         assert_pipe_enabled(dev_priv, pipe);
3325
3326         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3327            for train result */
3328         reg = FDI_RX_IMR(pipe);
3329         temp = I915_READ(reg);
3330         temp &= ~FDI_RX_SYMBOL_LOCK;
3331         temp &= ~FDI_RX_BIT_LOCK;
3332         I915_WRITE(reg, temp);
3333         I915_READ(reg);
3334         udelay(150);
3335
3336         /* enable CPU FDI TX and PCH FDI RX */
3337         reg = FDI_TX_CTL(pipe);
3338         temp = I915_READ(reg);
3339         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3340         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3341         temp &= ~FDI_LINK_TRAIN_NONE;
3342         temp |= FDI_LINK_TRAIN_PATTERN_1;
3343         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3344
3345         reg = FDI_RX_CTL(pipe);
3346         temp = I915_READ(reg);
3347         temp &= ~FDI_LINK_TRAIN_NONE;
3348         temp |= FDI_LINK_TRAIN_PATTERN_1;
3349         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3350
3351         POSTING_READ(reg);
3352         udelay(150);
3353
3354         /* Ironlake workaround, enable clock pointer after FDI enable*/
3355         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3356         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3357                    FDI_RX_PHASE_SYNC_POINTER_EN);
3358
3359         reg = FDI_RX_IIR(pipe);
3360         for (tries = 0; tries < 5; tries++) {
3361                 temp = I915_READ(reg);
3362                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3363
3364                 if ((temp & FDI_RX_BIT_LOCK)) {
3365                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3366                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3367                         break;
3368                 }
3369         }
3370         if (tries == 5)
3371                 DRM_ERROR("FDI train 1 fail!\n");
3372
3373         /* Train 2 */
3374         reg = FDI_TX_CTL(pipe);
3375         temp = I915_READ(reg);
3376         temp &= ~FDI_LINK_TRAIN_NONE;
3377         temp |= FDI_LINK_TRAIN_PATTERN_2;
3378         I915_WRITE(reg, temp);
3379
3380         reg = FDI_RX_CTL(pipe);
3381         temp = I915_READ(reg);
3382         temp &= ~FDI_LINK_TRAIN_NONE;
3383         temp |= FDI_LINK_TRAIN_PATTERN_2;
3384         I915_WRITE(reg, temp);
3385
3386         POSTING_READ(reg);
3387         udelay(150);
3388
3389         reg = FDI_RX_IIR(pipe);
3390         for (tries = 0; tries < 5; tries++) {
3391                 temp = I915_READ(reg);
3392                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3393
3394                 if (temp & FDI_RX_SYMBOL_LOCK) {
3395                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3396                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3397                         break;
3398                 }
3399         }
3400         if (tries == 5)
3401                 DRM_ERROR("FDI train 2 fail!\n");
3402
3403         DRM_DEBUG_KMS("FDI train done\n");
3404
3405 }
3406
3407 static const int snb_b_fdi_train_param[] = {
3408         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3409         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3410         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3411         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3412 };
3413
3414 /* The FDI link training functions for SNB/Cougarpoint. */
3415 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3416 {
3417         struct drm_device *dev = crtc->dev;
3418         struct drm_i915_private *dev_priv = dev->dev_private;
3419         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3420         int pipe = intel_crtc->pipe;
3421         i915_reg_t reg;
3422         u32 temp, i, retry;
3423
3424         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3425            for train result */
3426         reg = FDI_RX_IMR(pipe);
3427         temp = I915_READ(reg);
3428         temp &= ~FDI_RX_SYMBOL_LOCK;
3429         temp &= ~FDI_RX_BIT_LOCK;
3430         I915_WRITE(reg, temp);
3431
3432         POSTING_READ(reg);
3433         udelay(150);
3434
3435         /* enable CPU FDI TX and PCH FDI RX */
3436         reg = FDI_TX_CTL(pipe);
3437         temp = I915_READ(reg);
3438         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3439         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3440         temp &= ~FDI_LINK_TRAIN_NONE;
3441         temp |= FDI_LINK_TRAIN_PATTERN_1;
3442         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3443         /* SNB-B */
3444         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3445         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3446
3447         I915_WRITE(FDI_RX_MISC(pipe),
3448                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3449
3450         reg = FDI_RX_CTL(pipe);
3451         temp = I915_READ(reg);
3452         if (HAS_PCH_CPT(dev)) {
3453                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3454                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3455         } else {
3456                 temp &= ~FDI_LINK_TRAIN_NONE;
3457                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3458         }
3459         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3460
3461         POSTING_READ(reg);
3462         udelay(150);
3463
3464         for (i = 0; i < 4; i++) {
3465                 reg = FDI_TX_CTL(pipe);
3466                 temp = I915_READ(reg);
3467                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3468                 temp |= snb_b_fdi_train_param[i];
3469                 I915_WRITE(reg, temp);
3470
3471                 POSTING_READ(reg);
3472                 udelay(500);
3473
3474                 for (retry = 0; retry < 5; retry++) {
3475                         reg = FDI_RX_IIR(pipe);
3476                         temp = I915_READ(reg);
3477                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3478                         if (temp & FDI_RX_BIT_LOCK) {
3479                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3480                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3481                                 break;
3482                         }
3483                         udelay(50);
3484                 }
3485                 if (retry < 5)
3486                         break;
3487         }
3488         if (i == 4)
3489                 DRM_ERROR("FDI train 1 fail!\n");
3490
3491         /* Train 2 */
3492         reg = FDI_TX_CTL(pipe);
3493         temp = I915_READ(reg);
3494         temp &= ~FDI_LINK_TRAIN_NONE;
3495         temp |= FDI_LINK_TRAIN_PATTERN_2;
3496         if (IS_GEN6(dev)) {
3497                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3498                 /* SNB-B */
3499                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3500         }
3501         I915_WRITE(reg, temp);
3502
3503         reg = FDI_RX_CTL(pipe);
3504         temp = I915_READ(reg);
3505         if (HAS_PCH_CPT(dev)) {
3506                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3507                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3508         } else {
3509                 temp &= ~FDI_LINK_TRAIN_NONE;
3510                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3511         }
3512         I915_WRITE(reg, temp);
3513
3514         POSTING_READ(reg);
3515         udelay(150);
3516
3517         for (i = 0; i < 4; i++) {
3518                 reg = FDI_TX_CTL(pipe);
3519                 temp = I915_READ(reg);
3520                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3521                 temp |= snb_b_fdi_train_param[i];
3522                 I915_WRITE(reg, temp);
3523
3524                 POSTING_READ(reg);
3525                 udelay(500);
3526
3527                 for (retry = 0; retry < 5; retry++) {
3528                         reg = FDI_RX_IIR(pipe);
3529                         temp = I915_READ(reg);
3530                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3531                         if (temp & FDI_RX_SYMBOL_LOCK) {
3532                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3533                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3534                                 break;
3535                         }
3536                         udelay(50);
3537                 }
3538                 if (retry < 5)
3539                         break;
3540         }
3541         if (i == 4)
3542                 DRM_ERROR("FDI train 2 fail!\n");
3543
3544         DRM_DEBUG_KMS("FDI train done.\n");
3545 }
3546
3547 /* Manual link training for Ivy Bridge A0 parts */
3548 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3549 {
3550         struct drm_device *dev = crtc->dev;
3551         struct drm_i915_private *dev_priv = dev->dev_private;
3552         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3553         int pipe = intel_crtc->pipe;
3554         i915_reg_t reg;
3555         u32 temp, i, j;
3556
3557         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3558            for train result */
3559         reg = FDI_RX_IMR(pipe);
3560         temp = I915_READ(reg);
3561         temp &= ~FDI_RX_SYMBOL_LOCK;
3562         temp &= ~FDI_RX_BIT_LOCK;
3563         I915_WRITE(reg, temp);
3564
3565         POSTING_READ(reg);
3566         udelay(150);
3567
3568         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3569                       I915_READ(FDI_RX_IIR(pipe)));
3570
3571         /* Try each vswing and preemphasis setting twice before moving on */
3572         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3573                 /* disable first in case we need to retry */
3574                 reg = FDI_TX_CTL(pipe);
3575                 temp = I915_READ(reg);
3576                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3577                 temp &= ~FDI_TX_ENABLE;
3578                 I915_WRITE(reg, temp);
3579
3580                 reg = FDI_RX_CTL(pipe);
3581                 temp = I915_READ(reg);
3582                 temp &= ~FDI_LINK_TRAIN_AUTO;
3583                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3584                 temp &= ~FDI_RX_ENABLE;
3585                 I915_WRITE(reg, temp);
3586
3587                 /* enable CPU FDI TX and PCH FDI RX */
3588                 reg = FDI_TX_CTL(pipe);
3589                 temp = I915_READ(reg);
3590                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3591                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3592                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3593                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3594                 temp |= snb_b_fdi_train_param[j/2];
3595                 temp |= FDI_COMPOSITE_SYNC;
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                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3604                 temp |= FDI_COMPOSITE_SYNC;
3605                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3606
3607                 POSTING_READ(reg);
3608                 udelay(1); /* should be 0.5us */
3609
3610                 for (i = 0; i < 4; i++) {
3611                         reg = FDI_RX_IIR(pipe);
3612                         temp = I915_READ(reg);
3613                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3614
3615                         if (temp & FDI_RX_BIT_LOCK ||
3616                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3617                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3618                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3619                                               i);
3620                                 break;
3621                         }
3622                         udelay(1); /* should be 0.5us */
3623                 }
3624                 if (i == 4) {
3625                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3626                         continue;
3627                 }
3628
3629                 /* Train 2 */
3630                 reg = FDI_TX_CTL(pipe);
3631                 temp = I915_READ(reg);
3632                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3633                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3634                 I915_WRITE(reg, temp);
3635
3636                 reg = FDI_RX_CTL(pipe);
3637                 temp = I915_READ(reg);
3638                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3639                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3640                 I915_WRITE(reg, temp);
3641
3642                 POSTING_READ(reg);
3643                 udelay(2); /* should be 1.5us */
3644
3645                 for (i = 0; i < 4; i++) {
3646                         reg = FDI_RX_IIR(pipe);
3647                         temp = I915_READ(reg);
3648                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3649
3650                         if (temp & FDI_RX_SYMBOL_LOCK ||
3651                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3652                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3653                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3654                                               i);
3655                                 goto train_done;
3656                         }
3657                         udelay(2); /* should be 1.5us */
3658                 }
3659                 if (i == 4)
3660                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3661         }
3662
3663 train_done:
3664         DRM_DEBUG_KMS("FDI train done.\n");
3665 }
3666
3667 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3668 {
3669         struct drm_device *dev = intel_crtc->base.dev;
3670         struct drm_i915_private *dev_priv = dev->dev_private;
3671         int pipe = intel_crtc->pipe;
3672         i915_reg_t reg;
3673         u32 temp;
3674
3675         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3676         reg = FDI_RX_CTL(pipe);
3677         temp = I915_READ(reg);
3678         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3679         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3680         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3681         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3682
3683         POSTING_READ(reg);
3684         udelay(200);
3685
3686         /* Switch from Rawclk to PCDclk */
3687         temp = I915_READ(reg);
3688         I915_WRITE(reg, temp | FDI_PCDCLK);
3689
3690         POSTING_READ(reg);
3691         udelay(200);
3692
3693         /* Enable CPU FDI TX PLL, always on for Ironlake */
3694         reg = FDI_TX_CTL(pipe);
3695         temp = I915_READ(reg);
3696         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3697                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3698
3699                 POSTING_READ(reg);
3700                 udelay(100);
3701         }
3702 }
3703
3704 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3705 {
3706         struct drm_device *dev = intel_crtc->base.dev;
3707         struct drm_i915_private *dev_priv = dev->dev_private;
3708         int pipe = intel_crtc->pipe;
3709         i915_reg_t reg;
3710         u32 temp;
3711
3712         /* Switch from PCDclk to Rawclk */
3713         reg = FDI_RX_CTL(pipe);
3714         temp = I915_READ(reg);
3715         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3716
3717         /* Disable CPU FDI TX PLL */
3718         reg = FDI_TX_CTL(pipe);
3719         temp = I915_READ(reg);
3720         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3721
3722         POSTING_READ(reg);
3723         udelay(100);
3724
3725         reg = FDI_RX_CTL(pipe);
3726         temp = I915_READ(reg);
3727         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3728
3729         /* Wait for the clocks to turn off. */
3730         POSTING_READ(reg);
3731         udelay(100);
3732 }
3733
3734 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3735 {
3736         struct drm_device *dev = crtc->dev;
3737         struct drm_i915_private *dev_priv = dev->dev_private;
3738         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3739         int pipe = intel_crtc->pipe;
3740         i915_reg_t reg;
3741         u32 temp;
3742
3743         /* disable CPU FDI tx and PCH FDI rx */
3744         reg = FDI_TX_CTL(pipe);
3745         temp = I915_READ(reg);
3746         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3747         POSTING_READ(reg);
3748
3749         reg = FDI_RX_CTL(pipe);
3750         temp = I915_READ(reg);
3751         temp &= ~(0x7 << 16);
3752         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3753         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3754
3755         POSTING_READ(reg);
3756         udelay(100);
3757
3758         /* Ironlake workaround, disable clock pointer after downing FDI */
3759         if (HAS_PCH_IBX(dev))
3760                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3761
3762         /* still set train pattern 1 */
3763         reg = FDI_TX_CTL(pipe);
3764         temp = I915_READ(reg);
3765         temp &= ~FDI_LINK_TRAIN_NONE;
3766         temp |= FDI_LINK_TRAIN_PATTERN_1;
3767         I915_WRITE(reg, temp);
3768
3769         reg = FDI_RX_CTL(pipe);
3770         temp = I915_READ(reg);
3771         if (HAS_PCH_CPT(dev)) {
3772                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3773                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3774         } else {
3775                 temp &= ~FDI_LINK_TRAIN_NONE;
3776                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3777         }
3778         /* BPC in FDI rx is consistent with that in PIPECONF */
3779         temp &= ~(0x07 << 16);
3780         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3781         I915_WRITE(reg, temp);
3782
3783         POSTING_READ(reg);
3784         udelay(100);
3785 }
3786
3787 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3788 {
3789         struct intel_crtc *crtc;
3790
3791         /* Note that we don't need to be called with mode_config.lock here
3792          * as our list of CRTC objects is static for the lifetime of the
3793          * device and so cannot disappear as we iterate. Similarly, we can
3794          * happily treat the predicates as racy, atomic checks as userspace
3795          * cannot claim and pin a new fb without at least acquring the
3796          * struct_mutex and so serialising with us.
3797          */
3798         for_each_intel_crtc(dev, crtc) {
3799                 if (atomic_read(&crtc->unpin_work_count) == 0)
3800                         continue;
3801
3802                 if (crtc->unpin_work)
3803                         intel_wait_for_vblank(dev, crtc->pipe);
3804
3805                 return true;
3806         }
3807
3808         return false;
3809 }
3810
3811 static void page_flip_completed(struct intel_crtc *intel_crtc)
3812 {
3813         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3814         struct intel_unpin_work *work = intel_crtc->unpin_work;
3815
3816         intel_crtc->unpin_work = NULL;
3817
3818         if (work->event)
3819                 drm_crtc_send_vblank_event(&intel_crtc->base, work->event);
3820
3821         drm_crtc_vblank_put(&intel_crtc->base);
3822
3823         wake_up_all(&dev_priv->pending_flip_queue);
3824         queue_work(dev_priv->wq, &work->work);
3825
3826         trace_i915_flip_complete(intel_crtc->plane,
3827                                  work->pending_flip_obj);
3828 }
3829
3830 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3831 {
3832         struct drm_device *dev = crtc->dev;
3833         struct drm_i915_private *dev_priv = dev->dev_private;
3834         long ret;
3835
3836         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3837
3838         ret = wait_event_interruptible_timeout(
3839                                         dev_priv->pending_flip_queue,
3840                                         !intel_crtc_has_pending_flip(crtc),
3841                                         60*HZ);
3842
3843         if (ret < 0)
3844                 return ret;
3845
3846         if (ret == 0) {
3847                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3848
3849                 spin_lock_irq(&dev->event_lock);
3850                 if (intel_crtc->unpin_work) {
3851                         WARN_ONCE(1, "Removing stuck page flip\n");
3852                         page_flip_completed(intel_crtc);
3853                 }
3854                 spin_unlock_irq(&dev->event_lock);
3855         }
3856
3857         return 0;
3858 }
3859
3860 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3861 {
3862         u32 temp;
3863
3864         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3865
3866         mutex_lock(&dev_priv->sb_lock);
3867
3868         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3869         temp |= SBI_SSCCTL_DISABLE;
3870         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3871
3872         mutex_unlock(&dev_priv->sb_lock);
3873 }
3874
3875 /* Program iCLKIP clock to the desired frequency */
3876 static void lpt_program_iclkip(struct drm_crtc *crtc)
3877 {
3878         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3879         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3880         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3881         u32 temp;
3882
3883         lpt_disable_iclkip(dev_priv);
3884
3885         /* The iCLK virtual clock root frequency is in MHz,
3886          * but the adjusted_mode->crtc_clock in in KHz. To get the
3887          * divisors, it is necessary to divide one by another, so we
3888          * convert the virtual clock precision to KHz here for higher
3889          * precision.
3890          */
3891         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3892                 u32 iclk_virtual_root_freq = 172800 * 1000;
3893                 u32 iclk_pi_range = 64;
3894                 u32 desired_divisor;
3895
3896                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3897                                                     clock << auxdiv);
3898                 divsel = (desired_divisor / iclk_pi_range) - 2;
3899                 phaseinc = desired_divisor % iclk_pi_range;
3900
3901                 /*
3902                  * Near 20MHz is a corner case which is
3903                  * out of range for the 7-bit divisor
3904                  */
3905                 if (divsel <= 0x7f)
3906                         break;
3907         }
3908
3909         /* This should not happen with any sane values */
3910         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3911                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3912         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3913                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3914
3915         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3916                         clock,
3917                         auxdiv,
3918                         divsel,
3919                         phasedir,
3920                         phaseinc);
3921
3922         mutex_lock(&dev_priv->sb_lock);
3923
3924         /* Program SSCDIVINTPHASE6 */
3925         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3926         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3927         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3928         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3929         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3930         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3931         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3932         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3933
3934         /* Program SSCAUXDIV */
3935         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3936         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3937         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3938         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3939
3940         /* Enable modulator and associated divider */
3941         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3942         temp &= ~SBI_SSCCTL_DISABLE;
3943         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3944
3945         mutex_unlock(&dev_priv->sb_lock);
3946
3947         /* Wait for initialization time */
3948         udelay(24);
3949
3950         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3951 }
3952
3953 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3954 {
3955         u32 divsel, phaseinc, auxdiv;
3956         u32 iclk_virtual_root_freq = 172800 * 1000;
3957         u32 iclk_pi_range = 64;
3958         u32 desired_divisor;
3959         u32 temp;
3960
3961         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3962                 return 0;
3963
3964         mutex_lock(&dev_priv->sb_lock);
3965
3966         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3967         if (temp & SBI_SSCCTL_DISABLE) {
3968                 mutex_unlock(&dev_priv->sb_lock);
3969                 return 0;
3970         }
3971
3972         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3973         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
3974                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
3975         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
3976                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
3977
3978         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3979         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
3980                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
3981
3982         mutex_unlock(&dev_priv->sb_lock);
3983
3984         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
3985
3986         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3987                                  desired_divisor << auxdiv);
3988 }
3989
3990 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3991                                                 enum pipe pch_transcoder)
3992 {
3993         struct drm_device *dev = crtc->base.dev;
3994         struct drm_i915_private *dev_priv = dev->dev_private;
3995         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3996
3997         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3998                    I915_READ(HTOTAL(cpu_transcoder)));
3999         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4000                    I915_READ(HBLANK(cpu_transcoder)));
4001         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4002                    I915_READ(HSYNC(cpu_transcoder)));
4003
4004         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4005                    I915_READ(VTOTAL(cpu_transcoder)));
4006         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4007                    I915_READ(VBLANK(cpu_transcoder)));
4008         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4009                    I915_READ(VSYNC(cpu_transcoder)));
4010         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4011                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4012 }
4013
4014 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4015 {
4016         struct drm_i915_private *dev_priv = dev->dev_private;
4017         uint32_t temp;
4018
4019         temp = I915_READ(SOUTH_CHICKEN1);
4020         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4021                 return;
4022
4023         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4024         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4025
4026         temp &= ~FDI_BC_BIFURCATION_SELECT;
4027         if (enable)
4028                 temp |= FDI_BC_BIFURCATION_SELECT;
4029
4030         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4031         I915_WRITE(SOUTH_CHICKEN1, temp);
4032         POSTING_READ(SOUTH_CHICKEN1);
4033 }
4034
4035 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4036 {
4037         struct drm_device *dev = intel_crtc->base.dev;
4038
4039         switch (intel_crtc->pipe) {
4040         case PIPE_A:
4041                 break;
4042         case PIPE_B:
4043                 if (intel_crtc->config->fdi_lanes > 2)
4044                         cpt_set_fdi_bc_bifurcation(dev, false);
4045                 else
4046                         cpt_set_fdi_bc_bifurcation(dev, true);
4047
4048                 break;
4049         case PIPE_C:
4050                 cpt_set_fdi_bc_bifurcation(dev, true);
4051
4052                 break;
4053         default:
4054                 BUG();
4055         }
4056 }
4057
4058 /* Return which DP Port should be selected for Transcoder DP control */
4059 static enum port
4060 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4061 {
4062         struct drm_device *dev = crtc->dev;
4063         struct intel_encoder *encoder;
4064
4065         for_each_encoder_on_crtc(dev, crtc, encoder) {
4066                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4067                     encoder->type == INTEL_OUTPUT_EDP)
4068                         return enc_to_dig_port(&encoder->base)->port;
4069         }
4070
4071         return -1;
4072 }
4073
4074 /*
4075  * Enable PCH resources required for PCH ports:
4076  *   - PCH PLLs
4077  *   - FDI training & RX/TX
4078  *   - update transcoder timings
4079  *   - DP transcoding bits
4080  *   - transcoder
4081  */
4082 static void ironlake_pch_enable(struct drm_crtc *crtc)
4083 {
4084         struct drm_device *dev = crtc->dev;
4085         struct drm_i915_private *dev_priv = dev->dev_private;
4086         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4087         int pipe = intel_crtc->pipe;
4088         u32 temp;
4089
4090         assert_pch_transcoder_disabled(dev_priv, pipe);
4091
4092         if (IS_IVYBRIDGE(dev))
4093                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4094
4095         /* Write the TU size bits before fdi link training, so that error
4096          * detection works. */
4097         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4098                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4099
4100         /* For PCH output, training FDI link */
4101         dev_priv->display.fdi_link_train(crtc);
4102
4103         /* We need to program the right clock selection before writing the pixel
4104          * mutliplier into the DPLL. */
4105         if (HAS_PCH_CPT(dev)) {
4106                 u32 sel;
4107
4108                 temp = I915_READ(PCH_DPLL_SEL);
4109                 temp |= TRANS_DPLL_ENABLE(pipe);
4110                 sel = TRANS_DPLLB_SEL(pipe);
4111                 if (intel_crtc->config->shared_dpll ==
4112                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4113                         temp |= sel;
4114                 else
4115                         temp &= ~sel;
4116                 I915_WRITE(PCH_DPLL_SEL, temp);
4117         }
4118
4119         /* XXX: pch pll's can be enabled any time before we enable the PCH
4120          * transcoder, and we actually should do this to not upset any PCH
4121          * transcoder that already use the clock when we share it.
4122          *
4123          * Note that enable_shared_dpll tries to do the right thing, but
4124          * get_shared_dpll unconditionally resets the pll - we need that to have
4125          * the right LVDS enable sequence. */
4126         intel_enable_shared_dpll(intel_crtc);
4127
4128         /* set transcoder timing, panel must allow it */
4129         assert_panel_unlocked(dev_priv, pipe);
4130         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4131
4132         intel_fdi_normal_train(crtc);
4133
4134         /* For PCH DP, enable TRANS_DP_CTL */
4135         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4136                 const struct drm_display_mode *adjusted_mode =
4137                         &intel_crtc->config->base.adjusted_mode;
4138                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4139                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4140                 temp = I915_READ(reg);
4141                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4142                           TRANS_DP_SYNC_MASK |
4143                           TRANS_DP_BPC_MASK);
4144                 temp |= TRANS_DP_OUTPUT_ENABLE;
4145                 temp |= bpc << 9; /* same format but at 11:9 */
4146
4147                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4148                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4149                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4150                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4151
4152                 switch (intel_trans_dp_port_sel(crtc)) {
4153                 case PORT_B:
4154                         temp |= TRANS_DP_PORT_SEL_B;
4155                         break;
4156                 case PORT_C:
4157                         temp |= TRANS_DP_PORT_SEL_C;
4158                         break;
4159                 case PORT_D:
4160                         temp |= TRANS_DP_PORT_SEL_D;
4161                         break;
4162                 default:
4163                         BUG();
4164                 }
4165
4166                 I915_WRITE(reg, temp);
4167         }
4168
4169         ironlake_enable_pch_transcoder(dev_priv, pipe);
4170 }
4171
4172 static void lpt_pch_enable(struct drm_crtc *crtc)
4173 {
4174         struct drm_device *dev = crtc->dev;
4175         struct drm_i915_private *dev_priv = dev->dev_private;
4176         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4177         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4178
4179         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4180
4181         lpt_program_iclkip(crtc);
4182
4183         /* Set transcoder timing. */
4184         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4185
4186         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4187 }
4188
4189 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4190 {
4191         struct drm_i915_private *dev_priv = dev->dev_private;
4192         i915_reg_t dslreg = PIPEDSL(pipe);
4193         u32 temp;
4194
4195         temp = I915_READ(dslreg);
4196         udelay(500);
4197         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4198                 if (wait_for(I915_READ(dslreg) != temp, 5))
4199                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4200         }
4201 }
4202
4203 static int
4204 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4205                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4206                   int src_w, int src_h, int dst_w, int dst_h)
4207 {
4208         struct intel_crtc_scaler_state *scaler_state =
4209                 &crtc_state->scaler_state;
4210         struct intel_crtc *intel_crtc =
4211                 to_intel_crtc(crtc_state->base.crtc);
4212         int need_scaling;
4213
4214         need_scaling = intel_rotation_90_or_270(rotation) ?
4215                 (src_h != dst_w || src_w != dst_h):
4216                 (src_w != dst_w || src_h != dst_h);
4217
4218         /*
4219          * if plane is being disabled or scaler is no more required or force detach
4220          *  - free scaler binded to this plane/crtc
4221          *  - in order to do this, update crtc->scaler_usage
4222          *
4223          * Here scaler state in crtc_state is set free so that
4224          * scaler can be assigned to other user. Actual register
4225          * update to free the scaler is done in plane/panel-fit programming.
4226          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4227          */
4228         if (force_detach || !need_scaling) {
4229                 if (*scaler_id >= 0) {
4230                         scaler_state->scaler_users &= ~(1 << scaler_user);
4231                         scaler_state->scalers[*scaler_id].in_use = 0;
4232
4233                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4234                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4235                                 intel_crtc->pipe, scaler_user, *scaler_id,
4236                                 scaler_state->scaler_users);
4237                         *scaler_id = -1;
4238                 }
4239                 return 0;
4240         }
4241
4242         /* range checks */
4243         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4244                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4245
4246                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4247                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4248                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4249                         "size is out of scaler range\n",
4250                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4251                 return -EINVAL;
4252         }
4253
4254         /* mark this plane as a scaler user in crtc_state */
4255         scaler_state->scaler_users |= (1 << scaler_user);
4256         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4257                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4258                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4259                 scaler_state->scaler_users);
4260
4261         return 0;
4262 }
4263
4264 /**
4265  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4266  *
4267  * @state: crtc's scaler state
4268  *
4269  * Return
4270  *     0 - scaler_usage updated successfully
4271  *    error - requested scaling cannot be supported or other error condition
4272  */
4273 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4274 {
4275         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4276         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4277
4278         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4279                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4280
4281         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4282                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4283                 state->pipe_src_w, state->pipe_src_h,
4284                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4285 }
4286
4287 /**
4288  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4289  *
4290  * @state: crtc's scaler state
4291  * @plane_state: atomic plane state to update
4292  *
4293  * Return
4294  *     0 - scaler_usage updated successfully
4295  *    error - requested scaling cannot be supported or other error condition
4296  */
4297 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4298                                    struct intel_plane_state *plane_state)
4299 {
4300
4301         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4302         struct intel_plane *intel_plane =
4303                 to_intel_plane(plane_state->base.plane);
4304         struct drm_framebuffer *fb = plane_state->base.fb;
4305         int ret;
4306
4307         bool force_detach = !fb || !plane_state->visible;
4308
4309         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4310                       intel_plane->base.base.id, intel_crtc->pipe,
4311                       drm_plane_index(&intel_plane->base));
4312
4313         ret = skl_update_scaler(crtc_state, force_detach,
4314                                 drm_plane_index(&intel_plane->base),
4315                                 &plane_state->scaler_id,
4316                                 plane_state->base.rotation,
4317                                 drm_rect_width(&plane_state->src) >> 16,
4318                                 drm_rect_height(&plane_state->src) >> 16,
4319                                 drm_rect_width(&plane_state->dst),
4320                                 drm_rect_height(&plane_state->dst));
4321
4322         if (ret || plane_state->scaler_id < 0)
4323                 return ret;
4324
4325         /* check colorkey */
4326         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4327                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4328                               intel_plane->base.base.id);
4329                 return -EINVAL;
4330         }
4331
4332         /* Check src format */
4333         switch (fb->pixel_format) {
4334         case DRM_FORMAT_RGB565:
4335         case DRM_FORMAT_XBGR8888:
4336         case DRM_FORMAT_XRGB8888:
4337         case DRM_FORMAT_ABGR8888:
4338         case DRM_FORMAT_ARGB8888:
4339         case DRM_FORMAT_XRGB2101010:
4340         case DRM_FORMAT_XBGR2101010:
4341         case DRM_FORMAT_YUYV:
4342         case DRM_FORMAT_YVYU:
4343         case DRM_FORMAT_UYVY:
4344         case DRM_FORMAT_VYUY:
4345                 break;
4346         default:
4347                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4348                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4349                 return -EINVAL;
4350         }
4351
4352         return 0;
4353 }
4354
4355 static void skylake_scaler_disable(struct intel_crtc *crtc)
4356 {
4357         int i;
4358
4359         for (i = 0; i < crtc->num_scalers; i++)
4360                 skl_detach_scaler(crtc, i);
4361 }
4362
4363 static void skylake_pfit_enable(struct intel_crtc *crtc)
4364 {
4365         struct drm_device *dev = crtc->base.dev;
4366         struct drm_i915_private *dev_priv = dev->dev_private;
4367         int pipe = crtc->pipe;
4368         struct intel_crtc_scaler_state *scaler_state =
4369                 &crtc->config->scaler_state;
4370
4371         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4372
4373         if (crtc->config->pch_pfit.enabled) {
4374                 int id;
4375
4376                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4377                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4378                         return;
4379                 }
4380
4381                 id = scaler_state->scaler_id;
4382                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4383                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4384                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4385                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4386
4387                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4388         }
4389 }
4390
4391 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4392 {
4393         struct drm_device *dev = crtc->base.dev;
4394         struct drm_i915_private *dev_priv = dev->dev_private;
4395         int pipe = crtc->pipe;
4396
4397         if (crtc->config->pch_pfit.enabled) {
4398                 /* Force use of hard-coded filter coefficients
4399                  * as some pre-programmed values are broken,
4400                  * e.g. x201.
4401                  */
4402                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4403                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4404                                                  PF_PIPE_SEL_IVB(pipe));
4405                 else
4406                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4407                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4408                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4409         }
4410 }
4411
4412 void hsw_enable_ips(struct intel_crtc *crtc)
4413 {
4414         struct drm_device *dev = crtc->base.dev;
4415         struct drm_i915_private *dev_priv = dev->dev_private;
4416
4417         if (!crtc->config->ips_enabled)
4418                 return;
4419
4420         /*
4421          * We can only enable IPS after we enable a plane and wait for a vblank
4422          * This function is called from post_plane_update, which is run after
4423          * a vblank wait.
4424          */
4425
4426         assert_plane_enabled(dev_priv, crtc->plane);
4427         if (IS_BROADWELL(dev)) {
4428                 mutex_lock(&dev_priv->rps.hw_lock);
4429                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4430                 mutex_unlock(&dev_priv->rps.hw_lock);
4431                 /* Quoting Art Runyan: "its not safe to expect any particular
4432                  * value in IPS_CTL bit 31 after enabling IPS through the
4433                  * mailbox." Moreover, the mailbox may return a bogus state,
4434                  * so we need to just enable it and continue on.
4435                  */
4436         } else {
4437                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4438                 /* The bit only becomes 1 in the next vblank, so this wait here
4439                  * is essentially intel_wait_for_vblank. If we don't have this
4440                  * and don't wait for vblanks until the end of crtc_enable, then
4441                  * the HW state readout code will complain that the expected
4442                  * IPS_CTL value is not the one we read. */
4443                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4444                         DRM_ERROR("Timed out waiting for IPS enable\n");
4445         }
4446 }
4447
4448 void hsw_disable_ips(struct intel_crtc *crtc)
4449 {
4450         struct drm_device *dev = crtc->base.dev;
4451         struct drm_i915_private *dev_priv = dev->dev_private;
4452
4453         if (!crtc->config->ips_enabled)
4454                 return;
4455
4456         assert_plane_enabled(dev_priv, crtc->plane);
4457         if (IS_BROADWELL(dev)) {
4458                 mutex_lock(&dev_priv->rps.hw_lock);
4459                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4460                 mutex_unlock(&dev_priv->rps.hw_lock);
4461                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4462                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4463                         DRM_ERROR("Timed out waiting for IPS disable\n");
4464         } else {
4465                 I915_WRITE(IPS_CTL, 0);
4466                 POSTING_READ(IPS_CTL);
4467         }
4468
4469         /* We need to wait for a vblank before we can disable the plane. */
4470         intel_wait_for_vblank(dev, crtc->pipe);
4471 }
4472
4473 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4474 {
4475         if (intel_crtc->overlay) {
4476                 struct drm_device *dev = intel_crtc->base.dev;
4477                 struct drm_i915_private *dev_priv = dev->dev_private;
4478
4479                 mutex_lock(&dev->struct_mutex);
4480                 dev_priv->mm.interruptible = false;
4481                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4482                 dev_priv->mm.interruptible = true;
4483                 mutex_unlock(&dev->struct_mutex);
4484         }
4485
4486         /* Let userspace switch the overlay on again. In most cases userspace
4487          * has to recompute where to put it anyway.
4488          */
4489 }
4490
4491 /**
4492  * intel_post_enable_primary - Perform operations after enabling primary plane
4493  * @crtc: the CRTC whose primary plane was just enabled
4494  *
4495  * Performs potentially sleeping operations that must be done after the primary
4496  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4497  * called due to an explicit primary plane update, or due to an implicit
4498  * re-enable that is caused when a sprite plane is updated to no longer
4499  * completely hide the primary plane.
4500  */
4501 static void
4502 intel_post_enable_primary(struct drm_crtc *crtc)
4503 {
4504         struct drm_device *dev = crtc->dev;
4505         struct drm_i915_private *dev_priv = dev->dev_private;
4506         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4507         int pipe = intel_crtc->pipe;
4508
4509         /*
4510          * FIXME IPS should be fine as long as one plane is
4511          * enabled, but in practice it seems to have problems
4512          * when going from primary only to sprite only and vice
4513          * versa.
4514          */
4515         hsw_enable_ips(intel_crtc);
4516
4517         /*
4518          * Gen2 reports pipe underruns whenever all planes are disabled.
4519          * So don't enable underrun reporting before at least some planes
4520          * are enabled.
4521          * FIXME: Need to fix the logic to work when we turn off all planes
4522          * but leave the pipe running.
4523          */
4524         if (IS_GEN2(dev))
4525                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4526
4527         /* Underruns don't always raise interrupts, so check manually. */
4528         intel_check_cpu_fifo_underruns(dev_priv);
4529         intel_check_pch_fifo_underruns(dev_priv);
4530 }
4531
4532 /* FIXME move all this to pre_plane_update() with proper state tracking */
4533 static void
4534 intel_pre_disable_primary(struct drm_crtc *crtc)
4535 {
4536         struct drm_device *dev = crtc->dev;
4537         struct drm_i915_private *dev_priv = dev->dev_private;
4538         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4539         int pipe = intel_crtc->pipe;
4540
4541         /*
4542          * Gen2 reports pipe underruns whenever all planes are disabled.
4543          * So diasble underrun reporting before all the planes get disabled.
4544          * FIXME: Need to fix the logic to work when we turn off all planes
4545          * but leave the pipe running.
4546          */
4547         if (IS_GEN2(dev))
4548                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4549
4550         /*
4551          * FIXME IPS should be fine as long as one plane is
4552          * enabled, but in practice it seems to have problems
4553          * when going from primary only to sprite only and vice
4554          * versa.
4555          */
4556         hsw_disable_ips(intel_crtc);
4557 }
4558
4559 /* FIXME get rid of this and use pre_plane_update */
4560 static void
4561 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4562 {
4563         struct drm_device *dev = crtc->dev;
4564         struct drm_i915_private *dev_priv = dev->dev_private;
4565         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4566         int pipe = intel_crtc->pipe;
4567
4568         intel_pre_disable_primary(crtc);
4569
4570         /*
4571          * Vblank time updates from the shadow to live plane control register
4572          * are blocked if the memory self-refresh mode is active at that
4573          * moment. So to make sure the plane gets truly disabled, disable
4574          * first the self-refresh mode. The self-refresh enable bit in turn
4575          * will be checked/applied by the HW only at the next frame start
4576          * event which is after the vblank start event, so we need to have a
4577          * wait-for-vblank between disabling the plane and the pipe.
4578          */
4579         if (HAS_GMCH_DISPLAY(dev)) {
4580                 intel_set_memory_cxsr(dev_priv, false);
4581                 dev_priv->wm.vlv.cxsr = false;
4582                 intel_wait_for_vblank(dev, pipe);
4583         }
4584 }
4585
4586 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4587 {
4588         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4589         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4590         struct intel_crtc_state *pipe_config =
4591                 to_intel_crtc_state(crtc->base.state);
4592         struct drm_device *dev = crtc->base.dev;
4593         struct drm_plane *primary = crtc->base.primary;
4594         struct drm_plane_state *old_pri_state =
4595                 drm_atomic_get_existing_plane_state(old_state, primary);
4596
4597         intel_frontbuffer_flip(dev, pipe_config->fb_bits);
4598
4599         crtc->wm.cxsr_allowed = true;
4600
4601         if (pipe_config->update_wm_post && pipe_config->base.active)
4602                 intel_update_watermarks(&crtc->base);
4603
4604         if (old_pri_state) {
4605                 struct intel_plane_state *primary_state =
4606                         to_intel_plane_state(primary->state);
4607                 struct intel_plane_state *old_primary_state =
4608                         to_intel_plane_state(old_pri_state);
4609
4610                 intel_fbc_post_update(crtc);
4611
4612                 if (primary_state->visible &&
4613                     (needs_modeset(&pipe_config->base) ||
4614                      !old_primary_state->visible))
4615                         intel_post_enable_primary(&crtc->base);
4616         }
4617 }
4618
4619 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4620 {
4621         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4622         struct drm_device *dev = crtc->base.dev;
4623         struct drm_i915_private *dev_priv = dev->dev_private;
4624         struct intel_crtc_state *pipe_config =
4625                 to_intel_crtc_state(crtc->base.state);
4626         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4627         struct drm_plane *primary = crtc->base.primary;
4628         struct drm_plane_state *old_pri_state =
4629                 drm_atomic_get_existing_plane_state(old_state, primary);
4630         bool modeset = needs_modeset(&pipe_config->base);
4631
4632         if (old_pri_state) {
4633                 struct intel_plane_state *primary_state =
4634                         to_intel_plane_state(primary->state);
4635                 struct intel_plane_state *old_primary_state =
4636                         to_intel_plane_state(old_pri_state);
4637
4638                 intel_fbc_pre_update(crtc);
4639
4640                 if (old_primary_state->visible &&
4641                     (modeset || !primary_state->visible))
4642                         intel_pre_disable_primary(&crtc->base);
4643         }
4644
4645         if (pipe_config->disable_cxsr) {
4646                 crtc->wm.cxsr_allowed = false;
4647
4648                 /*
4649                  * Vblank time updates from the shadow to live plane control register
4650                  * are blocked if the memory self-refresh mode is active at that
4651                  * moment. So to make sure the plane gets truly disabled, disable
4652                  * first the self-refresh mode. The self-refresh enable bit in turn
4653                  * will be checked/applied by the HW only at the next frame start
4654                  * event which is after the vblank start event, so we need to have a
4655                  * wait-for-vblank between disabling the plane and the pipe.
4656                  */
4657                 if (old_crtc_state->base.active) {
4658                         intel_set_memory_cxsr(dev_priv, false);
4659                         dev_priv->wm.vlv.cxsr = false;
4660                         intel_wait_for_vblank(dev, crtc->pipe);
4661                 }
4662         }
4663
4664         /*
4665          * IVB workaround: must disable low power watermarks for at least
4666          * one frame before enabling scaling.  LP watermarks can be re-enabled
4667          * when scaling is disabled.
4668          *
4669          * WaCxSRDisabledForSpriteScaling:ivb
4670          */
4671         if (pipe_config->disable_lp_wm) {
4672                 ilk_disable_lp_wm(dev);
4673                 intel_wait_for_vblank(dev, crtc->pipe);
4674         }
4675
4676         /*
4677          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4678          * watermark programming here.
4679          */
4680         if (needs_modeset(&pipe_config->base))
4681                 return;
4682
4683         /*
4684          * For platforms that support atomic watermarks, program the
4685          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4686          * will be the intermediate values that are safe for both pre- and
4687          * post- vblank; when vblank happens, the 'active' values will be set
4688          * to the final 'target' values and we'll do this again to get the
4689          * optimal watermarks.  For gen9+ platforms, the values we program here
4690          * will be the final target values which will get automatically latched
4691          * at vblank time; no further programming will be necessary.
4692          *
4693          * If a platform hasn't been transitioned to atomic watermarks yet,
4694          * we'll continue to update watermarks the old way, if flags tell
4695          * us to.
4696          */
4697         if (dev_priv->display.initial_watermarks != NULL)
4698                 dev_priv->display.initial_watermarks(pipe_config);
4699         else if (pipe_config->update_wm_pre)
4700                 intel_update_watermarks(&crtc->base);
4701 }
4702
4703 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4704 {
4705         struct drm_device *dev = crtc->dev;
4706         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4707         struct drm_plane *p;
4708         int pipe = intel_crtc->pipe;
4709
4710         intel_crtc_dpms_overlay_disable(intel_crtc);
4711
4712         drm_for_each_plane_mask(p, dev, plane_mask)
4713                 to_intel_plane(p)->disable_plane(p, crtc);
4714
4715         /*
4716          * FIXME: Once we grow proper nuclear flip support out of this we need
4717          * to compute the mask of flip planes precisely. For the time being
4718          * consider this a flip to a NULL plane.
4719          */
4720         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4721 }
4722
4723 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4724 {
4725         struct drm_device *dev = crtc->dev;
4726         struct drm_i915_private *dev_priv = dev->dev_private;
4727         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4728         struct intel_encoder *encoder;
4729         int pipe = intel_crtc->pipe;
4730         struct intel_crtc_state *pipe_config =
4731                 to_intel_crtc_state(crtc->state);
4732
4733         if (WARN_ON(intel_crtc->active))
4734                 return;
4735
4736         /*
4737          * Sometimes spurious CPU pipe underruns happen during FDI
4738          * training, at least with VGA+HDMI cloning. Suppress them.
4739          *
4740          * On ILK we get an occasional spurious CPU pipe underruns
4741          * between eDP port A enable and vdd enable. Also PCH port
4742          * enable seems to result in the occasional CPU pipe underrun.
4743          *
4744          * Spurious PCH underruns also occur during PCH enabling.
4745          */
4746         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
4747                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4748         if (intel_crtc->config->has_pch_encoder)
4749                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4750
4751         if (intel_crtc->config->has_pch_encoder)
4752                 intel_prepare_shared_dpll(intel_crtc);
4753
4754         if (intel_crtc->config->has_dp_encoder)
4755                 intel_dp_set_m_n(intel_crtc, M1_N1);
4756
4757         intel_set_pipe_timings(intel_crtc);
4758         intel_set_pipe_src_size(intel_crtc);
4759
4760         if (intel_crtc->config->has_pch_encoder) {
4761                 intel_cpu_transcoder_set_m_n(intel_crtc,
4762                                      &intel_crtc->config->fdi_m_n, NULL);
4763         }
4764
4765         ironlake_set_pipeconf(crtc);
4766
4767         intel_crtc->active = true;
4768
4769         for_each_encoder_on_crtc(dev, crtc, encoder)
4770                 if (encoder->pre_enable)
4771                         encoder->pre_enable(encoder);
4772
4773         if (intel_crtc->config->has_pch_encoder) {
4774                 /* Note: FDI PLL enabling _must_ be done before we enable the
4775                  * cpu pipes, hence this is separate from all the other fdi/pch
4776                  * enabling. */
4777                 ironlake_fdi_pll_enable(intel_crtc);
4778         } else {
4779                 assert_fdi_tx_disabled(dev_priv, pipe);
4780                 assert_fdi_rx_disabled(dev_priv, pipe);
4781         }
4782
4783         ironlake_pfit_enable(intel_crtc);
4784
4785         /*
4786          * On ILK+ LUT must be loaded before the pipe is running but with
4787          * clocks enabled
4788          */
4789         intel_color_load_luts(&pipe_config->base);
4790
4791         if (dev_priv->display.initial_watermarks != NULL)
4792                 dev_priv->display.initial_watermarks(intel_crtc->config);
4793         intel_enable_pipe(intel_crtc);
4794
4795         if (intel_crtc->config->has_pch_encoder)
4796                 ironlake_pch_enable(crtc);
4797
4798         assert_vblank_disabled(crtc);
4799         drm_crtc_vblank_on(crtc);
4800
4801         for_each_encoder_on_crtc(dev, crtc, encoder)
4802                 encoder->enable(encoder);
4803
4804         if (HAS_PCH_CPT(dev))
4805                 cpt_verify_modeset(dev, intel_crtc->pipe);
4806
4807         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4808         if (intel_crtc->config->has_pch_encoder)
4809                 intel_wait_for_vblank(dev, pipe);
4810         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4811         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4812 }
4813
4814 /* IPS only exists on ULT machines and is tied to pipe A. */
4815 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4816 {
4817         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4818 }
4819
4820 static void haswell_crtc_enable(struct drm_crtc *crtc)
4821 {
4822         struct drm_device *dev = crtc->dev;
4823         struct drm_i915_private *dev_priv = dev->dev_private;
4824         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4825         struct intel_encoder *encoder;
4826         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4827         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4828         struct intel_crtc_state *pipe_config =
4829                 to_intel_crtc_state(crtc->state);
4830
4831         if (WARN_ON(intel_crtc->active))
4832                 return;
4833
4834         if (intel_crtc->config->has_pch_encoder)
4835                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4836                                                       false);
4837
4838         if (intel_crtc->config->shared_dpll)
4839                 intel_enable_shared_dpll(intel_crtc);
4840
4841         if (intel_crtc->config->has_dp_encoder)
4842                 intel_dp_set_m_n(intel_crtc, M1_N1);
4843
4844         if (!intel_crtc->config->has_dsi_encoder)
4845                 intel_set_pipe_timings(intel_crtc);
4846
4847         intel_set_pipe_src_size(intel_crtc);
4848
4849         if (cpu_transcoder != TRANSCODER_EDP &&
4850             !transcoder_is_dsi(cpu_transcoder)) {
4851                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4852                            intel_crtc->config->pixel_multiplier - 1);
4853         }
4854
4855         if (intel_crtc->config->has_pch_encoder) {
4856                 intel_cpu_transcoder_set_m_n(intel_crtc,
4857                                      &intel_crtc->config->fdi_m_n, NULL);
4858         }
4859
4860         if (!intel_crtc->config->has_dsi_encoder)
4861                 haswell_set_pipeconf(crtc);
4862
4863         haswell_set_pipemisc(crtc);
4864
4865         intel_color_set_csc(&pipe_config->base);
4866
4867         intel_crtc->active = true;
4868
4869         if (intel_crtc->config->has_pch_encoder)
4870                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4871         else
4872                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4873
4874         for_each_encoder_on_crtc(dev, crtc, encoder) {
4875                 if (encoder->pre_enable)
4876                         encoder->pre_enable(encoder);
4877         }
4878
4879         if (intel_crtc->config->has_pch_encoder)
4880                 dev_priv->display.fdi_link_train(crtc);
4881
4882         if (!intel_crtc->config->has_dsi_encoder)
4883                 intel_ddi_enable_pipe_clock(intel_crtc);
4884
4885         if (INTEL_INFO(dev)->gen >= 9)
4886                 skylake_pfit_enable(intel_crtc);
4887         else
4888                 ironlake_pfit_enable(intel_crtc);
4889
4890         /*
4891          * On ILK+ LUT must be loaded before the pipe is running but with
4892          * clocks enabled
4893          */
4894         intel_color_load_luts(&pipe_config->base);
4895
4896         intel_ddi_set_pipe_settings(crtc);
4897         if (!intel_crtc->config->has_dsi_encoder)
4898                 intel_ddi_enable_transcoder_func(crtc);
4899
4900         if (dev_priv->display.initial_watermarks != NULL)
4901                 dev_priv->display.initial_watermarks(pipe_config);
4902         else
4903                 intel_update_watermarks(crtc);
4904
4905         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4906         if (!intel_crtc->config->has_dsi_encoder)
4907                 intel_enable_pipe(intel_crtc);
4908
4909         if (intel_crtc->config->has_pch_encoder)
4910                 lpt_pch_enable(crtc);
4911
4912         if (intel_crtc->config->dp_encoder_is_mst)
4913                 intel_ddi_set_vc_payload_alloc(crtc, true);
4914
4915         assert_vblank_disabled(crtc);
4916         drm_crtc_vblank_on(crtc);
4917
4918         for_each_encoder_on_crtc(dev, crtc, encoder) {
4919                 encoder->enable(encoder);
4920                 intel_opregion_notify_encoder(encoder, true);
4921         }
4922
4923         if (intel_crtc->config->has_pch_encoder) {
4924                 intel_wait_for_vblank(dev, pipe);
4925                 intel_wait_for_vblank(dev, pipe);
4926                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4927                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4928                                                       true);
4929         }
4930
4931         /* If we change the relative order between pipe/planes enabling, we need
4932          * to change the workaround. */
4933         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4934         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4935                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4936                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4937         }
4938 }
4939
4940 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
4941 {
4942         struct drm_device *dev = crtc->base.dev;
4943         struct drm_i915_private *dev_priv = dev->dev_private;
4944         int pipe = crtc->pipe;
4945
4946         /* To avoid upsetting the power well on haswell only disable the pfit if
4947          * it's in use. The hw state code will make sure we get this right. */
4948         if (force || crtc->config->pch_pfit.enabled) {
4949                 I915_WRITE(PF_CTL(pipe), 0);
4950                 I915_WRITE(PF_WIN_POS(pipe), 0);
4951                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4952         }
4953 }
4954
4955 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4956 {
4957         struct drm_device *dev = crtc->dev;
4958         struct drm_i915_private *dev_priv = dev->dev_private;
4959         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4960         struct intel_encoder *encoder;
4961         int pipe = intel_crtc->pipe;
4962
4963         /*
4964          * Sometimes spurious CPU pipe underruns happen when the
4965          * pipe is already disabled, but FDI RX/TX is still enabled.
4966          * Happens at least with VGA+HDMI cloning. Suppress them.
4967          */
4968         if (intel_crtc->config->has_pch_encoder) {
4969                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4970                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4971         }
4972
4973         for_each_encoder_on_crtc(dev, crtc, encoder)
4974                 encoder->disable(encoder);
4975
4976         drm_crtc_vblank_off(crtc);
4977         assert_vblank_disabled(crtc);
4978
4979         intel_disable_pipe(intel_crtc);
4980
4981         ironlake_pfit_disable(intel_crtc, false);
4982
4983         if (intel_crtc->config->has_pch_encoder)
4984                 ironlake_fdi_disable(crtc);
4985
4986         for_each_encoder_on_crtc(dev, crtc, encoder)
4987                 if (encoder->post_disable)
4988                         encoder->post_disable(encoder);
4989
4990         if (intel_crtc->config->has_pch_encoder) {
4991                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4992
4993                 if (HAS_PCH_CPT(dev)) {
4994                         i915_reg_t reg;
4995                         u32 temp;
4996
4997                         /* disable TRANS_DP_CTL */
4998                         reg = TRANS_DP_CTL(pipe);
4999                         temp = I915_READ(reg);
5000                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5001                                   TRANS_DP_PORT_SEL_MASK);
5002                         temp |= TRANS_DP_PORT_SEL_NONE;
5003                         I915_WRITE(reg, temp);
5004
5005                         /* disable DPLL_SEL */
5006                         temp = I915_READ(PCH_DPLL_SEL);
5007                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5008                         I915_WRITE(PCH_DPLL_SEL, temp);
5009                 }
5010
5011                 ironlake_fdi_pll_disable(intel_crtc);
5012         }
5013
5014         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5015         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5016 }
5017
5018 static void haswell_crtc_disable(struct drm_crtc *crtc)
5019 {
5020         struct drm_device *dev = crtc->dev;
5021         struct drm_i915_private *dev_priv = dev->dev_private;
5022         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5023         struct intel_encoder *encoder;
5024         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5025
5026         if (intel_crtc->config->has_pch_encoder)
5027                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5028                                                       false);
5029
5030         for_each_encoder_on_crtc(dev, crtc, encoder) {
5031                 intel_opregion_notify_encoder(encoder, false);
5032                 encoder->disable(encoder);
5033         }
5034
5035         drm_crtc_vblank_off(crtc);
5036         assert_vblank_disabled(crtc);
5037
5038         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5039         if (!intel_crtc->config->has_dsi_encoder)
5040                 intel_disable_pipe(intel_crtc);
5041
5042         if (intel_crtc->config->dp_encoder_is_mst)
5043                 intel_ddi_set_vc_payload_alloc(crtc, false);
5044
5045         if (!intel_crtc->config->has_dsi_encoder)
5046                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5047
5048         if (INTEL_INFO(dev)->gen >= 9)
5049                 skylake_scaler_disable(intel_crtc);
5050         else
5051                 ironlake_pfit_disable(intel_crtc, false);
5052
5053         if (!intel_crtc->config->has_dsi_encoder)
5054                 intel_ddi_disable_pipe_clock(intel_crtc);
5055
5056         for_each_encoder_on_crtc(dev, crtc, encoder)
5057                 if (encoder->post_disable)
5058                         encoder->post_disable(encoder);
5059
5060         if (intel_crtc->config->has_pch_encoder) {
5061                 lpt_disable_pch_transcoder(dev_priv);
5062                 lpt_disable_iclkip(dev_priv);
5063                 intel_ddi_fdi_disable(crtc);
5064
5065                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5066                                                       true);
5067         }
5068 }
5069
5070 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5071 {
5072         struct drm_device *dev = crtc->base.dev;
5073         struct drm_i915_private *dev_priv = dev->dev_private;
5074         struct intel_crtc_state *pipe_config = crtc->config;
5075
5076         if (!pipe_config->gmch_pfit.control)
5077                 return;
5078
5079         /*
5080          * The panel fitter should only be adjusted whilst the pipe is disabled,
5081          * according to register description and PRM.
5082          */
5083         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5084         assert_pipe_disabled(dev_priv, crtc->pipe);
5085
5086         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5087         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5088
5089         /* Border color in case we don't scale up to the full screen. Black by
5090          * default, change to something else for debugging. */
5091         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5092 }
5093
5094 static enum intel_display_power_domain port_to_power_domain(enum port port)
5095 {
5096         switch (port) {
5097         case PORT_A:
5098                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5099         case PORT_B:
5100                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5101         case PORT_C:
5102                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5103         case PORT_D:
5104                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5105         case PORT_E:
5106                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5107         default:
5108                 MISSING_CASE(port);
5109                 return POWER_DOMAIN_PORT_OTHER;
5110         }
5111 }
5112
5113 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5114 {
5115         switch (port) {
5116         case PORT_A:
5117                 return POWER_DOMAIN_AUX_A;
5118         case PORT_B:
5119                 return POWER_DOMAIN_AUX_B;
5120         case PORT_C:
5121                 return POWER_DOMAIN_AUX_C;
5122         case PORT_D:
5123                 return POWER_DOMAIN_AUX_D;
5124         case PORT_E:
5125                 /* FIXME: Check VBT for actual wiring of PORT E */
5126                 return POWER_DOMAIN_AUX_D;
5127         default:
5128                 MISSING_CASE(port);
5129                 return POWER_DOMAIN_AUX_A;
5130         }
5131 }
5132
5133 enum intel_display_power_domain
5134 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5135 {
5136         struct drm_device *dev = intel_encoder->base.dev;
5137         struct intel_digital_port *intel_dig_port;
5138
5139         switch (intel_encoder->type) {
5140         case INTEL_OUTPUT_UNKNOWN:
5141                 /* Only DDI platforms should ever use this output type */
5142                 WARN_ON_ONCE(!HAS_DDI(dev));
5143         case INTEL_OUTPUT_DISPLAYPORT:
5144         case INTEL_OUTPUT_HDMI:
5145         case INTEL_OUTPUT_EDP:
5146                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5147                 return port_to_power_domain(intel_dig_port->port);
5148         case INTEL_OUTPUT_DP_MST:
5149                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5150                 return port_to_power_domain(intel_dig_port->port);
5151         case INTEL_OUTPUT_ANALOG:
5152                 return POWER_DOMAIN_PORT_CRT;
5153         case INTEL_OUTPUT_DSI:
5154                 return POWER_DOMAIN_PORT_DSI;
5155         default:
5156                 return POWER_DOMAIN_PORT_OTHER;
5157         }
5158 }
5159
5160 enum intel_display_power_domain
5161 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5162 {
5163         struct drm_device *dev = intel_encoder->base.dev;
5164         struct intel_digital_port *intel_dig_port;
5165
5166         switch (intel_encoder->type) {
5167         case INTEL_OUTPUT_UNKNOWN:
5168         case INTEL_OUTPUT_HDMI:
5169                 /*
5170                  * Only DDI platforms should ever use these output types.
5171                  * We can get here after the HDMI detect code has already set
5172                  * the type of the shared encoder. Since we can't be sure
5173                  * what's the status of the given connectors, play safe and
5174                  * run the DP detection too.
5175                  */
5176                 WARN_ON_ONCE(!HAS_DDI(dev));
5177         case INTEL_OUTPUT_DISPLAYPORT:
5178         case INTEL_OUTPUT_EDP:
5179                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5180                 return port_to_aux_power_domain(intel_dig_port->port);
5181         case INTEL_OUTPUT_DP_MST:
5182                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5183                 return port_to_aux_power_domain(intel_dig_port->port);
5184         default:
5185                 MISSING_CASE(intel_encoder->type);
5186                 return POWER_DOMAIN_AUX_A;
5187         }
5188 }
5189
5190 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5191                                             struct intel_crtc_state *crtc_state)
5192 {
5193         struct drm_device *dev = crtc->dev;
5194         struct drm_encoder *encoder;
5195         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5196         enum pipe pipe = intel_crtc->pipe;
5197         unsigned long mask;
5198         enum transcoder transcoder = crtc_state->cpu_transcoder;
5199
5200         if (!crtc_state->base.active)
5201                 return 0;
5202
5203         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5204         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5205         if (crtc_state->pch_pfit.enabled ||
5206             crtc_state->pch_pfit.force_thru)
5207                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5208
5209         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5210                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5211
5212                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5213         }
5214
5215         if (crtc_state->shared_dpll)
5216                 mask |= BIT(POWER_DOMAIN_PLLS);
5217
5218         return mask;
5219 }
5220
5221 static unsigned long
5222 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5223                                struct intel_crtc_state *crtc_state)
5224 {
5225         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5226         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5227         enum intel_display_power_domain domain;
5228         unsigned long domains, new_domains, old_domains;
5229
5230         old_domains = intel_crtc->enabled_power_domains;
5231         intel_crtc->enabled_power_domains = new_domains =
5232                 get_crtc_power_domains(crtc, crtc_state);
5233
5234         domains = new_domains & ~old_domains;
5235
5236         for_each_power_domain(domain, domains)
5237                 intel_display_power_get(dev_priv, domain);
5238
5239         return old_domains & ~new_domains;
5240 }
5241
5242 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5243                                       unsigned long domains)
5244 {
5245         enum intel_display_power_domain domain;
5246
5247         for_each_power_domain(domain, domains)
5248                 intel_display_power_put(dev_priv, domain);
5249 }
5250
5251 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5252 {
5253         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5254
5255         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5256             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5257                 return max_cdclk_freq;
5258         else if (IS_CHERRYVIEW(dev_priv))
5259                 return max_cdclk_freq*95/100;
5260         else if (INTEL_INFO(dev_priv)->gen < 4)
5261                 return 2*max_cdclk_freq*90/100;
5262         else
5263                 return max_cdclk_freq*90/100;
5264 }
5265
5266 static void intel_update_max_cdclk(struct drm_device *dev)
5267 {
5268         struct drm_i915_private *dev_priv = dev->dev_private;
5269
5270         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5271                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5272
5273                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5274                         dev_priv->max_cdclk_freq = 675000;
5275                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5276                         dev_priv->max_cdclk_freq = 540000;
5277                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5278                         dev_priv->max_cdclk_freq = 450000;
5279                 else
5280                         dev_priv->max_cdclk_freq = 337500;
5281         } else if (IS_BROXTON(dev)) {
5282                 dev_priv->max_cdclk_freq = 624000;
5283         } else if (IS_BROADWELL(dev))  {
5284                 /*
5285                  * FIXME with extra cooling we can allow
5286                  * 540 MHz for ULX and 675 Mhz for ULT.
5287                  * How can we know if extra cooling is
5288                  * available? PCI ID, VTB, something else?
5289                  */
5290                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5291                         dev_priv->max_cdclk_freq = 450000;
5292                 else if (IS_BDW_ULX(dev))
5293                         dev_priv->max_cdclk_freq = 450000;
5294                 else if (IS_BDW_ULT(dev))
5295                         dev_priv->max_cdclk_freq = 540000;
5296                 else
5297                         dev_priv->max_cdclk_freq = 675000;
5298         } else if (IS_CHERRYVIEW(dev)) {
5299                 dev_priv->max_cdclk_freq = 320000;
5300         } else if (IS_VALLEYVIEW(dev)) {
5301                 dev_priv->max_cdclk_freq = 400000;
5302         } else {
5303                 /* otherwise assume cdclk is fixed */
5304                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5305         }
5306
5307         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5308
5309         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5310                          dev_priv->max_cdclk_freq);
5311
5312         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5313                          dev_priv->max_dotclk_freq);
5314 }
5315
5316 static void intel_update_cdclk(struct drm_device *dev)
5317 {
5318         struct drm_i915_private *dev_priv = dev->dev_private;
5319
5320         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5321         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5322                          dev_priv->cdclk_freq);
5323
5324         /*
5325          * 9:0 CMBUS [sic] CDCLK frequency (cdfreq):
5326          * Programmng [sic] note: bit[9:2] should be programmed to the number
5327          * of cdclk that generates 4MHz reference clock freq which is used to
5328          * generate GMBus clock. This will vary with the cdclk freq.
5329          */
5330         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
5331                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5332
5333         if (dev_priv->max_cdclk_freq == 0)
5334                 intel_update_max_cdclk(dev);
5335 }
5336
5337 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5338 static int skl_cdclk_decimal(int cdclk)
5339 {
5340         return DIV_ROUND_CLOSEST(cdclk - 1000, 500);
5341 }
5342
5343 static void broxton_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5344 {
5345         uint32_t divider;
5346         uint32_t ratio;
5347         uint32_t current_cdclk;
5348         int ret;
5349
5350         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5351         switch (cdclk) {
5352         case 144000:
5353                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5354                 ratio = BXT_DE_PLL_RATIO(60);
5355                 break;
5356         case 288000:
5357                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5358                 ratio = BXT_DE_PLL_RATIO(60);
5359                 break;
5360         case 384000:
5361                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5362                 ratio = BXT_DE_PLL_RATIO(60);
5363                 break;
5364         case 576000:
5365                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5366                 ratio = BXT_DE_PLL_RATIO(60);
5367                 break;
5368         case 624000:
5369                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5370                 ratio = BXT_DE_PLL_RATIO(65);
5371                 break;
5372         case 19200:
5373                 /*
5374                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5375                  * to suppress GCC warning.
5376                  */
5377                 ratio = 0;
5378                 divider = 0;
5379                 break;
5380         default:
5381                 DRM_ERROR("unsupported CDCLK freq %d", cdclk);
5382
5383                 return;
5384         }
5385
5386         mutex_lock(&dev_priv->rps.hw_lock);
5387         /* Inform power controller of upcoming frequency change */
5388         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5389                                       0x80000000);
5390         mutex_unlock(&dev_priv->rps.hw_lock);
5391
5392         if (ret) {
5393                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5394                           ret, cdclk);
5395                 return;
5396         }
5397
5398         current_cdclk = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5399         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5400         current_cdclk = current_cdclk * 500 + 1000;
5401
5402         /*
5403          * DE PLL has to be disabled when
5404          * - setting to 19.2MHz (bypass, PLL isn't used)
5405          * - before setting to 624MHz (PLL needs toggling)
5406          * - before setting to any frequency from 624MHz (PLL needs toggling)
5407          */
5408         if (cdclk == 19200 || cdclk == 624000 ||
5409             current_cdclk == 624000) {
5410                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5411                 /* Timeout 200us */
5412                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5413                              1))
5414                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5415         }
5416
5417         if (cdclk != 19200) {
5418                 uint32_t val;
5419
5420                 val = I915_READ(BXT_DE_PLL_CTL);
5421                 val &= ~BXT_DE_PLL_RATIO_MASK;
5422                 val |= ratio;
5423                 I915_WRITE(BXT_DE_PLL_CTL, val);
5424
5425                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5426                 /* Timeout 200us */
5427                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5428                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5429
5430                 val = divider | skl_cdclk_decimal(cdclk);
5431                 /*
5432                  * FIXME if only the cd2x divider needs changing, it could be done
5433                  * without shutting off the pipe (if only one pipe is active).
5434                  */
5435                 val |= BXT_CDCLK_CD2X_PIPE_NONE;
5436                 /*
5437                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5438                  * enable otherwise.
5439                  */
5440                 if (cdclk >= 500000)
5441                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5442                 I915_WRITE(CDCLK_CTL, val);
5443         }
5444
5445         mutex_lock(&dev_priv->rps.hw_lock);
5446         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5447                                       DIV_ROUND_UP(cdclk, 25000));
5448         mutex_unlock(&dev_priv->rps.hw_lock);
5449
5450         if (ret) {
5451                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5452                           ret, cdclk);
5453                 return;
5454         }
5455
5456         intel_update_cdclk(dev_priv->dev);
5457 }
5458
5459 static bool broxton_cdclk_is_enabled(struct drm_i915_private *dev_priv)
5460 {
5461         if (!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE))
5462                 return false;
5463
5464         /* TODO: Check for a valid CDCLK rate */
5465
5466         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_REQUEST)) {
5467                 DRM_DEBUG_DRIVER("CDCLK enabled, but DBUF power not requested\n");
5468
5469                 return false;
5470         }
5471
5472         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE)) {
5473                 DRM_DEBUG_DRIVER("CDCLK enabled, but DBUF power hasn't settled\n");
5474
5475                 return false;
5476         }
5477
5478         return true;
5479 }
5480
5481 bool broxton_cdclk_verify_state(struct drm_i915_private *dev_priv)
5482 {
5483         return broxton_cdclk_is_enabled(dev_priv);
5484 }
5485
5486 void broxton_init_cdclk(struct drm_i915_private *dev_priv)
5487 {
5488         /* check if cd clock is enabled */
5489         if (broxton_cdclk_is_enabled(dev_priv)) {
5490                 DRM_DEBUG_KMS("CDCLK already enabled, won't reprogram it\n");
5491                 return;
5492         }
5493
5494         DRM_DEBUG_KMS("CDCLK not enabled, enabling it\n");
5495
5496         /*
5497          * FIXME:
5498          * - The initial CDCLK needs to be read from VBT.
5499          *   Need to make this change after VBT has changes for BXT.
5500          * - check if setting the max (or any) cdclk freq is really necessary
5501          *   here, it belongs to modeset time
5502          */
5503         broxton_set_cdclk(dev_priv, 624000);
5504
5505         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5506         POSTING_READ(DBUF_CTL);
5507
5508         udelay(10);
5509
5510         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5511                 DRM_ERROR("DBuf power enable timeout!\n");
5512 }
5513
5514 void broxton_uninit_cdclk(struct drm_i915_private *dev_priv)
5515 {
5516         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5517         POSTING_READ(DBUF_CTL);
5518
5519         udelay(10);
5520
5521         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5522                 DRM_ERROR("DBuf power disable timeout!\n");
5523
5524         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5525         broxton_set_cdclk(dev_priv, 19200);
5526 }
5527
5528 static const struct skl_cdclk_entry {
5529         unsigned int freq;
5530         unsigned int vco;
5531 } skl_cdclk_frequencies[] = {
5532         { .freq = 308570, .vco = 8640 },
5533         { .freq = 337500, .vco = 8100 },
5534         { .freq = 432000, .vco = 8640 },
5535         { .freq = 450000, .vco = 8100 },
5536         { .freq = 540000, .vco = 8100 },
5537         { .freq = 617140, .vco = 8640 },
5538         { .freq = 675000, .vco = 8100 },
5539 };
5540
5541 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5542 {
5543         unsigned int i;
5544
5545         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5546                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5547
5548                 if (e->freq == freq)
5549                         return e->vco;
5550         }
5551
5552         return 8100;
5553 }
5554
5555 static void
5556 skl_dpll0_enable(struct drm_i915_private *dev_priv, int vco)
5557 {
5558         int min_cdclk;
5559         u32 val;
5560
5561         /* select the minimum CDCLK before enabling DPLL 0 */
5562         if (vco == 8640)
5563                 min_cdclk = 308570;
5564         else
5565                 min_cdclk = 337500;
5566
5567         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_cdclk);
5568         I915_WRITE(CDCLK_CTL, val);
5569         POSTING_READ(CDCLK_CTL);
5570
5571         /*
5572          * We always enable DPLL0 with the lowest link rate possible, but still
5573          * taking into account the VCO required to operate the eDP panel at the
5574          * desired frequency. The usual DP link rates operate with a VCO of
5575          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5576          * The modeset code is responsible for the selection of the exact link
5577          * rate later on, with the constraint of choosing a frequency that
5578          * works with required_vco.
5579          */
5580         val = I915_READ(DPLL_CTRL1);
5581
5582         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5583                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5584         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5585         if (vco == 8640)
5586                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5587                                             SKL_DPLL0);
5588         else
5589                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5590                                             SKL_DPLL0);
5591
5592         I915_WRITE(DPLL_CTRL1, val);
5593         POSTING_READ(DPLL_CTRL1);
5594
5595         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5596
5597         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5598                 DRM_ERROR("DPLL0 not locked\n");
5599 }
5600
5601 static void
5602 skl_dpll0_disable(struct drm_i915_private *dev_priv)
5603 {
5604         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5605         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5606                 DRM_ERROR("Couldn't disable DPLL0\n");
5607 }
5608
5609 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5610 {
5611         int ret;
5612         u32 val;
5613
5614         /* inform PCU we want to change CDCLK */
5615         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5616         mutex_lock(&dev_priv->rps.hw_lock);
5617         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5618         mutex_unlock(&dev_priv->rps.hw_lock);
5619
5620         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5621 }
5622
5623 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5624 {
5625         unsigned int i;
5626
5627         for (i = 0; i < 15; i++) {
5628                 if (skl_cdclk_pcu_ready(dev_priv))
5629                         return true;
5630                 udelay(10);
5631         }
5632
5633         return false;
5634 }
5635
5636 static void skl_set_cdclk(struct drm_i915_private *dev_priv, int cdclk)
5637 {
5638         struct drm_device *dev = dev_priv->dev;
5639         u32 freq_select, pcu_ack;
5640
5641         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", cdclk);
5642
5643         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5644                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5645                 return;
5646         }
5647
5648         /* set CDCLK_CTL */
5649         switch (cdclk) {
5650         case 450000:
5651         case 432000:
5652                 freq_select = CDCLK_FREQ_450_432;
5653                 pcu_ack = 1;
5654                 break;
5655         case 540000:
5656                 freq_select = CDCLK_FREQ_540;
5657                 pcu_ack = 2;
5658                 break;
5659         case 308570:
5660         case 337500:
5661         default:
5662                 freq_select = CDCLK_FREQ_337_308;
5663                 pcu_ack = 0;
5664                 break;
5665         case 617140:
5666         case 675000:
5667                 freq_select = CDCLK_FREQ_675_617;
5668                 pcu_ack = 3;
5669                 break;
5670         }
5671
5672         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(cdclk));
5673         POSTING_READ(CDCLK_CTL);
5674
5675         /* inform PCU of the change */
5676         mutex_lock(&dev_priv->rps.hw_lock);
5677         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5678         mutex_unlock(&dev_priv->rps.hw_lock);
5679
5680         intel_update_cdclk(dev);
5681 }
5682
5683 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5684 {
5685         /* disable DBUF power */
5686         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5687         POSTING_READ(DBUF_CTL);
5688
5689         udelay(10);
5690
5691         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5692                 DRM_ERROR("DBuf power disable timeout\n");
5693
5694         skl_dpll0_disable(dev_priv);
5695 }
5696
5697 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5698 {
5699         unsigned int vco;
5700
5701         /* DPLL0 not enabled (happens on early BIOS versions) */
5702         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5703                 /* enable DPLL0 */
5704                 vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5705                 skl_dpll0_enable(dev_priv, vco);
5706         }
5707
5708         /* set CDCLK to the frequency the BIOS chose */
5709         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5710
5711         /* enable DBUF power */
5712         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5713         POSTING_READ(DBUF_CTL);
5714
5715         udelay(10);
5716
5717         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5718                 DRM_ERROR("DBuf power enable timeout\n");
5719 }
5720
5721 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5722 {
5723         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5724         uint32_t cdctl = I915_READ(CDCLK_CTL);
5725         int freq = dev_priv->skl_boot_cdclk;
5726
5727         /*
5728          * check if the pre-os intialized the display
5729          * There is SWF18 scratchpad register defined which is set by the
5730          * pre-os which can be used by the OS drivers to check the status
5731          */
5732         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5733                 goto sanitize;
5734
5735         /* Is PLL enabled and locked ? */
5736         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5737                 goto sanitize;
5738
5739         /* DPLL okay; verify the cdclock
5740          *
5741          * Noticed in some instances that the freq selection is correct but
5742          * decimal part is programmed wrong from BIOS where pre-os does not
5743          * enable display. Verify the same as well.
5744          */
5745         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
5746                 /* All well; nothing to sanitize */
5747                 return false;
5748 sanitize:
5749         /*
5750          * As of now initialize with max cdclk till
5751          * we get dynamic cdclk support
5752          * */
5753         dev_priv->skl_boot_cdclk = dev_priv->max_cdclk_freq;
5754         skl_init_cdclk(dev_priv);
5755
5756         /* we did have to sanitize */
5757         return true;
5758 }
5759
5760 /* Adjust CDclk dividers to allow high res or save power if possible */
5761 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5762 {
5763         struct drm_i915_private *dev_priv = dev->dev_private;
5764         u32 val, cmd;
5765
5766         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5767                                         != dev_priv->cdclk_freq);
5768
5769         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5770                 cmd = 2;
5771         else if (cdclk == 266667)
5772                 cmd = 1;
5773         else
5774                 cmd = 0;
5775
5776         mutex_lock(&dev_priv->rps.hw_lock);
5777         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5778         val &= ~DSPFREQGUAR_MASK;
5779         val |= (cmd << DSPFREQGUAR_SHIFT);
5780         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5781         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5782                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5783                      50)) {
5784                 DRM_ERROR("timed out waiting for CDclk change\n");
5785         }
5786         mutex_unlock(&dev_priv->rps.hw_lock);
5787
5788         mutex_lock(&dev_priv->sb_lock);
5789
5790         if (cdclk == 400000) {
5791                 u32 divider;
5792
5793                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5794
5795                 /* adjust cdclk divider */
5796                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5797                 val &= ~CCK_FREQUENCY_VALUES;
5798                 val |= divider;
5799                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5800
5801                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5802                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5803                              50))
5804                         DRM_ERROR("timed out waiting for CDclk change\n");
5805         }
5806
5807         /* adjust self-refresh exit latency value */
5808         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5809         val &= ~0x7f;
5810
5811         /*
5812          * For high bandwidth configs, we set a higher latency in the bunit
5813          * so that the core display fetch happens in time to avoid underruns.
5814          */
5815         if (cdclk == 400000)
5816                 val |= 4500 / 250; /* 4.5 usec */
5817         else
5818                 val |= 3000 / 250; /* 3.0 usec */
5819         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5820
5821         mutex_unlock(&dev_priv->sb_lock);
5822
5823         intel_update_cdclk(dev);
5824 }
5825
5826 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5827 {
5828         struct drm_i915_private *dev_priv = dev->dev_private;
5829         u32 val, cmd;
5830
5831         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5832                                                 != dev_priv->cdclk_freq);
5833
5834         switch (cdclk) {
5835         case 333333:
5836         case 320000:
5837         case 266667:
5838         case 200000:
5839                 break;
5840         default:
5841                 MISSING_CASE(cdclk);
5842                 return;
5843         }
5844
5845         /*
5846          * Specs are full of misinformation, but testing on actual
5847          * hardware has shown that we just need to write the desired
5848          * CCK divider into the Punit register.
5849          */
5850         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5851
5852         mutex_lock(&dev_priv->rps.hw_lock);
5853         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5854         val &= ~DSPFREQGUAR_MASK_CHV;
5855         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5856         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5857         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5858                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5859                      50)) {
5860                 DRM_ERROR("timed out waiting for CDclk change\n");
5861         }
5862         mutex_unlock(&dev_priv->rps.hw_lock);
5863
5864         intel_update_cdclk(dev);
5865 }
5866
5867 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5868                                  int max_pixclk)
5869 {
5870         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5871         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5872
5873         /*
5874          * Really only a few cases to deal with, as only 4 CDclks are supported:
5875          *   200MHz
5876          *   267MHz
5877          *   320/333MHz (depends on HPLL freq)
5878          *   400MHz (VLV only)
5879          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5880          * of the lower bin and adjust if needed.
5881          *
5882          * We seem to get an unstable or solid color picture at 200MHz.
5883          * Not sure what's wrong. For now use 200MHz only when all pipes
5884          * are off.
5885          */
5886         if (!IS_CHERRYVIEW(dev_priv) &&
5887             max_pixclk > freq_320*limit/100)
5888                 return 400000;
5889         else if (max_pixclk > 266667*limit/100)
5890                 return freq_320;
5891         else if (max_pixclk > 0)
5892                 return 266667;
5893         else
5894                 return 200000;
5895 }
5896
5897 static int broxton_calc_cdclk(int max_pixclk)
5898 {
5899         /*
5900          * FIXME:
5901          * - set 19.2MHz bypass frequency if there are no active pipes
5902          */
5903         if (max_pixclk > 576000)
5904                 return 624000;
5905         else if (max_pixclk > 384000)
5906                 return 576000;
5907         else if (max_pixclk > 288000)
5908                 return 384000;
5909         else if (max_pixclk > 144000)
5910                 return 288000;
5911         else
5912                 return 144000;
5913 }
5914
5915 /* Compute the max pixel clock for new configuration. */
5916 static int intel_mode_max_pixclk(struct drm_device *dev,
5917                                  struct drm_atomic_state *state)
5918 {
5919         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
5920         struct drm_i915_private *dev_priv = dev->dev_private;
5921         struct drm_crtc *crtc;
5922         struct drm_crtc_state *crtc_state;
5923         unsigned max_pixclk = 0, i;
5924         enum pipe pipe;
5925
5926         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
5927                sizeof(intel_state->min_pixclk));
5928
5929         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5930                 int pixclk = 0;
5931
5932                 if (crtc_state->enable)
5933                         pixclk = crtc_state->adjusted_mode.crtc_clock;
5934
5935                 intel_state->min_pixclk[i] = pixclk;
5936         }
5937
5938         for_each_pipe(dev_priv, pipe)
5939                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
5940
5941         return max_pixclk;
5942 }
5943
5944 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5945 {
5946         struct drm_device *dev = state->dev;
5947         struct drm_i915_private *dev_priv = dev->dev_private;
5948         int max_pixclk = intel_mode_max_pixclk(dev, state);
5949         struct intel_atomic_state *intel_state =
5950                 to_intel_atomic_state(state);
5951
5952         intel_state->cdclk = intel_state->dev_cdclk =
5953                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5954
5955         if (!intel_state->active_crtcs)
5956                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
5957
5958         return 0;
5959 }
5960
5961 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5962 {
5963         int max_pixclk = ilk_max_pixel_rate(state);
5964         struct intel_atomic_state *intel_state =
5965                 to_intel_atomic_state(state);
5966
5967         intel_state->cdclk = intel_state->dev_cdclk =
5968                 broxton_calc_cdclk(max_pixclk);
5969
5970         if (!intel_state->active_crtcs)
5971                 intel_state->dev_cdclk = broxton_calc_cdclk(0);
5972
5973         return 0;
5974 }
5975
5976 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5977 {
5978         unsigned int credits, default_credits;
5979
5980         if (IS_CHERRYVIEW(dev_priv))
5981                 default_credits = PFI_CREDIT(12);
5982         else
5983                 default_credits = PFI_CREDIT(8);
5984
5985         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
5986                 /* CHV suggested value is 31 or 63 */
5987                 if (IS_CHERRYVIEW(dev_priv))
5988                         credits = PFI_CREDIT_63;
5989                 else
5990                         credits = PFI_CREDIT(15);
5991         } else {
5992                 credits = default_credits;
5993         }
5994
5995         /*
5996          * WA - write default credits before re-programming
5997          * FIXME: should we also set the resend bit here?
5998          */
5999         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6000                    default_credits);
6001
6002         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6003                    credits | PFI_CREDIT_RESEND);
6004
6005         /*
6006          * FIXME is this guaranteed to clear
6007          * immediately or should we poll for it?
6008          */
6009         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6010 }
6011
6012 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6013 {
6014         struct drm_device *dev = old_state->dev;
6015         struct drm_i915_private *dev_priv = dev->dev_private;
6016         struct intel_atomic_state *old_intel_state =
6017                 to_intel_atomic_state(old_state);
6018         unsigned req_cdclk = old_intel_state->dev_cdclk;
6019
6020         /*
6021          * FIXME: We can end up here with all power domains off, yet
6022          * with a CDCLK frequency other than the minimum. To account
6023          * for this take the PIPE-A power domain, which covers the HW
6024          * blocks needed for the following programming. This can be
6025          * removed once it's guaranteed that we get here either with
6026          * the minimum CDCLK set, or the required power domains
6027          * enabled.
6028          */
6029         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6030
6031         if (IS_CHERRYVIEW(dev))
6032                 cherryview_set_cdclk(dev, req_cdclk);
6033         else
6034                 valleyview_set_cdclk(dev, req_cdclk);
6035
6036         vlv_program_pfi_credits(dev_priv);
6037
6038         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6039 }
6040
6041 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6042 {
6043         struct drm_device *dev = crtc->dev;
6044         struct drm_i915_private *dev_priv = to_i915(dev);
6045         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6046         struct intel_encoder *encoder;
6047         struct intel_crtc_state *pipe_config =
6048                 to_intel_crtc_state(crtc->state);
6049         int pipe = intel_crtc->pipe;
6050
6051         if (WARN_ON(intel_crtc->active))
6052                 return;
6053
6054         if (intel_crtc->config->has_dp_encoder)
6055                 intel_dp_set_m_n(intel_crtc, M1_N1);
6056
6057         intel_set_pipe_timings(intel_crtc);
6058         intel_set_pipe_src_size(intel_crtc);
6059
6060         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6061                 struct drm_i915_private *dev_priv = dev->dev_private;
6062
6063                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6064                 I915_WRITE(CHV_CANVAS(pipe), 0);
6065         }
6066
6067         i9xx_set_pipeconf(intel_crtc);
6068
6069         intel_crtc->active = true;
6070
6071         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6072
6073         for_each_encoder_on_crtc(dev, crtc, encoder)
6074                 if (encoder->pre_pll_enable)
6075                         encoder->pre_pll_enable(encoder);
6076
6077         if (IS_CHERRYVIEW(dev)) {
6078                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6079                 chv_enable_pll(intel_crtc, intel_crtc->config);
6080         } else {
6081                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6082                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6083         }
6084
6085         for_each_encoder_on_crtc(dev, crtc, encoder)
6086                 if (encoder->pre_enable)
6087                         encoder->pre_enable(encoder);
6088
6089         i9xx_pfit_enable(intel_crtc);
6090
6091         intel_color_load_luts(&pipe_config->base);
6092
6093         intel_update_watermarks(crtc);
6094         intel_enable_pipe(intel_crtc);
6095
6096         assert_vblank_disabled(crtc);
6097         drm_crtc_vblank_on(crtc);
6098
6099         for_each_encoder_on_crtc(dev, crtc, encoder)
6100                 encoder->enable(encoder);
6101 }
6102
6103 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6104 {
6105         struct drm_device *dev = crtc->base.dev;
6106         struct drm_i915_private *dev_priv = dev->dev_private;
6107
6108         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6109         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6110 }
6111
6112 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6113 {
6114         struct drm_device *dev = crtc->dev;
6115         struct drm_i915_private *dev_priv = to_i915(dev);
6116         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6117         struct intel_encoder *encoder;
6118         struct intel_crtc_state *pipe_config =
6119                 to_intel_crtc_state(crtc->state);
6120         enum pipe pipe = intel_crtc->pipe;
6121
6122         if (WARN_ON(intel_crtc->active))
6123                 return;
6124
6125         i9xx_set_pll_dividers(intel_crtc);
6126
6127         if (intel_crtc->config->has_dp_encoder)
6128                 intel_dp_set_m_n(intel_crtc, M1_N1);
6129
6130         intel_set_pipe_timings(intel_crtc);
6131         intel_set_pipe_src_size(intel_crtc);
6132
6133         i9xx_set_pipeconf(intel_crtc);
6134
6135         intel_crtc->active = true;
6136
6137         if (!IS_GEN2(dev))
6138                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6139
6140         for_each_encoder_on_crtc(dev, crtc, encoder)
6141                 if (encoder->pre_enable)
6142                         encoder->pre_enable(encoder);
6143
6144         i9xx_enable_pll(intel_crtc);
6145
6146         i9xx_pfit_enable(intel_crtc);
6147
6148         intel_color_load_luts(&pipe_config->base);
6149
6150         intel_update_watermarks(crtc);
6151         intel_enable_pipe(intel_crtc);
6152
6153         assert_vblank_disabled(crtc);
6154         drm_crtc_vblank_on(crtc);
6155
6156         for_each_encoder_on_crtc(dev, crtc, encoder)
6157                 encoder->enable(encoder);
6158 }
6159
6160 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6161 {
6162         struct drm_device *dev = crtc->base.dev;
6163         struct drm_i915_private *dev_priv = dev->dev_private;
6164
6165         if (!crtc->config->gmch_pfit.control)
6166                 return;
6167
6168         assert_pipe_disabled(dev_priv, crtc->pipe);
6169
6170         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6171                          I915_READ(PFIT_CONTROL));
6172         I915_WRITE(PFIT_CONTROL, 0);
6173 }
6174
6175 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6176 {
6177         struct drm_device *dev = crtc->dev;
6178         struct drm_i915_private *dev_priv = dev->dev_private;
6179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6180         struct intel_encoder *encoder;
6181         int pipe = intel_crtc->pipe;
6182
6183         /*
6184          * On gen2 planes are double buffered but the pipe isn't, so we must
6185          * wait for planes to fully turn off before disabling the pipe.
6186          */
6187         if (IS_GEN2(dev))
6188                 intel_wait_for_vblank(dev, pipe);
6189
6190         for_each_encoder_on_crtc(dev, crtc, encoder)
6191                 encoder->disable(encoder);
6192
6193         drm_crtc_vblank_off(crtc);
6194         assert_vblank_disabled(crtc);
6195
6196         intel_disable_pipe(intel_crtc);
6197
6198         i9xx_pfit_disable(intel_crtc);
6199
6200         for_each_encoder_on_crtc(dev, crtc, encoder)
6201                 if (encoder->post_disable)
6202                         encoder->post_disable(encoder);
6203
6204         if (!intel_crtc->config->has_dsi_encoder) {
6205                 if (IS_CHERRYVIEW(dev))
6206                         chv_disable_pll(dev_priv, pipe);
6207                 else if (IS_VALLEYVIEW(dev))
6208                         vlv_disable_pll(dev_priv, pipe);
6209                 else
6210                         i9xx_disable_pll(intel_crtc);
6211         }
6212
6213         for_each_encoder_on_crtc(dev, crtc, encoder)
6214                 if (encoder->post_pll_disable)
6215                         encoder->post_pll_disable(encoder);
6216
6217         if (!IS_GEN2(dev))
6218                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6219 }
6220
6221 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6222 {
6223         struct intel_encoder *encoder;
6224         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6225         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6226         enum intel_display_power_domain domain;
6227         unsigned long domains;
6228
6229         if (!intel_crtc->active)
6230                 return;
6231
6232         if (to_intel_plane_state(crtc->primary->state)->visible) {
6233                 WARN_ON(intel_crtc->unpin_work);
6234
6235                 intel_pre_disable_primary_noatomic(crtc);
6236
6237                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6238                 to_intel_plane_state(crtc->primary->state)->visible = false;
6239         }
6240
6241         dev_priv->display.crtc_disable(crtc);
6242
6243         DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was enabled, now disabled\n",
6244                       crtc->base.id);
6245
6246         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6247         crtc->state->active = false;
6248         intel_crtc->active = false;
6249         crtc->enabled = false;
6250         crtc->state->connector_mask = 0;
6251         crtc->state->encoder_mask = 0;
6252
6253         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6254                 encoder->base.crtc = NULL;
6255
6256         intel_fbc_disable(intel_crtc);
6257         intel_update_watermarks(crtc);
6258         intel_disable_shared_dpll(intel_crtc);
6259
6260         domains = intel_crtc->enabled_power_domains;
6261         for_each_power_domain(domain, domains)
6262                 intel_display_power_put(dev_priv, domain);
6263         intel_crtc->enabled_power_domains = 0;
6264
6265         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6266         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6267 }
6268
6269 /*
6270  * turn all crtc's off, but do not adjust state
6271  * This has to be paired with a call to intel_modeset_setup_hw_state.
6272  */
6273 int intel_display_suspend(struct drm_device *dev)
6274 {
6275         struct drm_i915_private *dev_priv = to_i915(dev);
6276         struct drm_atomic_state *state;
6277         int ret;
6278
6279         state = drm_atomic_helper_suspend(dev);
6280         ret = PTR_ERR_OR_ZERO(state);
6281         if (ret)
6282                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6283         else
6284                 dev_priv->modeset_restore_state = state;
6285         return ret;
6286 }
6287
6288 void intel_encoder_destroy(struct drm_encoder *encoder)
6289 {
6290         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6291
6292         drm_encoder_cleanup(encoder);
6293         kfree(intel_encoder);
6294 }
6295
6296 /* Cross check the actual hw state with our own modeset state tracking (and it's
6297  * internal consistency). */
6298 static void intel_connector_verify_state(struct intel_connector *connector)
6299 {
6300         struct drm_crtc *crtc = connector->base.state->crtc;
6301
6302         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6303                       connector->base.base.id,
6304                       connector->base.name);
6305
6306         if (connector->get_hw_state(connector)) {
6307                 struct intel_encoder *encoder = connector->encoder;
6308                 struct drm_connector_state *conn_state = connector->base.state;
6309
6310                 I915_STATE_WARN(!crtc,
6311                          "connector enabled without attached crtc\n");
6312
6313                 if (!crtc)
6314                         return;
6315
6316                 I915_STATE_WARN(!crtc->state->active,
6317                       "connector is active, but attached crtc isn't\n");
6318
6319                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6320                         return;
6321
6322                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6323                         "atomic encoder doesn't match attached encoder\n");
6324
6325                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6326                         "attached encoder crtc differs from connector crtc\n");
6327         } else {
6328                 I915_STATE_WARN(crtc && crtc->state->active,
6329                         "attached crtc is active, but connector isn't\n");
6330                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6331                         "best encoder set without crtc!\n");
6332         }
6333 }
6334
6335 int intel_connector_init(struct intel_connector *connector)
6336 {
6337         drm_atomic_helper_connector_reset(&connector->base);
6338
6339         if (!connector->base.state)
6340                 return -ENOMEM;
6341
6342         return 0;
6343 }
6344
6345 struct intel_connector *intel_connector_alloc(void)
6346 {
6347         struct intel_connector *connector;
6348
6349         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6350         if (!connector)
6351                 return NULL;
6352
6353         if (intel_connector_init(connector) < 0) {
6354                 kfree(connector);
6355                 return NULL;
6356         }
6357
6358         return connector;
6359 }
6360
6361 /* Simple connector->get_hw_state implementation for encoders that support only
6362  * one connector and no cloning and hence the encoder state determines the state
6363  * of the connector. */
6364 bool intel_connector_get_hw_state(struct intel_connector *connector)
6365 {
6366         enum pipe pipe = 0;
6367         struct intel_encoder *encoder = connector->encoder;
6368
6369         return encoder->get_hw_state(encoder, &pipe);
6370 }
6371
6372 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6373 {
6374         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6375                 return crtc_state->fdi_lanes;
6376
6377         return 0;
6378 }
6379
6380 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6381                                      struct intel_crtc_state *pipe_config)
6382 {
6383         struct drm_atomic_state *state = pipe_config->base.state;
6384         struct intel_crtc *other_crtc;
6385         struct intel_crtc_state *other_crtc_state;
6386
6387         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6388                       pipe_name(pipe), pipe_config->fdi_lanes);
6389         if (pipe_config->fdi_lanes > 4) {
6390                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6391                               pipe_name(pipe), pipe_config->fdi_lanes);
6392                 return -EINVAL;
6393         }
6394
6395         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6396                 if (pipe_config->fdi_lanes > 2) {
6397                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6398                                       pipe_config->fdi_lanes);
6399                         return -EINVAL;
6400                 } else {
6401                         return 0;
6402                 }
6403         }
6404
6405         if (INTEL_INFO(dev)->num_pipes == 2)
6406                 return 0;
6407
6408         /* Ivybridge 3 pipe is really complicated */
6409         switch (pipe) {
6410         case PIPE_A:
6411                 return 0;
6412         case PIPE_B:
6413                 if (pipe_config->fdi_lanes <= 2)
6414                         return 0;
6415
6416                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6417                 other_crtc_state =
6418                         intel_atomic_get_crtc_state(state, other_crtc);
6419                 if (IS_ERR(other_crtc_state))
6420                         return PTR_ERR(other_crtc_state);
6421
6422                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6423                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6424                                       pipe_name(pipe), pipe_config->fdi_lanes);
6425                         return -EINVAL;
6426                 }
6427                 return 0;
6428         case PIPE_C:
6429                 if (pipe_config->fdi_lanes > 2) {
6430                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6431                                       pipe_name(pipe), pipe_config->fdi_lanes);
6432                         return -EINVAL;
6433                 }
6434
6435                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6436                 other_crtc_state =
6437                         intel_atomic_get_crtc_state(state, other_crtc);
6438                 if (IS_ERR(other_crtc_state))
6439                         return PTR_ERR(other_crtc_state);
6440
6441                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6442                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6443                         return -EINVAL;
6444                 }
6445                 return 0;
6446         default:
6447                 BUG();
6448         }
6449 }
6450
6451 #define RETRY 1
6452 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6453                                        struct intel_crtc_state *pipe_config)
6454 {
6455         struct drm_device *dev = intel_crtc->base.dev;
6456         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6457         int lane, link_bw, fdi_dotclock, ret;
6458         bool needs_recompute = false;
6459
6460 retry:
6461         /* FDI is a binary signal running at ~2.7GHz, encoding
6462          * each output octet as 10 bits. The actual frequency
6463          * is stored as a divider into a 100MHz clock, and the
6464          * mode pixel clock is stored in units of 1KHz.
6465          * Hence the bw of each lane in terms of the mode signal
6466          * is:
6467          */
6468         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6469
6470         fdi_dotclock = adjusted_mode->crtc_clock;
6471
6472         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6473                                            pipe_config->pipe_bpp);
6474
6475         pipe_config->fdi_lanes = lane;
6476
6477         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6478                                link_bw, &pipe_config->fdi_m_n);
6479
6480         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6481         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6482                 pipe_config->pipe_bpp -= 2*3;
6483                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6484                               pipe_config->pipe_bpp);
6485                 needs_recompute = true;
6486                 pipe_config->bw_constrained = true;
6487
6488                 goto retry;
6489         }
6490
6491         if (needs_recompute)
6492                 return RETRY;
6493
6494         return ret;
6495 }
6496
6497 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6498                                      struct intel_crtc_state *pipe_config)
6499 {
6500         if (pipe_config->pipe_bpp > 24)
6501                 return false;
6502
6503         /* HSW can handle pixel rate up to cdclk? */
6504         if (IS_HASWELL(dev_priv))
6505                 return true;
6506
6507         /*
6508          * We compare against max which means we must take
6509          * the increased cdclk requirement into account when
6510          * calculating the new cdclk.
6511          *
6512          * Should measure whether using a lower cdclk w/o IPS
6513          */
6514         return ilk_pipe_pixel_rate(pipe_config) <=
6515                 dev_priv->max_cdclk_freq * 95 / 100;
6516 }
6517
6518 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6519                                    struct intel_crtc_state *pipe_config)
6520 {
6521         struct drm_device *dev = crtc->base.dev;
6522         struct drm_i915_private *dev_priv = dev->dev_private;
6523
6524         pipe_config->ips_enabled = i915.enable_ips &&
6525                 hsw_crtc_supports_ips(crtc) &&
6526                 pipe_config_supports_ips(dev_priv, pipe_config);
6527 }
6528
6529 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6530 {
6531         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6532
6533         /* GDG double wide on either pipe, otherwise pipe A only */
6534         return INTEL_INFO(dev_priv)->gen < 4 &&
6535                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6536 }
6537
6538 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6539                                      struct intel_crtc_state *pipe_config)
6540 {
6541         struct drm_device *dev = crtc->base.dev;
6542         struct drm_i915_private *dev_priv = dev->dev_private;
6543         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6544
6545         /* FIXME should check pixel clock limits on all platforms */
6546         if (INTEL_INFO(dev)->gen < 4) {
6547                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6548
6549                 /*
6550                  * Enable double wide mode when the dot clock
6551                  * is > 90% of the (display) core speed.
6552                  */
6553                 if (intel_crtc_supports_double_wide(crtc) &&
6554                     adjusted_mode->crtc_clock > clock_limit) {
6555                         clock_limit *= 2;
6556                         pipe_config->double_wide = true;
6557                 }
6558
6559                 if (adjusted_mode->crtc_clock > clock_limit) {
6560                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6561                                       adjusted_mode->crtc_clock, clock_limit,
6562                                       yesno(pipe_config->double_wide));
6563                         return -EINVAL;
6564                 }
6565         }
6566
6567         /*
6568          * Pipe horizontal size must be even in:
6569          * - DVO ganged mode
6570          * - LVDS dual channel mode
6571          * - Double wide pipe
6572          */
6573         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6574              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6575                 pipe_config->pipe_src_w &= ~1;
6576
6577         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6578          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6579          */
6580         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6581                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6582                 return -EINVAL;
6583
6584         if (HAS_IPS(dev))
6585                 hsw_compute_ips_config(crtc, pipe_config);
6586
6587         if (pipe_config->has_pch_encoder)
6588                 return ironlake_fdi_compute_config(crtc, pipe_config);
6589
6590         return 0;
6591 }
6592
6593 static int skylake_get_display_clock_speed(struct drm_device *dev)
6594 {
6595         struct drm_i915_private *dev_priv = to_i915(dev);
6596         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6597         uint32_t cdctl = I915_READ(CDCLK_CTL);
6598         uint32_t linkrate;
6599
6600         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6601                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6602
6603         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6604                 return 540000;
6605
6606         linkrate = (I915_READ(DPLL_CTRL1) &
6607                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6608
6609         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6610             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6611                 /* vco 8640 */
6612                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6613                 case CDCLK_FREQ_450_432:
6614                         return 432000;
6615                 case CDCLK_FREQ_337_308:
6616                         return 308570;
6617                 case CDCLK_FREQ_675_617:
6618                         return 617140;
6619                 default:
6620                         WARN(1, "Unknown cd freq selection\n");
6621                 }
6622         } else {
6623                 /* vco 8100 */
6624                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6625                 case CDCLK_FREQ_450_432:
6626                         return 450000;
6627                 case CDCLK_FREQ_337_308:
6628                         return 337500;
6629                 case CDCLK_FREQ_675_617:
6630                         return 675000;
6631                 default:
6632                         WARN(1, "Unknown cd freq selection\n");
6633                 }
6634         }
6635
6636         /* error case, do as if DPLL0 isn't enabled */
6637         return 24000;
6638 }
6639
6640 static int broxton_get_display_clock_speed(struct drm_device *dev)
6641 {
6642         struct drm_i915_private *dev_priv = to_i915(dev);
6643         uint32_t cdctl = I915_READ(CDCLK_CTL);
6644         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6645         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6646         int cdclk;
6647
6648         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6649                 return 19200;
6650
6651         cdclk = 19200 * pll_ratio / 2;
6652
6653         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6654         case BXT_CDCLK_CD2X_DIV_SEL_1:
6655                 return cdclk;  /* 576MHz or 624MHz */
6656         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6657                 return cdclk * 2 / 3; /* 384MHz */
6658         case BXT_CDCLK_CD2X_DIV_SEL_2:
6659                 return cdclk / 2; /* 288MHz */
6660         case BXT_CDCLK_CD2X_DIV_SEL_4:
6661                 return cdclk / 4; /* 144MHz */
6662         }
6663
6664         /* error case, do as if DE PLL isn't enabled */
6665         return 19200;
6666 }
6667
6668 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6669 {
6670         struct drm_i915_private *dev_priv = dev->dev_private;
6671         uint32_t lcpll = I915_READ(LCPLL_CTL);
6672         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6673
6674         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6675                 return 800000;
6676         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6677                 return 450000;
6678         else if (freq == LCPLL_CLK_FREQ_450)
6679                 return 450000;
6680         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6681                 return 540000;
6682         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6683                 return 337500;
6684         else
6685                 return 675000;
6686 }
6687
6688 static int haswell_get_display_clock_speed(struct drm_device *dev)
6689 {
6690         struct drm_i915_private *dev_priv = dev->dev_private;
6691         uint32_t lcpll = I915_READ(LCPLL_CTL);
6692         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6693
6694         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6695                 return 800000;
6696         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6697                 return 450000;
6698         else if (freq == LCPLL_CLK_FREQ_450)
6699                 return 450000;
6700         else if (IS_HSW_ULT(dev))
6701                 return 337500;
6702         else
6703                 return 540000;
6704 }
6705
6706 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6707 {
6708         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6709                                       CCK_DISPLAY_CLOCK_CONTROL);
6710 }
6711
6712 static int ilk_get_display_clock_speed(struct drm_device *dev)
6713 {
6714         return 450000;
6715 }
6716
6717 static int i945_get_display_clock_speed(struct drm_device *dev)
6718 {
6719         return 400000;
6720 }
6721
6722 static int i915_get_display_clock_speed(struct drm_device *dev)
6723 {
6724         return 333333;
6725 }
6726
6727 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6728 {
6729         return 200000;
6730 }
6731
6732 static int pnv_get_display_clock_speed(struct drm_device *dev)
6733 {
6734         u16 gcfgc = 0;
6735
6736         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6737
6738         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6739         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6740                 return 266667;
6741         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6742                 return 333333;
6743         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6744                 return 444444;
6745         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6746                 return 200000;
6747         default:
6748                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6749         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6750                 return 133333;
6751         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6752                 return 166667;
6753         }
6754 }
6755
6756 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6757 {
6758         u16 gcfgc = 0;
6759
6760         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6761
6762         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6763                 return 133333;
6764         else {
6765                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6766                 case GC_DISPLAY_CLOCK_333_MHZ:
6767                         return 333333;
6768                 default:
6769                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6770                         return 190000;
6771                 }
6772         }
6773 }
6774
6775 static int i865_get_display_clock_speed(struct drm_device *dev)
6776 {
6777         return 266667;
6778 }
6779
6780 static int i85x_get_display_clock_speed(struct drm_device *dev)
6781 {
6782         u16 hpllcc = 0;
6783
6784         /*
6785          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6786          * encoding is different :(
6787          * FIXME is this the right way to detect 852GM/852GMV?
6788          */
6789         if (dev->pdev->revision == 0x1)
6790                 return 133333;
6791
6792         pci_bus_read_config_word(dev->pdev->bus,
6793                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6794
6795         /* Assume that the hardware is in the high speed state.  This
6796          * should be the default.
6797          */
6798         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6799         case GC_CLOCK_133_200:
6800         case GC_CLOCK_133_200_2:
6801         case GC_CLOCK_100_200:
6802                 return 200000;
6803         case GC_CLOCK_166_250:
6804                 return 250000;
6805         case GC_CLOCK_100_133:
6806                 return 133333;
6807         case GC_CLOCK_133_266:
6808         case GC_CLOCK_133_266_2:
6809         case GC_CLOCK_166_266:
6810                 return 266667;
6811         }
6812
6813         /* Shouldn't happen */
6814         return 0;
6815 }
6816
6817 static int i830_get_display_clock_speed(struct drm_device *dev)
6818 {
6819         return 133333;
6820 }
6821
6822 static unsigned int intel_hpll_vco(struct drm_device *dev)
6823 {
6824         struct drm_i915_private *dev_priv = dev->dev_private;
6825         static const unsigned int blb_vco[8] = {
6826                 [0] = 3200000,
6827                 [1] = 4000000,
6828                 [2] = 5333333,
6829                 [3] = 4800000,
6830                 [4] = 6400000,
6831         };
6832         static const unsigned int pnv_vco[8] = {
6833                 [0] = 3200000,
6834                 [1] = 4000000,
6835                 [2] = 5333333,
6836                 [3] = 4800000,
6837                 [4] = 2666667,
6838         };
6839         static const unsigned int cl_vco[8] = {
6840                 [0] = 3200000,
6841                 [1] = 4000000,
6842                 [2] = 5333333,
6843                 [3] = 6400000,
6844                 [4] = 3333333,
6845                 [5] = 3566667,
6846                 [6] = 4266667,
6847         };
6848         static const unsigned int elk_vco[8] = {
6849                 [0] = 3200000,
6850                 [1] = 4000000,
6851                 [2] = 5333333,
6852                 [3] = 4800000,
6853         };
6854         static const unsigned int ctg_vco[8] = {
6855                 [0] = 3200000,
6856                 [1] = 4000000,
6857                 [2] = 5333333,
6858                 [3] = 6400000,
6859                 [4] = 2666667,
6860                 [5] = 4266667,
6861         };
6862         const unsigned int *vco_table;
6863         unsigned int vco;
6864         uint8_t tmp = 0;
6865
6866         /* FIXME other chipsets? */
6867         if (IS_GM45(dev))
6868                 vco_table = ctg_vco;
6869         else if (IS_G4X(dev))
6870                 vco_table = elk_vco;
6871         else if (IS_CRESTLINE(dev))
6872                 vco_table = cl_vco;
6873         else if (IS_PINEVIEW(dev))
6874                 vco_table = pnv_vco;
6875         else if (IS_G33(dev))
6876                 vco_table = blb_vco;
6877         else
6878                 return 0;
6879
6880         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6881
6882         vco = vco_table[tmp & 0x7];
6883         if (vco == 0)
6884                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6885         else
6886                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6887
6888         return vco;
6889 }
6890
6891 static int gm45_get_display_clock_speed(struct drm_device *dev)
6892 {
6893         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6894         uint16_t tmp = 0;
6895
6896         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6897
6898         cdclk_sel = (tmp >> 12) & 0x1;
6899
6900         switch (vco) {
6901         case 2666667:
6902         case 4000000:
6903         case 5333333:
6904                 return cdclk_sel ? 333333 : 222222;
6905         case 3200000:
6906                 return cdclk_sel ? 320000 : 228571;
6907         default:
6908                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6909                 return 222222;
6910         }
6911 }
6912
6913 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6914 {
6915         static const uint8_t div_3200[] = { 16, 10,  8 };
6916         static const uint8_t div_4000[] = { 20, 12, 10 };
6917         static const uint8_t div_5333[] = { 24, 16, 14 };
6918         const uint8_t *div_table;
6919         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6920         uint16_t tmp = 0;
6921
6922         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6923
6924         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6925
6926         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6927                 goto fail;
6928
6929         switch (vco) {
6930         case 3200000:
6931                 div_table = div_3200;
6932                 break;
6933         case 4000000:
6934                 div_table = div_4000;
6935                 break;
6936         case 5333333:
6937                 div_table = div_5333;
6938                 break;
6939         default:
6940                 goto fail;
6941         }
6942
6943         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6944
6945 fail:
6946         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6947         return 200000;
6948 }
6949
6950 static int g33_get_display_clock_speed(struct drm_device *dev)
6951 {
6952         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6953         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6954         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6955         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6956         const uint8_t *div_table;
6957         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6958         uint16_t tmp = 0;
6959
6960         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6961
6962         cdclk_sel = (tmp >> 4) & 0x7;
6963
6964         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6965                 goto fail;
6966
6967         switch (vco) {
6968         case 3200000:
6969                 div_table = div_3200;
6970                 break;
6971         case 4000000:
6972                 div_table = div_4000;
6973                 break;
6974         case 4800000:
6975                 div_table = div_4800;
6976                 break;
6977         case 5333333:
6978                 div_table = div_5333;
6979                 break;
6980         default:
6981                 goto fail;
6982         }
6983
6984         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6985
6986 fail:
6987         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6988         return 190476;
6989 }
6990
6991 static void
6992 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6993 {
6994         while (*num > DATA_LINK_M_N_MASK ||
6995                *den > DATA_LINK_M_N_MASK) {
6996                 *num >>= 1;
6997                 *den >>= 1;
6998         }
6999 }
7000
7001 static void compute_m_n(unsigned int m, unsigned int n,
7002                         uint32_t *ret_m, uint32_t *ret_n)
7003 {
7004         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7005         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7006         intel_reduce_m_n_ratio(ret_m, ret_n);
7007 }
7008
7009 void
7010 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7011                        int pixel_clock, int link_clock,
7012                        struct intel_link_m_n *m_n)
7013 {
7014         m_n->tu = 64;
7015
7016         compute_m_n(bits_per_pixel * pixel_clock,
7017                     link_clock * nlanes * 8,
7018                     &m_n->gmch_m, &m_n->gmch_n);
7019
7020         compute_m_n(pixel_clock, link_clock,
7021                     &m_n->link_m, &m_n->link_n);
7022 }
7023
7024 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7025 {
7026         if (i915.panel_use_ssc >= 0)
7027                 return i915.panel_use_ssc != 0;
7028         return dev_priv->vbt.lvds_use_ssc
7029                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7030 }
7031
7032 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7033 {
7034         return (1 << dpll->n) << 16 | dpll->m2;
7035 }
7036
7037 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7038 {
7039         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7040 }
7041
7042 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7043                                      struct intel_crtc_state *crtc_state,
7044                                      struct dpll *reduced_clock)
7045 {
7046         struct drm_device *dev = crtc->base.dev;
7047         u32 fp, fp2 = 0;
7048
7049         if (IS_PINEVIEW(dev)) {
7050                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7051                 if (reduced_clock)
7052                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7053         } else {
7054                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7055                 if (reduced_clock)
7056                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7057         }
7058
7059         crtc_state->dpll_hw_state.fp0 = fp;
7060
7061         crtc->lowfreq_avail = false;
7062         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7063             reduced_clock) {
7064                 crtc_state->dpll_hw_state.fp1 = fp2;
7065                 crtc->lowfreq_avail = true;
7066         } else {
7067                 crtc_state->dpll_hw_state.fp1 = fp;
7068         }
7069 }
7070
7071 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7072                 pipe)
7073 {
7074         u32 reg_val;
7075
7076         /*
7077          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7078          * and set it to a reasonable value instead.
7079          */
7080         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7081         reg_val &= 0xffffff00;
7082         reg_val |= 0x00000030;
7083         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7084
7085         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7086         reg_val &= 0x8cffffff;
7087         reg_val = 0x8c000000;
7088         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7089
7090         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7091         reg_val &= 0xffffff00;
7092         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7093
7094         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7095         reg_val &= 0x00ffffff;
7096         reg_val |= 0xb0000000;
7097         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7098 }
7099
7100 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7101                                          struct intel_link_m_n *m_n)
7102 {
7103         struct drm_device *dev = crtc->base.dev;
7104         struct drm_i915_private *dev_priv = dev->dev_private;
7105         int pipe = crtc->pipe;
7106
7107         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7108         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7109         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7110         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7111 }
7112
7113 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7114                                          struct intel_link_m_n *m_n,
7115                                          struct intel_link_m_n *m2_n2)
7116 {
7117         struct drm_device *dev = crtc->base.dev;
7118         struct drm_i915_private *dev_priv = dev->dev_private;
7119         int pipe = crtc->pipe;
7120         enum transcoder transcoder = crtc->config->cpu_transcoder;
7121
7122         if (INTEL_INFO(dev)->gen >= 5) {
7123                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7124                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7125                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7126                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7127                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7128                  * for gen < 8) and if DRRS is supported (to make sure the
7129                  * registers are not unnecessarily accessed).
7130                  */
7131                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7132                         crtc->config->has_drrs) {
7133                         I915_WRITE(PIPE_DATA_M2(transcoder),
7134                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7135                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7136                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7137                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7138                 }
7139         } else {
7140                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7141                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7142                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7143                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7144         }
7145 }
7146
7147 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7148 {
7149         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7150
7151         if (m_n == M1_N1) {
7152                 dp_m_n = &crtc->config->dp_m_n;
7153                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7154         } else if (m_n == M2_N2) {
7155
7156                 /*
7157                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7158                  * needs to be programmed into M1_N1.
7159                  */
7160                 dp_m_n = &crtc->config->dp_m2_n2;
7161         } else {
7162                 DRM_ERROR("Unsupported divider value\n");
7163                 return;
7164         }
7165
7166         if (crtc->config->has_pch_encoder)
7167                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7168         else
7169                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7170 }
7171
7172 static void vlv_compute_dpll(struct intel_crtc *crtc,
7173                              struct intel_crtc_state *pipe_config)
7174 {
7175         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7176                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7177         if (crtc->pipe != PIPE_A)
7178                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7179
7180         /* DPLL not used with DSI, but still need the rest set up */
7181         if (!pipe_config->has_dsi_encoder)
7182                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7183                         DPLL_EXT_BUFFER_ENABLE_VLV;
7184
7185         pipe_config->dpll_hw_state.dpll_md =
7186                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7187 }
7188
7189 static void chv_compute_dpll(struct intel_crtc *crtc,
7190                              struct intel_crtc_state *pipe_config)
7191 {
7192         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7193                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7194         if (crtc->pipe != PIPE_A)
7195                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7196
7197         /* DPLL not used with DSI, but still need the rest set up */
7198         if (!pipe_config->has_dsi_encoder)
7199                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7200
7201         pipe_config->dpll_hw_state.dpll_md =
7202                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7203 }
7204
7205 static void vlv_prepare_pll(struct intel_crtc *crtc,
7206                             const struct intel_crtc_state *pipe_config)
7207 {
7208         struct drm_device *dev = crtc->base.dev;
7209         struct drm_i915_private *dev_priv = dev->dev_private;
7210         enum pipe pipe = crtc->pipe;
7211         u32 mdiv;
7212         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7213         u32 coreclk, reg_val;
7214
7215         /* Enable Refclk */
7216         I915_WRITE(DPLL(pipe),
7217                    pipe_config->dpll_hw_state.dpll &
7218                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7219
7220         /* No need to actually set up the DPLL with DSI */
7221         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7222                 return;
7223
7224         mutex_lock(&dev_priv->sb_lock);
7225
7226         bestn = pipe_config->dpll.n;
7227         bestm1 = pipe_config->dpll.m1;
7228         bestm2 = pipe_config->dpll.m2;
7229         bestp1 = pipe_config->dpll.p1;
7230         bestp2 = pipe_config->dpll.p2;
7231
7232         /* See eDP HDMI DPIO driver vbios notes doc */
7233
7234         /* PLL B needs special handling */
7235         if (pipe == PIPE_B)
7236                 vlv_pllb_recal_opamp(dev_priv, pipe);
7237
7238         /* Set up Tx target for periodic Rcomp update */
7239         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7240
7241         /* Disable target IRef on PLL */
7242         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7243         reg_val &= 0x00ffffff;
7244         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7245
7246         /* Disable fast lock */
7247         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7248
7249         /* Set idtafcrecal before PLL is enabled */
7250         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7251         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7252         mdiv |= ((bestn << DPIO_N_SHIFT));
7253         mdiv |= (1 << DPIO_K_SHIFT);
7254
7255         /*
7256          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7257          * but we don't support that).
7258          * Note: don't use the DAC post divider as it seems unstable.
7259          */
7260         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7261         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7262
7263         mdiv |= DPIO_ENABLE_CALIBRATION;
7264         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7265
7266         /* Set HBR and RBR LPF coefficients */
7267         if (pipe_config->port_clock == 162000 ||
7268             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7269             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7270                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7271                                  0x009f0003);
7272         else
7273                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7274                                  0x00d0000f);
7275
7276         if (pipe_config->has_dp_encoder) {
7277                 /* Use SSC source */
7278                 if (pipe == PIPE_A)
7279                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7280                                          0x0df40000);
7281                 else
7282                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7283                                          0x0df70000);
7284         } else { /* HDMI or VGA */
7285                 /* Use bend source */
7286                 if (pipe == PIPE_A)
7287                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7288                                          0x0df70000);
7289                 else
7290                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7291                                          0x0df40000);
7292         }
7293
7294         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7295         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7296         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7297             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7298                 coreclk |= 0x01000000;
7299         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7300
7301         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7302         mutex_unlock(&dev_priv->sb_lock);
7303 }
7304
7305 static void chv_prepare_pll(struct intel_crtc *crtc,
7306                             const struct intel_crtc_state *pipe_config)
7307 {
7308         struct drm_device *dev = crtc->base.dev;
7309         struct drm_i915_private *dev_priv = dev->dev_private;
7310         enum pipe pipe = crtc->pipe;
7311         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7312         u32 loopfilter, tribuf_calcntr;
7313         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7314         u32 dpio_val;
7315         int vco;
7316
7317         /* Enable Refclk and SSC */
7318         I915_WRITE(DPLL(pipe),
7319                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7320
7321         /* No need to actually set up the DPLL with DSI */
7322         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7323                 return;
7324
7325         bestn = pipe_config->dpll.n;
7326         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7327         bestm1 = pipe_config->dpll.m1;
7328         bestm2 = pipe_config->dpll.m2 >> 22;
7329         bestp1 = pipe_config->dpll.p1;
7330         bestp2 = pipe_config->dpll.p2;
7331         vco = pipe_config->dpll.vco;
7332         dpio_val = 0;
7333         loopfilter = 0;
7334
7335         mutex_lock(&dev_priv->sb_lock);
7336
7337         /* p1 and p2 divider */
7338         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7339                         5 << DPIO_CHV_S1_DIV_SHIFT |
7340                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7341                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7342                         1 << DPIO_CHV_K_DIV_SHIFT);
7343
7344         /* Feedback post-divider - m2 */
7345         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7346
7347         /* Feedback refclk divider - n and m1 */
7348         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7349                         DPIO_CHV_M1_DIV_BY_2 |
7350                         1 << DPIO_CHV_N_DIV_SHIFT);
7351
7352         /* M2 fraction division */
7353         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7354
7355         /* M2 fraction division enable */
7356         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7357         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7358         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7359         if (bestm2_frac)
7360                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7361         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7362
7363         /* Program digital lock detect threshold */
7364         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7365         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7366                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7367         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7368         if (!bestm2_frac)
7369                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7370         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7371
7372         /* Loop filter */
7373         if (vco == 5400000) {
7374                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7375                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7376                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7377                 tribuf_calcntr = 0x9;
7378         } else if (vco <= 6200000) {
7379                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7380                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7381                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7382                 tribuf_calcntr = 0x9;
7383         } else if (vco <= 6480000) {
7384                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7385                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7386                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7387                 tribuf_calcntr = 0x8;
7388         } else {
7389                 /* Not supported. Apply the same limits as in the max case */
7390                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7391                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7392                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7393                 tribuf_calcntr = 0;
7394         }
7395         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7396
7397         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7398         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7399         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7400         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7401
7402         /* AFC Recal */
7403         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7404                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7405                         DPIO_AFC_RECAL);
7406
7407         mutex_unlock(&dev_priv->sb_lock);
7408 }
7409
7410 /**
7411  * vlv_force_pll_on - forcibly enable just the PLL
7412  * @dev_priv: i915 private structure
7413  * @pipe: pipe PLL to enable
7414  * @dpll: PLL configuration
7415  *
7416  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7417  * in cases where we need the PLL enabled even when @pipe is not going to
7418  * be enabled.
7419  */
7420 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7421                      const struct dpll *dpll)
7422 {
7423         struct intel_crtc *crtc =
7424                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7425         struct intel_crtc_state *pipe_config;
7426
7427         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7428         if (!pipe_config)
7429                 return -ENOMEM;
7430
7431         pipe_config->base.crtc = &crtc->base;
7432         pipe_config->pixel_multiplier = 1;
7433         pipe_config->dpll = *dpll;
7434
7435         if (IS_CHERRYVIEW(dev)) {
7436                 chv_compute_dpll(crtc, pipe_config);
7437                 chv_prepare_pll(crtc, pipe_config);
7438                 chv_enable_pll(crtc, pipe_config);
7439         } else {
7440                 vlv_compute_dpll(crtc, pipe_config);
7441                 vlv_prepare_pll(crtc, pipe_config);
7442                 vlv_enable_pll(crtc, pipe_config);
7443         }
7444
7445         kfree(pipe_config);
7446
7447         return 0;
7448 }
7449
7450 /**
7451  * vlv_force_pll_off - forcibly disable just the PLL
7452  * @dev_priv: i915 private structure
7453  * @pipe: pipe PLL to disable
7454  *
7455  * Disable the PLL for @pipe. To be used in cases where we need
7456  * the PLL enabled even when @pipe is not going to be enabled.
7457  */
7458 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7459 {
7460         if (IS_CHERRYVIEW(dev))
7461                 chv_disable_pll(to_i915(dev), pipe);
7462         else
7463                 vlv_disable_pll(to_i915(dev), pipe);
7464 }
7465
7466 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7467                               struct intel_crtc_state *crtc_state,
7468                               struct dpll *reduced_clock)
7469 {
7470         struct drm_device *dev = crtc->base.dev;
7471         struct drm_i915_private *dev_priv = dev->dev_private;
7472         u32 dpll;
7473         bool is_sdvo;
7474         struct dpll *clock = &crtc_state->dpll;
7475
7476         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7477
7478         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7479                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7480
7481         dpll = DPLL_VGA_MODE_DIS;
7482
7483         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7484                 dpll |= DPLLB_MODE_LVDS;
7485         else
7486                 dpll |= DPLLB_MODE_DAC_SERIAL;
7487
7488         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7489                 dpll |= (crtc_state->pixel_multiplier - 1)
7490                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7491         }
7492
7493         if (is_sdvo)
7494                 dpll |= DPLL_SDVO_HIGH_SPEED;
7495
7496         if (crtc_state->has_dp_encoder)
7497                 dpll |= DPLL_SDVO_HIGH_SPEED;
7498
7499         /* compute bitmask from p1 value */
7500         if (IS_PINEVIEW(dev))
7501                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7502         else {
7503                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7504                 if (IS_G4X(dev) && reduced_clock)
7505                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7506         }
7507         switch (clock->p2) {
7508         case 5:
7509                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7510                 break;
7511         case 7:
7512                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7513                 break;
7514         case 10:
7515                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7516                 break;
7517         case 14:
7518                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7519                 break;
7520         }
7521         if (INTEL_INFO(dev)->gen >= 4)
7522                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7523
7524         if (crtc_state->sdvo_tv_clock)
7525                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7526         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7527                  intel_panel_use_ssc(dev_priv))
7528                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7529         else
7530                 dpll |= PLL_REF_INPUT_DREFCLK;
7531
7532         dpll |= DPLL_VCO_ENABLE;
7533         crtc_state->dpll_hw_state.dpll = dpll;
7534
7535         if (INTEL_INFO(dev)->gen >= 4) {
7536                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7537                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7538                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7539         }
7540 }
7541
7542 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7543                               struct intel_crtc_state *crtc_state,
7544                               struct dpll *reduced_clock)
7545 {
7546         struct drm_device *dev = crtc->base.dev;
7547         struct drm_i915_private *dev_priv = dev->dev_private;
7548         u32 dpll;
7549         struct dpll *clock = &crtc_state->dpll;
7550
7551         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7552
7553         dpll = DPLL_VGA_MODE_DIS;
7554
7555         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7556                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7557         } else {
7558                 if (clock->p1 == 2)
7559                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7560                 else
7561                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7562                 if (clock->p2 == 4)
7563                         dpll |= PLL_P2_DIVIDE_BY_4;
7564         }
7565
7566         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7567                 dpll |= DPLL_DVO_2X_MODE;
7568
7569         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7570             intel_panel_use_ssc(dev_priv))
7571                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7572         else
7573                 dpll |= PLL_REF_INPUT_DREFCLK;
7574
7575         dpll |= DPLL_VCO_ENABLE;
7576         crtc_state->dpll_hw_state.dpll = dpll;
7577 }
7578
7579 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7580 {
7581         struct drm_device *dev = intel_crtc->base.dev;
7582         struct drm_i915_private *dev_priv = dev->dev_private;
7583         enum pipe pipe = intel_crtc->pipe;
7584         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7585         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7586         uint32_t crtc_vtotal, crtc_vblank_end;
7587         int vsyncshift = 0;
7588
7589         /* We need to be careful not to changed the adjusted mode, for otherwise
7590          * the hw state checker will get angry at the mismatch. */
7591         crtc_vtotal = adjusted_mode->crtc_vtotal;
7592         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7593
7594         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7595                 /* the chip adds 2 halflines automatically */
7596                 crtc_vtotal -= 1;
7597                 crtc_vblank_end -= 1;
7598
7599                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7600                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7601                 else
7602                         vsyncshift = adjusted_mode->crtc_hsync_start -
7603                                 adjusted_mode->crtc_htotal / 2;
7604                 if (vsyncshift < 0)
7605                         vsyncshift += adjusted_mode->crtc_htotal;
7606         }
7607
7608         if (INTEL_INFO(dev)->gen > 3)
7609                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7610
7611         I915_WRITE(HTOTAL(cpu_transcoder),
7612                    (adjusted_mode->crtc_hdisplay - 1) |
7613                    ((adjusted_mode->crtc_htotal - 1) << 16));
7614         I915_WRITE(HBLANK(cpu_transcoder),
7615                    (adjusted_mode->crtc_hblank_start - 1) |
7616                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7617         I915_WRITE(HSYNC(cpu_transcoder),
7618                    (adjusted_mode->crtc_hsync_start - 1) |
7619                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7620
7621         I915_WRITE(VTOTAL(cpu_transcoder),
7622                    (adjusted_mode->crtc_vdisplay - 1) |
7623                    ((crtc_vtotal - 1) << 16));
7624         I915_WRITE(VBLANK(cpu_transcoder),
7625                    (adjusted_mode->crtc_vblank_start - 1) |
7626                    ((crtc_vblank_end - 1) << 16));
7627         I915_WRITE(VSYNC(cpu_transcoder),
7628                    (adjusted_mode->crtc_vsync_start - 1) |
7629                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7630
7631         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7632          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7633          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7634          * bits. */
7635         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7636             (pipe == PIPE_B || pipe == PIPE_C))
7637                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7638
7639 }
7640
7641 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7642 {
7643         struct drm_device *dev = intel_crtc->base.dev;
7644         struct drm_i915_private *dev_priv = dev->dev_private;
7645         enum pipe pipe = intel_crtc->pipe;
7646
7647         /* pipesrc controls the size that is scaled from, which should
7648          * always be the user's requested size.
7649          */
7650         I915_WRITE(PIPESRC(pipe),
7651                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7652                    (intel_crtc->config->pipe_src_h - 1));
7653 }
7654
7655 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7656                                    struct intel_crtc_state *pipe_config)
7657 {
7658         struct drm_device *dev = crtc->base.dev;
7659         struct drm_i915_private *dev_priv = dev->dev_private;
7660         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7661         uint32_t tmp;
7662
7663         tmp = I915_READ(HTOTAL(cpu_transcoder));
7664         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7665         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7666         tmp = I915_READ(HBLANK(cpu_transcoder));
7667         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7668         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7669         tmp = I915_READ(HSYNC(cpu_transcoder));
7670         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7671         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7672
7673         tmp = I915_READ(VTOTAL(cpu_transcoder));
7674         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7675         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7676         tmp = I915_READ(VBLANK(cpu_transcoder));
7677         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7678         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7679         tmp = I915_READ(VSYNC(cpu_transcoder));
7680         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7681         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7682
7683         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7684                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7685                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7686                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7687         }
7688 }
7689
7690 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7691                                     struct intel_crtc_state *pipe_config)
7692 {
7693         struct drm_device *dev = crtc->base.dev;
7694         struct drm_i915_private *dev_priv = dev->dev_private;
7695         u32 tmp;
7696
7697         tmp = I915_READ(PIPESRC(crtc->pipe));
7698         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7699         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7700
7701         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7702         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7703 }
7704
7705 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7706                                  struct intel_crtc_state *pipe_config)
7707 {
7708         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7709         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7710         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7711         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7712
7713         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7714         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7715         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7716         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7717
7718         mode->flags = pipe_config->base.adjusted_mode.flags;
7719         mode->type = DRM_MODE_TYPE_DRIVER;
7720
7721         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7722         mode->flags |= pipe_config->base.adjusted_mode.flags;
7723
7724         mode->hsync = drm_mode_hsync(mode);
7725         mode->vrefresh = drm_mode_vrefresh(mode);
7726         drm_mode_set_name(mode);
7727 }
7728
7729 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7730 {
7731         struct drm_device *dev = intel_crtc->base.dev;
7732         struct drm_i915_private *dev_priv = dev->dev_private;
7733         uint32_t pipeconf;
7734
7735         pipeconf = 0;
7736
7737         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7738             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7739                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7740
7741         if (intel_crtc->config->double_wide)
7742                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7743
7744         /* only g4x and later have fancy bpc/dither controls */
7745         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7746                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7747                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7748                         pipeconf |= PIPECONF_DITHER_EN |
7749                                     PIPECONF_DITHER_TYPE_SP;
7750
7751                 switch (intel_crtc->config->pipe_bpp) {
7752                 case 18:
7753                         pipeconf |= PIPECONF_6BPC;
7754                         break;
7755                 case 24:
7756                         pipeconf |= PIPECONF_8BPC;
7757                         break;
7758                 case 30:
7759                         pipeconf |= PIPECONF_10BPC;
7760                         break;
7761                 default:
7762                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7763                         BUG();
7764                 }
7765         }
7766
7767         if (HAS_PIPE_CXSR(dev)) {
7768                 if (intel_crtc->lowfreq_avail) {
7769                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7770                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7771                 } else {
7772                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7773                 }
7774         }
7775
7776         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7777                 if (INTEL_INFO(dev)->gen < 4 ||
7778                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7779                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7780                 else
7781                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7782         } else
7783                 pipeconf |= PIPECONF_PROGRESSIVE;
7784
7785         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7786              intel_crtc->config->limited_color_range)
7787                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7788
7789         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7790         POSTING_READ(PIPECONF(intel_crtc->pipe));
7791 }
7792
7793 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7794                                    struct intel_crtc_state *crtc_state)
7795 {
7796         struct drm_device *dev = crtc->base.dev;
7797         struct drm_i915_private *dev_priv = dev->dev_private;
7798         const struct intel_limit *limit;
7799         int refclk = 48000;
7800
7801         memset(&crtc_state->dpll_hw_state, 0,
7802                sizeof(crtc_state->dpll_hw_state));
7803
7804         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7805                 if (intel_panel_use_ssc(dev_priv)) {
7806                         refclk = dev_priv->vbt.lvds_ssc_freq;
7807                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7808                 }
7809
7810                 limit = &intel_limits_i8xx_lvds;
7811         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO)) {
7812                 limit = &intel_limits_i8xx_dvo;
7813         } else {
7814                 limit = &intel_limits_i8xx_dac;
7815         }
7816
7817         if (!crtc_state->clock_set &&
7818             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7819                                  refclk, NULL, &crtc_state->dpll)) {
7820                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7821                 return -EINVAL;
7822         }
7823
7824         i8xx_compute_dpll(crtc, crtc_state, NULL);
7825
7826         return 0;
7827 }
7828
7829 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7830                                   struct intel_crtc_state *crtc_state)
7831 {
7832         struct drm_device *dev = crtc->base.dev;
7833         struct drm_i915_private *dev_priv = dev->dev_private;
7834         const struct intel_limit *limit;
7835         int refclk = 96000;
7836
7837         memset(&crtc_state->dpll_hw_state, 0,
7838                sizeof(crtc_state->dpll_hw_state));
7839
7840         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7841                 if (intel_panel_use_ssc(dev_priv)) {
7842                         refclk = dev_priv->vbt.lvds_ssc_freq;
7843                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7844                 }
7845
7846                 if (intel_is_dual_link_lvds(dev))
7847                         limit = &intel_limits_g4x_dual_channel_lvds;
7848                 else
7849                         limit = &intel_limits_g4x_single_channel_lvds;
7850         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7851                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7852                 limit = &intel_limits_g4x_hdmi;
7853         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7854                 limit = &intel_limits_g4x_sdvo;
7855         } else {
7856                 /* The option is for other outputs */
7857                 limit = &intel_limits_i9xx_sdvo;
7858         }
7859
7860         if (!crtc_state->clock_set &&
7861             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7862                                 refclk, NULL, &crtc_state->dpll)) {
7863                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7864                 return -EINVAL;
7865         }
7866
7867         i9xx_compute_dpll(crtc, crtc_state, NULL);
7868
7869         return 0;
7870 }
7871
7872 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7873                                   struct intel_crtc_state *crtc_state)
7874 {
7875         struct drm_device *dev = crtc->base.dev;
7876         struct drm_i915_private *dev_priv = dev->dev_private;
7877         const struct intel_limit *limit;
7878         int refclk = 96000;
7879
7880         memset(&crtc_state->dpll_hw_state, 0,
7881                sizeof(crtc_state->dpll_hw_state));
7882
7883         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7884                 if (intel_panel_use_ssc(dev_priv)) {
7885                         refclk = dev_priv->vbt.lvds_ssc_freq;
7886                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7887                 }
7888
7889                 limit = &intel_limits_pineview_lvds;
7890         } else {
7891                 limit = &intel_limits_pineview_sdvo;
7892         }
7893
7894         if (!crtc_state->clock_set &&
7895             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7896                                 refclk, NULL, &crtc_state->dpll)) {
7897                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7898                 return -EINVAL;
7899         }
7900
7901         i9xx_compute_dpll(crtc, crtc_state, NULL);
7902
7903         return 0;
7904 }
7905
7906 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7907                                    struct intel_crtc_state *crtc_state)
7908 {
7909         struct drm_device *dev = crtc->base.dev;
7910         struct drm_i915_private *dev_priv = dev->dev_private;
7911         const struct intel_limit *limit;
7912         int refclk = 96000;
7913
7914         memset(&crtc_state->dpll_hw_state, 0,
7915                sizeof(crtc_state->dpll_hw_state));
7916
7917         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7918                 if (intel_panel_use_ssc(dev_priv)) {
7919                         refclk = dev_priv->vbt.lvds_ssc_freq;
7920                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7921                 }
7922
7923                 limit = &intel_limits_i9xx_lvds;
7924         } else {
7925                 limit = &intel_limits_i9xx_sdvo;
7926         }
7927
7928         if (!crtc_state->clock_set &&
7929             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7930                                  refclk, NULL, &crtc_state->dpll)) {
7931                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7932                 return -EINVAL;
7933         }
7934
7935         i9xx_compute_dpll(crtc, crtc_state, NULL);
7936
7937         return 0;
7938 }
7939
7940 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7941                                   struct intel_crtc_state *crtc_state)
7942 {
7943         int refclk = 100000;
7944         const struct intel_limit *limit = &intel_limits_chv;
7945
7946         memset(&crtc_state->dpll_hw_state, 0,
7947                sizeof(crtc_state->dpll_hw_state));
7948
7949         if (!crtc_state->clock_set &&
7950             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7951                                 refclk, NULL, &crtc_state->dpll)) {
7952                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7953                 return -EINVAL;
7954         }
7955
7956         chv_compute_dpll(crtc, crtc_state);
7957
7958         return 0;
7959 }
7960
7961 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7962                                   struct intel_crtc_state *crtc_state)
7963 {
7964         int refclk = 100000;
7965         const struct intel_limit *limit = &intel_limits_vlv;
7966
7967         memset(&crtc_state->dpll_hw_state, 0,
7968                sizeof(crtc_state->dpll_hw_state));
7969
7970         if (!crtc_state->clock_set &&
7971             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7972                                 refclk, NULL, &crtc_state->dpll)) {
7973                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7974                 return -EINVAL;
7975         }
7976
7977         vlv_compute_dpll(crtc, crtc_state);
7978
7979         return 0;
7980 }
7981
7982 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7983                                  struct intel_crtc_state *pipe_config)
7984 {
7985         struct drm_device *dev = crtc->base.dev;
7986         struct drm_i915_private *dev_priv = dev->dev_private;
7987         uint32_t tmp;
7988
7989         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7990                 return;
7991
7992         tmp = I915_READ(PFIT_CONTROL);
7993         if (!(tmp & PFIT_ENABLE))
7994                 return;
7995
7996         /* Check whether the pfit is attached to our pipe. */
7997         if (INTEL_INFO(dev)->gen < 4) {
7998                 if (crtc->pipe != PIPE_B)
7999                         return;
8000         } else {
8001                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
8002                         return;
8003         }
8004
8005         pipe_config->gmch_pfit.control = tmp;
8006         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
8007 }
8008
8009 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8010                                struct intel_crtc_state *pipe_config)
8011 {
8012         struct drm_device *dev = crtc->base.dev;
8013         struct drm_i915_private *dev_priv = dev->dev_private;
8014         int pipe = pipe_config->cpu_transcoder;
8015         struct dpll clock;
8016         u32 mdiv;
8017         int refclk = 100000;
8018
8019         /* In case of DSI, DPLL will not be used */
8020         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8021                 return;
8022
8023         mutex_lock(&dev_priv->sb_lock);
8024         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8025         mutex_unlock(&dev_priv->sb_lock);
8026
8027         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8028         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8029         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8030         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8031         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8032
8033         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8034 }
8035
8036 static void
8037 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8038                               struct intel_initial_plane_config *plane_config)
8039 {
8040         struct drm_device *dev = crtc->base.dev;
8041         struct drm_i915_private *dev_priv = dev->dev_private;
8042         u32 val, base, offset;
8043         int pipe = crtc->pipe, plane = crtc->plane;
8044         int fourcc, pixel_format;
8045         unsigned int aligned_height;
8046         struct drm_framebuffer *fb;
8047         struct intel_framebuffer *intel_fb;
8048
8049         val = I915_READ(DSPCNTR(plane));
8050         if (!(val & DISPLAY_PLANE_ENABLE))
8051                 return;
8052
8053         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8054         if (!intel_fb) {
8055                 DRM_DEBUG_KMS("failed to alloc fb\n");
8056                 return;
8057         }
8058
8059         fb = &intel_fb->base;
8060
8061         if (INTEL_INFO(dev)->gen >= 4) {
8062                 if (val & DISPPLANE_TILED) {
8063                         plane_config->tiling = I915_TILING_X;
8064                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8065                 }
8066         }
8067
8068         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8069         fourcc = i9xx_format_to_fourcc(pixel_format);
8070         fb->pixel_format = fourcc;
8071         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8072
8073         if (INTEL_INFO(dev)->gen >= 4) {
8074                 if (plane_config->tiling)
8075                         offset = I915_READ(DSPTILEOFF(plane));
8076                 else
8077                         offset = I915_READ(DSPLINOFF(plane));
8078                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8079         } else {
8080                 base = I915_READ(DSPADDR(plane));
8081         }
8082         plane_config->base = base;
8083
8084         val = I915_READ(PIPESRC(pipe));
8085         fb->width = ((val >> 16) & 0xfff) + 1;
8086         fb->height = ((val >> 0) & 0xfff) + 1;
8087
8088         val = I915_READ(DSPSTRIDE(pipe));
8089         fb->pitches[0] = val & 0xffffffc0;
8090
8091         aligned_height = intel_fb_align_height(dev, fb->height,
8092                                                fb->pixel_format,
8093                                                fb->modifier[0]);
8094
8095         plane_config->size = fb->pitches[0] * aligned_height;
8096
8097         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8098                       pipe_name(pipe), plane, fb->width, fb->height,
8099                       fb->bits_per_pixel, base, fb->pitches[0],
8100                       plane_config->size);
8101
8102         plane_config->fb = intel_fb;
8103 }
8104
8105 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8106                                struct intel_crtc_state *pipe_config)
8107 {
8108         struct drm_device *dev = crtc->base.dev;
8109         struct drm_i915_private *dev_priv = dev->dev_private;
8110         int pipe = pipe_config->cpu_transcoder;
8111         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8112         struct dpll clock;
8113         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8114         int refclk = 100000;
8115
8116         /* In case of DSI, DPLL will not be used */
8117         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
8118                 return;
8119
8120         mutex_lock(&dev_priv->sb_lock);
8121         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8122         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8123         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8124         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8125         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8126         mutex_unlock(&dev_priv->sb_lock);
8127
8128         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8129         clock.m2 = (pll_dw0 & 0xff) << 22;
8130         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8131                 clock.m2 |= pll_dw2 & 0x3fffff;
8132         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8133         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8134         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8135
8136         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8137 }
8138
8139 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8140                                  struct intel_crtc_state *pipe_config)
8141 {
8142         struct drm_device *dev = crtc->base.dev;
8143         struct drm_i915_private *dev_priv = dev->dev_private;
8144         enum intel_display_power_domain power_domain;
8145         uint32_t tmp;
8146         bool ret;
8147
8148         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8149         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8150                 return false;
8151
8152         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8153         pipe_config->shared_dpll = NULL;
8154
8155         ret = false;
8156
8157         tmp = I915_READ(PIPECONF(crtc->pipe));
8158         if (!(tmp & PIPECONF_ENABLE))
8159                 goto out;
8160
8161         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8162                 switch (tmp & PIPECONF_BPC_MASK) {
8163                 case PIPECONF_6BPC:
8164                         pipe_config->pipe_bpp = 18;
8165                         break;
8166                 case PIPECONF_8BPC:
8167                         pipe_config->pipe_bpp = 24;
8168                         break;
8169                 case PIPECONF_10BPC:
8170                         pipe_config->pipe_bpp = 30;
8171                         break;
8172                 default:
8173                         break;
8174                 }
8175         }
8176
8177         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8178             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8179                 pipe_config->limited_color_range = true;
8180
8181         if (INTEL_INFO(dev)->gen < 4)
8182                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8183
8184         intel_get_pipe_timings(crtc, pipe_config);
8185         intel_get_pipe_src_size(crtc, pipe_config);
8186
8187         i9xx_get_pfit_config(crtc, pipe_config);
8188
8189         if (INTEL_INFO(dev)->gen >= 4) {
8190                 /* No way to read it out on pipes B and C */
8191                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8192                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8193                 else
8194                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8195                 pipe_config->pixel_multiplier =
8196                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8197                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8198                 pipe_config->dpll_hw_state.dpll_md = tmp;
8199         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8200                 tmp = I915_READ(DPLL(crtc->pipe));
8201                 pipe_config->pixel_multiplier =
8202                         ((tmp & SDVO_MULTIPLIER_MASK)
8203                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8204         } else {
8205                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8206                  * port and will be fixed up in the encoder->get_config
8207                  * function. */
8208                 pipe_config->pixel_multiplier = 1;
8209         }
8210         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8211         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8212                 /*
8213                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8214                  * on 830. Filter it out here so that we don't
8215                  * report errors due to that.
8216                  */
8217                 if (IS_I830(dev))
8218                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8219
8220                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8221                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8222         } else {
8223                 /* Mask out read-only status bits. */
8224                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8225                                                      DPLL_PORTC_READY_MASK |
8226                                                      DPLL_PORTB_READY_MASK);
8227         }
8228
8229         if (IS_CHERRYVIEW(dev))
8230                 chv_crtc_clock_get(crtc, pipe_config);
8231         else if (IS_VALLEYVIEW(dev))
8232                 vlv_crtc_clock_get(crtc, pipe_config);
8233         else
8234                 i9xx_crtc_clock_get(crtc, pipe_config);
8235
8236         /*
8237          * Normally the dotclock is filled in by the encoder .get_config()
8238          * but in case the pipe is enabled w/o any ports we need a sane
8239          * default.
8240          */
8241         pipe_config->base.adjusted_mode.crtc_clock =
8242                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8243
8244         ret = true;
8245
8246 out:
8247         intel_display_power_put(dev_priv, power_domain);
8248
8249         return ret;
8250 }
8251
8252 static void ironlake_init_pch_refclk(struct drm_device *dev)
8253 {
8254         struct drm_i915_private *dev_priv = dev->dev_private;
8255         struct intel_encoder *encoder;
8256         u32 val, final;
8257         bool has_lvds = false;
8258         bool has_cpu_edp = false;
8259         bool has_panel = false;
8260         bool has_ck505 = false;
8261         bool can_ssc = false;
8262
8263         /* We need to take the global config into account */
8264         for_each_intel_encoder(dev, encoder) {
8265                 switch (encoder->type) {
8266                 case INTEL_OUTPUT_LVDS:
8267                         has_panel = true;
8268                         has_lvds = true;
8269                         break;
8270                 case INTEL_OUTPUT_EDP:
8271                         has_panel = true;
8272                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8273                                 has_cpu_edp = true;
8274                         break;
8275                 default:
8276                         break;
8277                 }
8278         }
8279
8280         if (HAS_PCH_IBX(dev)) {
8281                 has_ck505 = dev_priv->vbt.display_clock_mode;
8282                 can_ssc = has_ck505;
8283         } else {
8284                 has_ck505 = false;
8285                 can_ssc = true;
8286         }
8287
8288         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8289                       has_panel, has_lvds, has_ck505);
8290
8291         /* Ironlake: try to setup display ref clock before DPLL
8292          * enabling. This is only under driver's control after
8293          * PCH B stepping, previous chipset stepping should be
8294          * ignoring this setting.
8295          */
8296         val = I915_READ(PCH_DREF_CONTROL);
8297
8298         /* As we must carefully and slowly disable/enable each source in turn,
8299          * compute the final state we want first and check if we need to
8300          * make any changes at all.
8301          */
8302         final = val;
8303         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8304         if (has_ck505)
8305                 final |= DREF_NONSPREAD_CK505_ENABLE;
8306         else
8307                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8308
8309         final &= ~DREF_SSC_SOURCE_MASK;
8310         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8311         final &= ~DREF_SSC1_ENABLE;
8312
8313         if (has_panel) {
8314                 final |= DREF_SSC_SOURCE_ENABLE;
8315
8316                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8317                         final |= DREF_SSC1_ENABLE;
8318
8319                 if (has_cpu_edp) {
8320                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8321                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8322                         else
8323                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8324                 } else
8325                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8326         } else {
8327                 final |= DREF_SSC_SOURCE_DISABLE;
8328                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8329         }
8330
8331         if (final == val)
8332                 return;
8333
8334         /* Always enable nonspread source */
8335         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8336
8337         if (has_ck505)
8338                 val |= DREF_NONSPREAD_CK505_ENABLE;
8339         else
8340                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8341
8342         if (has_panel) {
8343                 val &= ~DREF_SSC_SOURCE_MASK;
8344                 val |= DREF_SSC_SOURCE_ENABLE;
8345
8346                 /* SSC must be turned on before enabling the CPU output  */
8347                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8348                         DRM_DEBUG_KMS("Using SSC on panel\n");
8349                         val |= DREF_SSC1_ENABLE;
8350                 } else
8351                         val &= ~DREF_SSC1_ENABLE;
8352
8353                 /* Get SSC going before enabling the outputs */
8354                 I915_WRITE(PCH_DREF_CONTROL, val);
8355                 POSTING_READ(PCH_DREF_CONTROL);
8356                 udelay(200);
8357
8358                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8359
8360                 /* Enable CPU source on CPU attached eDP */
8361                 if (has_cpu_edp) {
8362                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8363                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8364                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8365                         } else
8366                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8367                 } else
8368                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8369
8370                 I915_WRITE(PCH_DREF_CONTROL, val);
8371                 POSTING_READ(PCH_DREF_CONTROL);
8372                 udelay(200);
8373         } else {
8374                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8375
8376                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8377
8378                 /* Turn off CPU output */
8379                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8380
8381                 I915_WRITE(PCH_DREF_CONTROL, val);
8382                 POSTING_READ(PCH_DREF_CONTROL);
8383                 udelay(200);
8384
8385                 /* Turn off the SSC source */
8386                 val &= ~DREF_SSC_SOURCE_MASK;
8387                 val |= DREF_SSC_SOURCE_DISABLE;
8388
8389                 /* Turn off SSC1 */
8390                 val &= ~DREF_SSC1_ENABLE;
8391
8392                 I915_WRITE(PCH_DREF_CONTROL, val);
8393                 POSTING_READ(PCH_DREF_CONTROL);
8394                 udelay(200);
8395         }
8396
8397         BUG_ON(val != final);
8398 }
8399
8400 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8401 {
8402         uint32_t tmp;
8403
8404         tmp = I915_READ(SOUTH_CHICKEN2);
8405         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8406         I915_WRITE(SOUTH_CHICKEN2, tmp);
8407
8408         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8409                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8410                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8411
8412         tmp = I915_READ(SOUTH_CHICKEN2);
8413         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8414         I915_WRITE(SOUTH_CHICKEN2, tmp);
8415
8416         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8417                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8418                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8419 }
8420
8421 /* WaMPhyProgramming:hsw */
8422 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8423 {
8424         uint32_t tmp;
8425
8426         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8427         tmp &= ~(0xFF << 24);
8428         tmp |= (0x12 << 24);
8429         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8430
8431         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8432         tmp |= (1 << 11);
8433         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8434
8435         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8436         tmp |= (1 << 11);
8437         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8438
8439         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8440         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8441         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8442
8443         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8444         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8445         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8446
8447         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8448         tmp &= ~(7 << 13);
8449         tmp |= (5 << 13);
8450         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8451
8452         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8453         tmp &= ~(7 << 13);
8454         tmp |= (5 << 13);
8455         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8456
8457         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8458         tmp &= ~0xFF;
8459         tmp |= 0x1C;
8460         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8461
8462         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8463         tmp &= ~0xFF;
8464         tmp |= 0x1C;
8465         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8466
8467         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8468         tmp &= ~(0xFF << 16);
8469         tmp |= (0x1C << 16);
8470         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8471
8472         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8473         tmp &= ~(0xFF << 16);
8474         tmp |= (0x1C << 16);
8475         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8476
8477         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8478         tmp |= (1 << 27);
8479         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8480
8481         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8482         tmp |= (1 << 27);
8483         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8484
8485         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8486         tmp &= ~(0xF << 28);
8487         tmp |= (4 << 28);
8488         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8489
8490         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8491         tmp &= ~(0xF << 28);
8492         tmp |= (4 << 28);
8493         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8494 }
8495
8496 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8497  * Programming" based on the parameters passed:
8498  * - Sequence to enable CLKOUT_DP
8499  * - Sequence to enable CLKOUT_DP without spread
8500  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8501  */
8502 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8503                                  bool with_fdi)
8504 {
8505         struct drm_i915_private *dev_priv = dev->dev_private;
8506         uint32_t reg, tmp;
8507
8508         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8509                 with_spread = true;
8510         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8511                 with_fdi = false;
8512
8513         mutex_lock(&dev_priv->sb_lock);
8514
8515         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8516         tmp &= ~SBI_SSCCTL_DISABLE;
8517         tmp |= SBI_SSCCTL_PATHALT;
8518         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8519
8520         udelay(24);
8521
8522         if (with_spread) {
8523                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8524                 tmp &= ~SBI_SSCCTL_PATHALT;
8525                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8526
8527                 if (with_fdi) {
8528                         lpt_reset_fdi_mphy(dev_priv);
8529                         lpt_program_fdi_mphy(dev_priv);
8530                 }
8531         }
8532
8533         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8534         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8535         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8536         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8537
8538         mutex_unlock(&dev_priv->sb_lock);
8539 }
8540
8541 /* Sequence to disable CLKOUT_DP */
8542 static void lpt_disable_clkout_dp(struct drm_device *dev)
8543 {
8544         struct drm_i915_private *dev_priv = dev->dev_private;
8545         uint32_t reg, tmp;
8546
8547         mutex_lock(&dev_priv->sb_lock);
8548
8549         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8550         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8551         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8552         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8553
8554         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8555         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8556                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8557                         tmp |= SBI_SSCCTL_PATHALT;
8558                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8559                         udelay(32);
8560                 }
8561                 tmp |= SBI_SSCCTL_DISABLE;
8562                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8563         }
8564
8565         mutex_unlock(&dev_priv->sb_lock);
8566 }
8567
8568 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8569
8570 static const uint16_t sscdivintphase[] = {
8571         [BEND_IDX( 50)] = 0x3B23,
8572         [BEND_IDX( 45)] = 0x3B23,
8573         [BEND_IDX( 40)] = 0x3C23,
8574         [BEND_IDX( 35)] = 0x3C23,
8575         [BEND_IDX( 30)] = 0x3D23,
8576         [BEND_IDX( 25)] = 0x3D23,
8577         [BEND_IDX( 20)] = 0x3E23,
8578         [BEND_IDX( 15)] = 0x3E23,
8579         [BEND_IDX( 10)] = 0x3F23,
8580         [BEND_IDX(  5)] = 0x3F23,
8581         [BEND_IDX(  0)] = 0x0025,
8582         [BEND_IDX( -5)] = 0x0025,
8583         [BEND_IDX(-10)] = 0x0125,
8584         [BEND_IDX(-15)] = 0x0125,
8585         [BEND_IDX(-20)] = 0x0225,
8586         [BEND_IDX(-25)] = 0x0225,
8587         [BEND_IDX(-30)] = 0x0325,
8588         [BEND_IDX(-35)] = 0x0325,
8589         [BEND_IDX(-40)] = 0x0425,
8590         [BEND_IDX(-45)] = 0x0425,
8591         [BEND_IDX(-50)] = 0x0525,
8592 };
8593
8594 /*
8595  * Bend CLKOUT_DP
8596  * steps -50 to 50 inclusive, in steps of 5
8597  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8598  * change in clock period = -(steps / 10) * 5.787 ps
8599  */
8600 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8601 {
8602         uint32_t tmp;
8603         int idx = BEND_IDX(steps);
8604
8605         if (WARN_ON(steps % 5 != 0))
8606                 return;
8607
8608         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8609                 return;
8610
8611         mutex_lock(&dev_priv->sb_lock);
8612
8613         if (steps % 10 != 0)
8614                 tmp = 0xAAAAAAAB;
8615         else
8616                 tmp = 0x00000000;
8617         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8618
8619         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8620         tmp &= 0xffff0000;
8621         tmp |= sscdivintphase[idx];
8622         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8623
8624         mutex_unlock(&dev_priv->sb_lock);
8625 }
8626
8627 #undef BEND_IDX
8628
8629 static void lpt_init_pch_refclk(struct drm_device *dev)
8630 {
8631         struct intel_encoder *encoder;
8632         bool has_vga = false;
8633
8634         for_each_intel_encoder(dev, encoder) {
8635                 switch (encoder->type) {
8636                 case INTEL_OUTPUT_ANALOG:
8637                         has_vga = true;
8638                         break;
8639                 default:
8640                         break;
8641                 }
8642         }
8643
8644         if (has_vga) {
8645                 lpt_bend_clkout_dp(to_i915(dev), 0);
8646                 lpt_enable_clkout_dp(dev, true, true);
8647         } else {
8648                 lpt_disable_clkout_dp(dev);
8649         }
8650 }
8651
8652 /*
8653  * Initialize reference clocks when the driver loads
8654  */
8655 void intel_init_pch_refclk(struct drm_device *dev)
8656 {
8657         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8658                 ironlake_init_pch_refclk(dev);
8659         else if (HAS_PCH_LPT(dev))
8660                 lpt_init_pch_refclk(dev);
8661 }
8662
8663 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8664 {
8665         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8666         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8667         int pipe = intel_crtc->pipe;
8668         uint32_t val;
8669
8670         val = 0;
8671
8672         switch (intel_crtc->config->pipe_bpp) {
8673         case 18:
8674                 val |= PIPECONF_6BPC;
8675                 break;
8676         case 24:
8677                 val |= PIPECONF_8BPC;
8678                 break;
8679         case 30:
8680                 val |= PIPECONF_10BPC;
8681                 break;
8682         case 36:
8683                 val |= PIPECONF_12BPC;
8684                 break;
8685         default:
8686                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8687                 BUG();
8688         }
8689
8690         if (intel_crtc->config->dither)
8691                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8692
8693         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8694                 val |= PIPECONF_INTERLACED_ILK;
8695         else
8696                 val |= PIPECONF_PROGRESSIVE;
8697
8698         if (intel_crtc->config->limited_color_range)
8699                 val |= PIPECONF_COLOR_RANGE_SELECT;
8700
8701         I915_WRITE(PIPECONF(pipe), val);
8702         POSTING_READ(PIPECONF(pipe));
8703 }
8704
8705 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8706 {
8707         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8708         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8709         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8710         u32 val = 0;
8711
8712         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8713                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8714
8715         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8716                 val |= PIPECONF_INTERLACED_ILK;
8717         else
8718                 val |= PIPECONF_PROGRESSIVE;
8719
8720         I915_WRITE(PIPECONF(cpu_transcoder), val);
8721         POSTING_READ(PIPECONF(cpu_transcoder));
8722 }
8723
8724 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8725 {
8726         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8727         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8728
8729         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8730                 u32 val = 0;
8731
8732                 switch (intel_crtc->config->pipe_bpp) {
8733                 case 18:
8734                         val |= PIPEMISC_DITHER_6_BPC;
8735                         break;
8736                 case 24:
8737                         val |= PIPEMISC_DITHER_8_BPC;
8738                         break;
8739                 case 30:
8740                         val |= PIPEMISC_DITHER_10_BPC;
8741                         break;
8742                 case 36:
8743                         val |= PIPEMISC_DITHER_12_BPC;
8744                         break;
8745                 default:
8746                         /* Case prevented by pipe_config_set_bpp. */
8747                         BUG();
8748                 }
8749
8750                 if (intel_crtc->config->dither)
8751                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8752
8753                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8754         }
8755 }
8756
8757 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8758 {
8759         /*
8760          * Account for spread spectrum to avoid
8761          * oversubscribing the link. Max center spread
8762          * is 2.5%; use 5% for safety's sake.
8763          */
8764         u32 bps = target_clock * bpp * 21 / 20;
8765         return DIV_ROUND_UP(bps, link_bw * 8);
8766 }
8767
8768 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8769 {
8770         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8771 }
8772
8773 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8774                                   struct intel_crtc_state *crtc_state,
8775                                   struct dpll *reduced_clock)
8776 {
8777         struct drm_crtc *crtc = &intel_crtc->base;
8778         struct drm_device *dev = crtc->dev;
8779         struct drm_i915_private *dev_priv = dev->dev_private;
8780         struct drm_atomic_state *state = crtc_state->base.state;
8781         struct drm_connector *connector;
8782         struct drm_connector_state *connector_state;
8783         struct intel_encoder *encoder;
8784         u32 dpll, fp, fp2;
8785         int factor, i;
8786         bool is_lvds = false, is_sdvo = false;
8787
8788         for_each_connector_in_state(state, connector, connector_state, i) {
8789                 if (connector_state->crtc != crtc_state->base.crtc)
8790                         continue;
8791
8792                 encoder = to_intel_encoder(connector_state->best_encoder);
8793
8794                 switch (encoder->type) {
8795                 case INTEL_OUTPUT_LVDS:
8796                         is_lvds = true;
8797                         break;
8798                 case INTEL_OUTPUT_SDVO:
8799                 case INTEL_OUTPUT_HDMI:
8800                         is_sdvo = true;
8801                         break;
8802                 default:
8803                         break;
8804                 }
8805         }
8806
8807         /* Enable autotuning of the PLL clock (if permissible) */
8808         factor = 21;
8809         if (is_lvds) {
8810                 if ((intel_panel_use_ssc(dev_priv) &&
8811                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8812                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8813                         factor = 25;
8814         } else if (crtc_state->sdvo_tv_clock)
8815                 factor = 20;
8816
8817         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8818
8819         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8820                 fp |= FP_CB_TUNE;
8821
8822         if (reduced_clock) {
8823                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8824
8825                 if (reduced_clock->m < factor * reduced_clock->n)
8826                         fp2 |= FP_CB_TUNE;
8827         } else {
8828                 fp2 = fp;
8829         }
8830
8831         dpll = 0;
8832
8833         if (is_lvds)
8834                 dpll |= DPLLB_MODE_LVDS;
8835         else
8836                 dpll |= DPLLB_MODE_DAC_SERIAL;
8837
8838         dpll |= (crtc_state->pixel_multiplier - 1)
8839                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8840
8841         if (is_sdvo)
8842                 dpll |= DPLL_SDVO_HIGH_SPEED;
8843         if (crtc_state->has_dp_encoder)
8844                 dpll |= DPLL_SDVO_HIGH_SPEED;
8845
8846         /* compute bitmask from p1 value */
8847         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8848         /* also FPA1 */
8849         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8850
8851         switch (crtc_state->dpll.p2) {
8852         case 5:
8853                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8854                 break;
8855         case 7:
8856                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8857                 break;
8858         case 10:
8859                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8860                 break;
8861         case 14:
8862                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8863                 break;
8864         }
8865
8866         if (is_lvds && intel_panel_use_ssc(dev_priv))
8867                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8868         else
8869                 dpll |= PLL_REF_INPUT_DREFCLK;
8870
8871         dpll |= DPLL_VCO_ENABLE;
8872
8873         crtc_state->dpll_hw_state.dpll = dpll;
8874         crtc_state->dpll_hw_state.fp0 = fp;
8875         crtc_state->dpll_hw_state.fp1 = fp2;
8876 }
8877
8878 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8879                                        struct intel_crtc_state *crtc_state)
8880 {
8881         struct drm_device *dev = crtc->base.dev;
8882         struct drm_i915_private *dev_priv = dev->dev_private;
8883         struct dpll reduced_clock;
8884         bool has_reduced_clock = false;
8885         struct intel_shared_dpll *pll;
8886         const struct intel_limit *limit;
8887         int refclk = 120000;
8888
8889         memset(&crtc_state->dpll_hw_state, 0,
8890                sizeof(crtc_state->dpll_hw_state));
8891
8892         crtc->lowfreq_avail = false;
8893
8894         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8895         if (!crtc_state->has_pch_encoder)
8896                 return 0;
8897
8898         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8899                 if (intel_panel_use_ssc(dev_priv)) {
8900                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8901                                       dev_priv->vbt.lvds_ssc_freq);
8902                         refclk = dev_priv->vbt.lvds_ssc_freq;
8903                 }
8904
8905                 if (intel_is_dual_link_lvds(dev)) {
8906                         if (refclk == 100000)
8907                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8908                         else
8909                                 limit = &intel_limits_ironlake_dual_lvds;
8910                 } else {
8911                         if (refclk == 100000)
8912                                 limit = &intel_limits_ironlake_single_lvds_100m;
8913                         else
8914                                 limit = &intel_limits_ironlake_single_lvds;
8915                 }
8916         } else {
8917                 limit = &intel_limits_ironlake_dac;
8918         }
8919
8920         if (!crtc_state->clock_set &&
8921             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8922                                 refclk, NULL, &crtc_state->dpll)) {
8923                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8924                 return -EINVAL;
8925         }
8926
8927         ironlake_compute_dpll(crtc, crtc_state,
8928                               has_reduced_clock ? &reduced_clock : NULL);
8929
8930         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
8931         if (pll == NULL) {
8932                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8933                                  pipe_name(crtc->pipe));
8934                 return -EINVAL;
8935         }
8936
8937         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8938             has_reduced_clock)
8939                 crtc->lowfreq_avail = true;
8940
8941         return 0;
8942 }
8943
8944 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8945                                          struct intel_link_m_n *m_n)
8946 {
8947         struct drm_device *dev = crtc->base.dev;
8948         struct drm_i915_private *dev_priv = dev->dev_private;
8949         enum pipe pipe = crtc->pipe;
8950
8951         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8952         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8953         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8954                 & ~TU_SIZE_MASK;
8955         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8956         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8957                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8958 }
8959
8960 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8961                                          enum transcoder transcoder,
8962                                          struct intel_link_m_n *m_n,
8963                                          struct intel_link_m_n *m2_n2)
8964 {
8965         struct drm_device *dev = crtc->base.dev;
8966         struct drm_i915_private *dev_priv = dev->dev_private;
8967         enum pipe pipe = crtc->pipe;
8968
8969         if (INTEL_INFO(dev)->gen >= 5) {
8970                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8971                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8972                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8973                         & ~TU_SIZE_MASK;
8974                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8975                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8976                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8977                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8978                  * gen < 8) and if DRRS is supported (to make sure the
8979                  * registers are not unnecessarily read).
8980                  */
8981                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8982                         crtc->config->has_drrs) {
8983                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8984                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8985                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8986                                         & ~TU_SIZE_MASK;
8987                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8988                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8989                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8990                 }
8991         } else {
8992                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8993                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8994                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8995                         & ~TU_SIZE_MASK;
8996                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8997                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8998                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8999         }
9000 }
9001
9002 void intel_dp_get_m_n(struct intel_crtc *crtc,
9003                       struct intel_crtc_state *pipe_config)
9004 {
9005         if (pipe_config->has_pch_encoder)
9006                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9007         else
9008                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9009                                              &pipe_config->dp_m_n,
9010                                              &pipe_config->dp_m2_n2);
9011 }
9012
9013 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9014                                         struct intel_crtc_state *pipe_config)
9015 {
9016         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9017                                      &pipe_config->fdi_m_n, NULL);
9018 }
9019
9020 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9021                                     struct intel_crtc_state *pipe_config)
9022 {
9023         struct drm_device *dev = crtc->base.dev;
9024         struct drm_i915_private *dev_priv = dev->dev_private;
9025         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9026         uint32_t ps_ctrl = 0;
9027         int id = -1;
9028         int i;
9029
9030         /* find scaler attached to this pipe */
9031         for (i = 0; i < crtc->num_scalers; i++) {
9032                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9033                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9034                         id = i;
9035                         pipe_config->pch_pfit.enabled = true;
9036                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9037                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9038                         break;
9039                 }
9040         }
9041
9042         scaler_state->scaler_id = id;
9043         if (id >= 0) {
9044                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9045         } else {
9046                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9047         }
9048 }
9049
9050 static void
9051 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9052                                  struct intel_initial_plane_config *plane_config)
9053 {
9054         struct drm_device *dev = crtc->base.dev;
9055         struct drm_i915_private *dev_priv = dev->dev_private;
9056         u32 val, base, offset, stride_mult, tiling;
9057         int pipe = crtc->pipe;
9058         int fourcc, pixel_format;
9059         unsigned int aligned_height;
9060         struct drm_framebuffer *fb;
9061         struct intel_framebuffer *intel_fb;
9062
9063         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9064         if (!intel_fb) {
9065                 DRM_DEBUG_KMS("failed to alloc fb\n");
9066                 return;
9067         }
9068
9069         fb = &intel_fb->base;
9070
9071         val = I915_READ(PLANE_CTL(pipe, 0));
9072         if (!(val & PLANE_CTL_ENABLE))
9073                 goto error;
9074
9075         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9076         fourcc = skl_format_to_fourcc(pixel_format,
9077                                       val & PLANE_CTL_ORDER_RGBX,
9078                                       val & PLANE_CTL_ALPHA_MASK);
9079         fb->pixel_format = fourcc;
9080         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9081
9082         tiling = val & PLANE_CTL_TILED_MASK;
9083         switch (tiling) {
9084         case PLANE_CTL_TILED_LINEAR:
9085                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9086                 break;
9087         case PLANE_CTL_TILED_X:
9088                 plane_config->tiling = I915_TILING_X;
9089                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9090                 break;
9091         case PLANE_CTL_TILED_Y:
9092                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9093                 break;
9094         case PLANE_CTL_TILED_YF:
9095                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9096                 break;
9097         default:
9098                 MISSING_CASE(tiling);
9099                 goto error;
9100         }
9101
9102         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9103         plane_config->base = base;
9104
9105         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9106
9107         val = I915_READ(PLANE_SIZE(pipe, 0));
9108         fb->height = ((val >> 16) & 0xfff) + 1;
9109         fb->width = ((val >> 0) & 0x1fff) + 1;
9110
9111         val = I915_READ(PLANE_STRIDE(pipe, 0));
9112         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9113                                                 fb->pixel_format);
9114         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9115
9116         aligned_height = intel_fb_align_height(dev, fb->height,
9117                                                fb->pixel_format,
9118                                                fb->modifier[0]);
9119
9120         plane_config->size = fb->pitches[0] * aligned_height;
9121
9122         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9123                       pipe_name(pipe), fb->width, fb->height,
9124                       fb->bits_per_pixel, base, fb->pitches[0],
9125                       plane_config->size);
9126
9127         plane_config->fb = intel_fb;
9128         return;
9129
9130 error:
9131         kfree(fb);
9132 }
9133
9134 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9135                                      struct intel_crtc_state *pipe_config)
9136 {
9137         struct drm_device *dev = crtc->base.dev;
9138         struct drm_i915_private *dev_priv = dev->dev_private;
9139         uint32_t tmp;
9140
9141         tmp = I915_READ(PF_CTL(crtc->pipe));
9142
9143         if (tmp & PF_ENABLE) {
9144                 pipe_config->pch_pfit.enabled = true;
9145                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9146                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9147
9148                 /* We currently do not free assignements of panel fitters on
9149                  * ivb/hsw (since we don't use the higher upscaling modes which
9150                  * differentiates them) so just WARN about this case for now. */
9151                 if (IS_GEN7(dev)) {
9152                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9153                                 PF_PIPE_SEL_IVB(crtc->pipe));
9154                 }
9155         }
9156 }
9157
9158 static void
9159 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9160                                   struct intel_initial_plane_config *plane_config)
9161 {
9162         struct drm_device *dev = crtc->base.dev;
9163         struct drm_i915_private *dev_priv = dev->dev_private;
9164         u32 val, base, offset;
9165         int pipe = crtc->pipe;
9166         int fourcc, pixel_format;
9167         unsigned int aligned_height;
9168         struct drm_framebuffer *fb;
9169         struct intel_framebuffer *intel_fb;
9170
9171         val = I915_READ(DSPCNTR(pipe));
9172         if (!(val & DISPLAY_PLANE_ENABLE))
9173                 return;
9174
9175         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9176         if (!intel_fb) {
9177                 DRM_DEBUG_KMS("failed to alloc fb\n");
9178                 return;
9179         }
9180
9181         fb = &intel_fb->base;
9182
9183         if (INTEL_INFO(dev)->gen >= 4) {
9184                 if (val & DISPPLANE_TILED) {
9185                         plane_config->tiling = I915_TILING_X;
9186                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9187                 }
9188         }
9189
9190         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9191         fourcc = i9xx_format_to_fourcc(pixel_format);
9192         fb->pixel_format = fourcc;
9193         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9194
9195         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9196         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9197                 offset = I915_READ(DSPOFFSET(pipe));
9198         } else {
9199                 if (plane_config->tiling)
9200                         offset = I915_READ(DSPTILEOFF(pipe));
9201                 else
9202                         offset = I915_READ(DSPLINOFF(pipe));
9203         }
9204         plane_config->base = base;
9205
9206         val = I915_READ(PIPESRC(pipe));
9207         fb->width = ((val >> 16) & 0xfff) + 1;
9208         fb->height = ((val >> 0) & 0xfff) + 1;
9209
9210         val = I915_READ(DSPSTRIDE(pipe));
9211         fb->pitches[0] = val & 0xffffffc0;
9212
9213         aligned_height = intel_fb_align_height(dev, fb->height,
9214                                                fb->pixel_format,
9215                                                fb->modifier[0]);
9216
9217         plane_config->size = fb->pitches[0] * aligned_height;
9218
9219         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9220                       pipe_name(pipe), fb->width, fb->height,
9221                       fb->bits_per_pixel, base, fb->pitches[0],
9222                       plane_config->size);
9223
9224         plane_config->fb = intel_fb;
9225 }
9226
9227 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9228                                      struct intel_crtc_state *pipe_config)
9229 {
9230         struct drm_device *dev = crtc->base.dev;
9231         struct drm_i915_private *dev_priv = dev->dev_private;
9232         enum intel_display_power_domain power_domain;
9233         uint32_t tmp;
9234         bool ret;
9235
9236         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9237         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9238                 return false;
9239
9240         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9241         pipe_config->shared_dpll = NULL;
9242
9243         ret = false;
9244         tmp = I915_READ(PIPECONF(crtc->pipe));
9245         if (!(tmp & PIPECONF_ENABLE))
9246                 goto out;
9247
9248         switch (tmp & PIPECONF_BPC_MASK) {
9249         case PIPECONF_6BPC:
9250                 pipe_config->pipe_bpp = 18;
9251                 break;
9252         case PIPECONF_8BPC:
9253                 pipe_config->pipe_bpp = 24;
9254                 break;
9255         case PIPECONF_10BPC:
9256                 pipe_config->pipe_bpp = 30;
9257                 break;
9258         case PIPECONF_12BPC:
9259                 pipe_config->pipe_bpp = 36;
9260                 break;
9261         default:
9262                 break;
9263         }
9264
9265         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9266                 pipe_config->limited_color_range = true;
9267
9268         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9269                 struct intel_shared_dpll *pll;
9270                 enum intel_dpll_id pll_id;
9271
9272                 pipe_config->has_pch_encoder = true;
9273
9274                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9275                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9276                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9277
9278                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9279
9280                 if (HAS_PCH_IBX(dev_priv)) {
9281                         /*
9282                          * The pipe->pch transcoder and pch transcoder->pll
9283                          * mapping is fixed.
9284                          */
9285                         pll_id = (enum intel_dpll_id) crtc->pipe;
9286                 } else {
9287                         tmp = I915_READ(PCH_DPLL_SEL);
9288                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9289                                 pll_id = DPLL_ID_PCH_PLL_B;
9290                         else
9291                                 pll_id= DPLL_ID_PCH_PLL_A;
9292                 }
9293
9294                 pipe_config->shared_dpll =
9295                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9296                 pll = pipe_config->shared_dpll;
9297
9298                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9299                                                  &pipe_config->dpll_hw_state));
9300
9301                 tmp = pipe_config->dpll_hw_state.dpll;
9302                 pipe_config->pixel_multiplier =
9303                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9304                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9305
9306                 ironlake_pch_clock_get(crtc, pipe_config);
9307         } else {
9308                 pipe_config->pixel_multiplier = 1;
9309         }
9310
9311         intel_get_pipe_timings(crtc, pipe_config);
9312         intel_get_pipe_src_size(crtc, pipe_config);
9313
9314         ironlake_get_pfit_config(crtc, pipe_config);
9315
9316         ret = true;
9317
9318 out:
9319         intel_display_power_put(dev_priv, power_domain);
9320
9321         return ret;
9322 }
9323
9324 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9325 {
9326         struct drm_device *dev = dev_priv->dev;
9327         struct intel_crtc *crtc;
9328
9329         for_each_intel_crtc(dev, crtc)
9330                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9331                      pipe_name(crtc->pipe));
9332
9333         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9334         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9335         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9336         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9337         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9338         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9339              "CPU PWM1 enabled\n");
9340         if (IS_HASWELL(dev))
9341                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9342                      "CPU PWM2 enabled\n");
9343         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9344              "PCH PWM1 enabled\n");
9345         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9346              "Utility pin enabled\n");
9347         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9348
9349         /*
9350          * In theory we can still leave IRQs enabled, as long as only the HPD
9351          * interrupts remain enabled. We used to check for that, but since it's
9352          * gen-specific and since we only disable LCPLL after we fully disable
9353          * the interrupts, the check below should be enough.
9354          */
9355         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9356 }
9357
9358 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9359 {
9360         struct drm_device *dev = dev_priv->dev;
9361
9362         if (IS_HASWELL(dev))
9363                 return I915_READ(D_COMP_HSW);
9364         else
9365                 return I915_READ(D_COMP_BDW);
9366 }
9367
9368 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9369 {
9370         struct drm_device *dev = dev_priv->dev;
9371
9372         if (IS_HASWELL(dev)) {
9373                 mutex_lock(&dev_priv->rps.hw_lock);
9374                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9375                                             val))
9376                         DRM_ERROR("Failed to write to D_COMP\n");
9377                 mutex_unlock(&dev_priv->rps.hw_lock);
9378         } else {
9379                 I915_WRITE(D_COMP_BDW, val);
9380                 POSTING_READ(D_COMP_BDW);
9381         }
9382 }
9383
9384 /*
9385  * This function implements pieces of two sequences from BSpec:
9386  * - Sequence for display software to disable LCPLL
9387  * - Sequence for display software to allow package C8+
9388  * The steps implemented here are just the steps that actually touch the LCPLL
9389  * register. Callers should take care of disabling all the display engine
9390  * functions, doing the mode unset, fixing interrupts, etc.
9391  */
9392 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9393                               bool switch_to_fclk, bool allow_power_down)
9394 {
9395         uint32_t val;
9396
9397         assert_can_disable_lcpll(dev_priv);
9398
9399         val = I915_READ(LCPLL_CTL);
9400
9401         if (switch_to_fclk) {
9402                 val |= LCPLL_CD_SOURCE_FCLK;
9403                 I915_WRITE(LCPLL_CTL, val);
9404
9405                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9406                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9407                         DRM_ERROR("Switching to FCLK failed\n");
9408
9409                 val = I915_READ(LCPLL_CTL);
9410         }
9411
9412         val |= LCPLL_PLL_DISABLE;
9413         I915_WRITE(LCPLL_CTL, val);
9414         POSTING_READ(LCPLL_CTL);
9415
9416         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9417                 DRM_ERROR("LCPLL still locked\n");
9418
9419         val = hsw_read_dcomp(dev_priv);
9420         val |= D_COMP_COMP_DISABLE;
9421         hsw_write_dcomp(dev_priv, val);
9422         ndelay(100);
9423
9424         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9425                      1))
9426                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9427
9428         if (allow_power_down) {
9429                 val = I915_READ(LCPLL_CTL);
9430                 val |= LCPLL_POWER_DOWN_ALLOW;
9431                 I915_WRITE(LCPLL_CTL, val);
9432                 POSTING_READ(LCPLL_CTL);
9433         }
9434 }
9435
9436 /*
9437  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9438  * source.
9439  */
9440 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9441 {
9442         uint32_t val;
9443
9444         val = I915_READ(LCPLL_CTL);
9445
9446         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9447                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9448                 return;
9449
9450         /*
9451          * Make sure we're not on PC8 state before disabling PC8, otherwise
9452          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9453          */
9454         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9455
9456         if (val & LCPLL_POWER_DOWN_ALLOW) {
9457                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9458                 I915_WRITE(LCPLL_CTL, val);
9459                 POSTING_READ(LCPLL_CTL);
9460         }
9461
9462         val = hsw_read_dcomp(dev_priv);
9463         val |= D_COMP_COMP_FORCE;
9464         val &= ~D_COMP_COMP_DISABLE;
9465         hsw_write_dcomp(dev_priv, val);
9466
9467         val = I915_READ(LCPLL_CTL);
9468         val &= ~LCPLL_PLL_DISABLE;
9469         I915_WRITE(LCPLL_CTL, val);
9470
9471         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9472                 DRM_ERROR("LCPLL not locked yet\n");
9473
9474         if (val & LCPLL_CD_SOURCE_FCLK) {
9475                 val = I915_READ(LCPLL_CTL);
9476                 val &= ~LCPLL_CD_SOURCE_FCLK;
9477                 I915_WRITE(LCPLL_CTL, val);
9478
9479                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9480                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9481                         DRM_ERROR("Switching back to LCPLL failed\n");
9482         }
9483
9484         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9485         intel_update_cdclk(dev_priv->dev);
9486 }
9487
9488 /*
9489  * Package states C8 and deeper are really deep PC states that can only be
9490  * reached when all the devices on the system allow it, so even if the graphics
9491  * device allows PC8+, it doesn't mean the system will actually get to these
9492  * states. Our driver only allows PC8+ when going into runtime PM.
9493  *
9494  * The requirements for PC8+ are that all the outputs are disabled, the power
9495  * well is disabled and most interrupts are disabled, and these are also
9496  * requirements for runtime PM. When these conditions are met, we manually do
9497  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9498  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9499  * hang the machine.
9500  *
9501  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9502  * the state of some registers, so when we come back from PC8+ we need to
9503  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9504  * need to take care of the registers kept by RC6. Notice that this happens even
9505  * if we don't put the device in PCI D3 state (which is what currently happens
9506  * because of the runtime PM support).
9507  *
9508  * For more, read "Display Sequences for Package C8" on the hardware
9509  * documentation.
9510  */
9511 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9512 {
9513         struct drm_device *dev = dev_priv->dev;
9514         uint32_t val;
9515
9516         DRM_DEBUG_KMS("Enabling package C8+\n");
9517
9518         if (HAS_PCH_LPT_LP(dev)) {
9519                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9520                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9521                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9522         }
9523
9524         lpt_disable_clkout_dp(dev);
9525         hsw_disable_lcpll(dev_priv, true, true);
9526 }
9527
9528 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9529 {
9530         struct drm_device *dev = dev_priv->dev;
9531         uint32_t val;
9532
9533         DRM_DEBUG_KMS("Disabling package C8+\n");
9534
9535         hsw_restore_lcpll(dev_priv);
9536         lpt_init_pch_refclk(dev);
9537
9538         if (HAS_PCH_LPT_LP(dev)) {
9539                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9540                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9541                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9542         }
9543 }
9544
9545 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9546 {
9547         struct drm_device *dev = old_state->dev;
9548         struct intel_atomic_state *old_intel_state =
9549                 to_intel_atomic_state(old_state);
9550         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9551
9552         broxton_set_cdclk(to_i915(dev), req_cdclk);
9553 }
9554
9555 /* compute the max rate for new configuration */
9556 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9557 {
9558         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9559         struct drm_i915_private *dev_priv = state->dev->dev_private;
9560         struct drm_crtc *crtc;
9561         struct drm_crtc_state *cstate;
9562         struct intel_crtc_state *crtc_state;
9563         unsigned max_pixel_rate = 0, i;
9564         enum pipe pipe;
9565
9566         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9567                sizeof(intel_state->min_pixclk));
9568
9569         for_each_crtc_in_state(state, crtc, cstate, i) {
9570                 int pixel_rate;
9571
9572                 crtc_state = to_intel_crtc_state(cstate);
9573                 if (!crtc_state->base.enable) {
9574                         intel_state->min_pixclk[i] = 0;
9575                         continue;
9576                 }
9577
9578                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9579
9580                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9581                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9582                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9583
9584                 intel_state->min_pixclk[i] = pixel_rate;
9585         }
9586
9587         for_each_pipe(dev_priv, pipe)
9588                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9589
9590         return max_pixel_rate;
9591 }
9592
9593 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9594 {
9595         struct drm_i915_private *dev_priv = dev->dev_private;
9596         uint32_t val, data;
9597         int ret;
9598
9599         if (WARN((I915_READ(LCPLL_CTL) &
9600                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9601                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9602                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9603                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9604                  "trying to change cdclk frequency with cdclk not enabled\n"))
9605                 return;
9606
9607         mutex_lock(&dev_priv->rps.hw_lock);
9608         ret = sandybridge_pcode_write(dev_priv,
9609                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9610         mutex_unlock(&dev_priv->rps.hw_lock);
9611         if (ret) {
9612                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9613                 return;
9614         }
9615
9616         val = I915_READ(LCPLL_CTL);
9617         val |= LCPLL_CD_SOURCE_FCLK;
9618         I915_WRITE(LCPLL_CTL, val);
9619
9620         if (wait_for_us(I915_READ(LCPLL_CTL) &
9621                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9622                 DRM_ERROR("Switching to FCLK failed\n");
9623
9624         val = I915_READ(LCPLL_CTL);
9625         val &= ~LCPLL_CLK_FREQ_MASK;
9626
9627         switch (cdclk) {
9628         case 450000:
9629                 val |= LCPLL_CLK_FREQ_450;
9630                 data = 0;
9631                 break;
9632         case 540000:
9633                 val |= LCPLL_CLK_FREQ_54O_BDW;
9634                 data = 1;
9635                 break;
9636         case 337500:
9637                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9638                 data = 2;
9639                 break;
9640         case 675000:
9641                 val |= LCPLL_CLK_FREQ_675_BDW;
9642                 data = 3;
9643                 break;
9644         default:
9645                 WARN(1, "invalid cdclk frequency\n");
9646                 return;
9647         }
9648
9649         I915_WRITE(LCPLL_CTL, val);
9650
9651         val = I915_READ(LCPLL_CTL);
9652         val &= ~LCPLL_CD_SOURCE_FCLK;
9653         I915_WRITE(LCPLL_CTL, val);
9654
9655         if (wait_for_us((I915_READ(LCPLL_CTL) &
9656                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9657                 DRM_ERROR("Switching back to LCPLL failed\n");
9658
9659         mutex_lock(&dev_priv->rps.hw_lock);
9660         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9661         mutex_unlock(&dev_priv->rps.hw_lock);
9662
9663         I915_WRITE(CDCLK_FREQ, DIV_ROUND_CLOSEST(cdclk, 1000) - 1);
9664
9665         intel_update_cdclk(dev);
9666
9667         WARN(cdclk != dev_priv->cdclk_freq,
9668              "cdclk requested %d kHz but got %d kHz\n",
9669              cdclk, dev_priv->cdclk_freq);
9670 }
9671
9672 static int broadwell_calc_cdclk(int max_pixclk)
9673 {
9674         if (max_pixclk > 540000)
9675                 return 675000;
9676         else if (max_pixclk > 450000)
9677                 return 540000;
9678         else if (max_pixclk > 337500)
9679                 return 450000;
9680         else
9681                 return 337500;
9682 }
9683
9684 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9685 {
9686         struct drm_i915_private *dev_priv = to_i915(state->dev);
9687         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9688         int max_pixclk = ilk_max_pixel_rate(state);
9689         int cdclk;
9690
9691         /*
9692          * FIXME should also account for plane ratio
9693          * once 64bpp pixel formats are supported.
9694          */
9695         cdclk = broadwell_calc_cdclk(max_pixclk);
9696
9697         if (cdclk > dev_priv->max_cdclk_freq) {
9698                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9699                               cdclk, dev_priv->max_cdclk_freq);
9700                 return -EINVAL;
9701         }
9702
9703         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9704         if (!intel_state->active_crtcs)
9705                 intel_state->dev_cdclk = broadwell_calc_cdclk(0);
9706
9707         return 0;
9708 }
9709
9710 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9711 {
9712         struct drm_device *dev = old_state->dev;
9713         struct intel_atomic_state *old_intel_state =
9714                 to_intel_atomic_state(old_state);
9715         unsigned req_cdclk = old_intel_state->dev_cdclk;
9716
9717         broadwell_set_cdclk(dev, req_cdclk);
9718 }
9719
9720 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9721                                       struct intel_crtc_state *crtc_state)
9722 {
9723         struct intel_encoder *intel_encoder =
9724                 intel_ddi_get_crtc_new_encoder(crtc_state);
9725
9726         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9727                 if (!intel_ddi_pll_select(crtc, crtc_state))
9728                         return -EINVAL;
9729         }
9730
9731         crtc->lowfreq_avail = false;
9732
9733         return 0;
9734 }
9735
9736 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9737                                 enum port port,
9738                                 struct intel_crtc_state *pipe_config)
9739 {
9740         enum intel_dpll_id id;
9741
9742         switch (port) {
9743         case PORT_A:
9744                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9745                 id = DPLL_ID_SKL_DPLL0;
9746                 break;
9747         case PORT_B:
9748                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9749                 id = DPLL_ID_SKL_DPLL1;
9750                 break;
9751         case PORT_C:
9752                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9753                 id = DPLL_ID_SKL_DPLL2;
9754                 break;
9755         default:
9756                 DRM_ERROR("Incorrect port type\n");
9757                 return;
9758         }
9759
9760         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9761 }
9762
9763 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9764                                 enum port port,
9765                                 struct intel_crtc_state *pipe_config)
9766 {
9767         enum intel_dpll_id id;
9768         u32 temp;
9769
9770         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9771         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9772
9773         switch (pipe_config->ddi_pll_sel) {
9774         case SKL_DPLL0:
9775                 id = DPLL_ID_SKL_DPLL0;
9776                 break;
9777         case SKL_DPLL1:
9778                 id = DPLL_ID_SKL_DPLL1;
9779                 break;
9780         case SKL_DPLL2:
9781                 id = DPLL_ID_SKL_DPLL2;
9782                 break;
9783         case SKL_DPLL3:
9784                 id = DPLL_ID_SKL_DPLL3;
9785                 break;
9786         default:
9787                 MISSING_CASE(pipe_config->ddi_pll_sel);
9788                 return;
9789         }
9790
9791         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9792 }
9793
9794 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9795                                 enum port port,
9796                                 struct intel_crtc_state *pipe_config)
9797 {
9798         enum intel_dpll_id id;
9799
9800         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9801
9802         switch (pipe_config->ddi_pll_sel) {
9803         case PORT_CLK_SEL_WRPLL1:
9804                 id = DPLL_ID_WRPLL1;
9805                 break;
9806         case PORT_CLK_SEL_WRPLL2:
9807                 id = DPLL_ID_WRPLL2;
9808                 break;
9809         case PORT_CLK_SEL_SPLL:
9810                 id = DPLL_ID_SPLL;
9811                 break;
9812         case PORT_CLK_SEL_LCPLL_810:
9813                 id = DPLL_ID_LCPLL_810;
9814                 break;
9815         case PORT_CLK_SEL_LCPLL_1350:
9816                 id = DPLL_ID_LCPLL_1350;
9817                 break;
9818         case PORT_CLK_SEL_LCPLL_2700:
9819                 id = DPLL_ID_LCPLL_2700;
9820                 break;
9821         default:
9822                 MISSING_CASE(pipe_config->ddi_pll_sel);
9823                 /* fall through */
9824         case PORT_CLK_SEL_NONE:
9825                 return;
9826         }
9827
9828         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9829 }
9830
9831 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9832                                      struct intel_crtc_state *pipe_config,
9833                                      unsigned long *power_domain_mask)
9834 {
9835         struct drm_device *dev = crtc->base.dev;
9836         struct drm_i915_private *dev_priv = dev->dev_private;
9837         enum intel_display_power_domain power_domain;
9838         u32 tmp;
9839
9840         /*
9841          * The pipe->transcoder mapping is fixed with the exception of the eDP
9842          * transcoder handled below.
9843          */
9844         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9845
9846         /*
9847          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9848          * consistency and less surprising code; it's in always on power).
9849          */
9850         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9851         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9852                 enum pipe trans_edp_pipe;
9853                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9854                 default:
9855                         WARN(1, "unknown pipe linked to edp transcoder\n");
9856                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9857                 case TRANS_DDI_EDP_INPUT_A_ON:
9858                         trans_edp_pipe = PIPE_A;
9859                         break;
9860                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9861                         trans_edp_pipe = PIPE_B;
9862                         break;
9863                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9864                         trans_edp_pipe = PIPE_C;
9865                         break;
9866                 }
9867
9868                 if (trans_edp_pipe == crtc->pipe)
9869                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9870         }
9871
9872         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9873         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9874                 return false;
9875         *power_domain_mask |= BIT(power_domain);
9876
9877         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9878
9879         return tmp & PIPECONF_ENABLE;
9880 }
9881
9882 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9883                                          struct intel_crtc_state *pipe_config,
9884                                          unsigned long *power_domain_mask)
9885 {
9886         struct drm_device *dev = crtc->base.dev;
9887         struct drm_i915_private *dev_priv = dev->dev_private;
9888         enum intel_display_power_domain power_domain;
9889         enum port port;
9890         enum transcoder cpu_transcoder;
9891         u32 tmp;
9892
9893         pipe_config->has_dsi_encoder = false;
9894
9895         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9896                 if (port == PORT_A)
9897                         cpu_transcoder = TRANSCODER_DSI_A;
9898                 else
9899                         cpu_transcoder = TRANSCODER_DSI_C;
9900
9901                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9902                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9903                         continue;
9904                 *power_domain_mask |= BIT(power_domain);
9905
9906                 /*
9907                  * The PLL needs to be enabled with a valid divider
9908                  * configuration, otherwise accessing DSI registers will hang
9909                  * the machine. See BSpec North Display Engine
9910                  * registers/MIPI[BXT]. We can break out here early, since we
9911                  * need the same DSI PLL to be enabled for both DSI ports.
9912                  */
9913                 if (!intel_dsi_pll_is_enabled(dev_priv))
9914                         break;
9915
9916                 /* XXX: this works for video mode only */
9917                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9918                 if (!(tmp & DPI_ENABLE))
9919                         continue;
9920
9921                 tmp = I915_READ(MIPI_CTRL(port));
9922                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9923                         continue;
9924
9925                 pipe_config->cpu_transcoder = cpu_transcoder;
9926                 pipe_config->has_dsi_encoder = true;
9927                 break;
9928         }
9929
9930         return pipe_config->has_dsi_encoder;
9931 }
9932
9933 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9934                                        struct intel_crtc_state *pipe_config)
9935 {
9936         struct drm_device *dev = crtc->base.dev;
9937         struct drm_i915_private *dev_priv = dev->dev_private;
9938         struct intel_shared_dpll *pll;
9939         enum port port;
9940         uint32_t tmp;
9941
9942         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9943
9944         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9945
9946         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
9947                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9948         else if (IS_BROXTON(dev))
9949                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9950         else
9951                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9952
9953         pll = pipe_config->shared_dpll;
9954         if (pll) {
9955                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9956                                                  &pipe_config->dpll_hw_state));
9957         }
9958
9959         /*
9960          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9961          * DDI E. So just check whether this pipe is wired to DDI E and whether
9962          * the PCH transcoder is on.
9963          */
9964         if (INTEL_INFO(dev)->gen < 9 &&
9965             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9966                 pipe_config->has_pch_encoder = true;
9967
9968                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9969                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9970                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9971
9972                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9973         }
9974 }
9975
9976 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9977                                     struct intel_crtc_state *pipe_config)
9978 {
9979         struct drm_device *dev = crtc->base.dev;
9980         struct drm_i915_private *dev_priv = dev->dev_private;
9981         enum intel_display_power_domain power_domain;
9982         unsigned long power_domain_mask;
9983         bool active;
9984
9985         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9986         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9987                 return false;
9988         power_domain_mask = BIT(power_domain);
9989
9990         pipe_config->shared_dpll = NULL;
9991
9992         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9993
9994         if (IS_BROXTON(dev_priv)) {
9995                 bxt_get_dsi_transcoder_state(crtc, pipe_config,
9996                                              &power_domain_mask);
9997                 WARN_ON(active && pipe_config->has_dsi_encoder);
9998                 if (pipe_config->has_dsi_encoder)
9999                         active = true;
10000         }
10001
10002         if (!active)
10003                 goto out;
10004
10005         if (!pipe_config->has_dsi_encoder) {
10006                 haswell_get_ddi_port_state(crtc, pipe_config);
10007                 intel_get_pipe_timings(crtc, pipe_config);
10008         }
10009
10010         intel_get_pipe_src_size(crtc, pipe_config);
10011
10012         pipe_config->gamma_mode =
10013                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
10014
10015         if (INTEL_INFO(dev)->gen >= 9) {
10016                 skl_init_scalers(dev, crtc, pipe_config);
10017         }
10018
10019         if (INTEL_INFO(dev)->gen >= 9) {
10020                 pipe_config->scaler_state.scaler_id = -1;
10021                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10022         }
10023
10024         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10025         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10026                 power_domain_mask |= BIT(power_domain);
10027                 if (INTEL_INFO(dev)->gen >= 9)
10028                         skylake_get_pfit_config(crtc, pipe_config);
10029                 else
10030                         ironlake_get_pfit_config(crtc, pipe_config);
10031         }
10032
10033         if (IS_HASWELL(dev))
10034                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10035                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10036
10037         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10038             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10039                 pipe_config->pixel_multiplier =
10040                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10041         } else {
10042                 pipe_config->pixel_multiplier = 1;
10043         }
10044
10045 out:
10046         for_each_power_domain(power_domain, power_domain_mask)
10047                 intel_display_power_put(dev_priv, power_domain);
10048
10049         return active;
10050 }
10051
10052 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10053                                const struct intel_plane_state *plane_state)
10054 {
10055         struct drm_device *dev = crtc->dev;
10056         struct drm_i915_private *dev_priv = dev->dev_private;
10057         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10058         uint32_t cntl = 0, size = 0;
10059
10060         if (plane_state && plane_state->visible) {
10061                 unsigned int width = plane_state->base.crtc_w;
10062                 unsigned int height = plane_state->base.crtc_h;
10063                 unsigned int stride = roundup_pow_of_two(width) * 4;
10064
10065                 switch (stride) {
10066                 default:
10067                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10068                                   width, stride);
10069                         stride = 256;
10070                         /* fallthrough */
10071                 case 256:
10072                 case 512:
10073                 case 1024:
10074                 case 2048:
10075                         break;
10076                 }
10077
10078                 cntl |= CURSOR_ENABLE |
10079                         CURSOR_GAMMA_ENABLE |
10080                         CURSOR_FORMAT_ARGB |
10081                         CURSOR_STRIDE(stride);
10082
10083                 size = (height << 12) | width;
10084         }
10085
10086         if (intel_crtc->cursor_cntl != 0 &&
10087             (intel_crtc->cursor_base != base ||
10088              intel_crtc->cursor_size != size ||
10089              intel_crtc->cursor_cntl != cntl)) {
10090                 /* On these chipsets we can only modify the base/size/stride
10091                  * whilst the cursor is disabled.
10092                  */
10093                 I915_WRITE(CURCNTR(PIPE_A), 0);
10094                 POSTING_READ(CURCNTR(PIPE_A));
10095                 intel_crtc->cursor_cntl = 0;
10096         }
10097
10098         if (intel_crtc->cursor_base != base) {
10099                 I915_WRITE(CURBASE(PIPE_A), base);
10100                 intel_crtc->cursor_base = base;
10101         }
10102
10103         if (intel_crtc->cursor_size != size) {
10104                 I915_WRITE(CURSIZE, size);
10105                 intel_crtc->cursor_size = size;
10106         }
10107
10108         if (intel_crtc->cursor_cntl != cntl) {
10109                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10110                 POSTING_READ(CURCNTR(PIPE_A));
10111                 intel_crtc->cursor_cntl = cntl;
10112         }
10113 }
10114
10115 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10116                                const struct intel_plane_state *plane_state)
10117 {
10118         struct drm_device *dev = crtc->dev;
10119         struct drm_i915_private *dev_priv = dev->dev_private;
10120         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10121         int pipe = intel_crtc->pipe;
10122         uint32_t cntl = 0;
10123
10124         if (plane_state && plane_state->visible) {
10125                 cntl = MCURSOR_GAMMA_ENABLE;
10126                 switch (plane_state->base.crtc_w) {
10127                         case 64:
10128                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10129                                 break;
10130                         case 128:
10131                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10132                                 break;
10133                         case 256:
10134                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10135                                 break;
10136                         default:
10137                                 MISSING_CASE(plane_state->base.crtc_w);
10138                                 return;
10139                 }
10140                 cntl |= pipe << 28; /* Connect to correct pipe */
10141
10142                 if (HAS_DDI(dev))
10143                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10144
10145                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10146                         cntl |= CURSOR_ROTATE_180;
10147         }
10148
10149         if (intel_crtc->cursor_cntl != cntl) {
10150                 I915_WRITE(CURCNTR(pipe), cntl);
10151                 POSTING_READ(CURCNTR(pipe));
10152                 intel_crtc->cursor_cntl = cntl;
10153         }
10154
10155         /* and commit changes on next vblank */
10156         I915_WRITE(CURBASE(pipe), base);
10157         POSTING_READ(CURBASE(pipe));
10158
10159         intel_crtc->cursor_base = base;
10160 }
10161
10162 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10163 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10164                                      const struct intel_plane_state *plane_state)
10165 {
10166         struct drm_device *dev = crtc->dev;
10167         struct drm_i915_private *dev_priv = dev->dev_private;
10168         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10169         int pipe = intel_crtc->pipe;
10170         u32 base = intel_crtc->cursor_addr;
10171         u32 pos = 0;
10172
10173         if (plane_state) {
10174                 int x = plane_state->base.crtc_x;
10175                 int y = plane_state->base.crtc_y;
10176
10177                 if (x < 0) {
10178                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10179                         x = -x;
10180                 }
10181                 pos |= x << CURSOR_X_SHIFT;
10182
10183                 if (y < 0) {
10184                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10185                         y = -y;
10186                 }
10187                 pos |= y << CURSOR_Y_SHIFT;
10188
10189                 /* ILK+ do this automagically */
10190                 if (HAS_GMCH_DISPLAY(dev) &&
10191                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10192                         base += (plane_state->base.crtc_h *
10193                                  plane_state->base.crtc_w - 1) * 4;
10194                 }
10195         }
10196
10197         I915_WRITE(CURPOS(pipe), pos);
10198
10199         if (IS_845G(dev) || IS_I865G(dev))
10200                 i845_update_cursor(crtc, base, plane_state);
10201         else
10202                 i9xx_update_cursor(crtc, base, plane_state);
10203 }
10204
10205 static bool cursor_size_ok(struct drm_device *dev,
10206                            uint32_t width, uint32_t height)
10207 {
10208         if (width == 0 || height == 0)
10209                 return false;
10210
10211         /*
10212          * 845g/865g are special in that they are only limited by
10213          * the width of their cursors, the height is arbitrary up to
10214          * the precision of the register. Everything else requires
10215          * square cursors, limited to a few power-of-two sizes.
10216          */
10217         if (IS_845G(dev) || IS_I865G(dev)) {
10218                 if ((width & 63) != 0)
10219                         return false;
10220
10221                 if (width > (IS_845G(dev) ? 64 : 512))
10222                         return false;
10223
10224                 if (height > 1023)
10225                         return false;
10226         } else {
10227                 switch (width | height) {
10228                 case 256:
10229                 case 128:
10230                         if (IS_GEN2(dev))
10231                                 return false;
10232                 case 64:
10233                         break;
10234                 default:
10235                         return false;
10236                 }
10237         }
10238
10239         return true;
10240 }
10241
10242 /* VESA 640x480x72Hz mode to set on the pipe */
10243 static struct drm_display_mode load_detect_mode = {
10244         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10245                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10246 };
10247
10248 struct drm_framebuffer *
10249 __intel_framebuffer_create(struct drm_device *dev,
10250                            struct drm_mode_fb_cmd2 *mode_cmd,
10251                            struct drm_i915_gem_object *obj)
10252 {
10253         struct intel_framebuffer *intel_fb;
10254         int ret;
10255
10256         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10257         if (!intel_fb)
10258                 return ERR_PTR(-ENOMEM);
10259
10260         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10261         if (ret)
10262                 goto err;
10263
10264         return &intel_fb->base;
10265
10266 err:
10267         kfree(intel_fb);
10268         return ERR_PTR(ret);
10269 }
10270
10271 static struct drm_framebuffer *
10272 intel_framebuffer_create(struct drm_device *dev,
10273                          struct drm_mode_fb_cmd2 *mode_cmd,
10274                          struct drm_i915_gem_object *obj)
10275 {
10276         struct drm_framebuffer *fb;
10277         int ret;
10278
10279         ret = i915_mutex_lock_interruptible(dev);
10280         if (ret)
10281                 return ERR_PTR(ret);
10282         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10283         mutex_unlock(&dev->struct_mutex);
10284
10285         return fb;
10286 }
10287
10288 static u32
10289 intel_framebuffer_pitch_for_width(int width, int bpp)
10290 {
10291         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10292         return ALIGN(pitch, 64);
10293 }
10294
10295 static u32
10296 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10297 {
10298         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10299         return PAGE_ALIGN(pitch * mode->vdisplay);
10300 }
10301
10302 static struct drm_framebuffer *
10303 intel_framebuffer_create_for_mode(struct drm_device *dev,
10304                                   struct drm_display_mode *mode,
10305                                   int depth, int bpp)
10306 {
10307         struct drm_framebuffer *fb;
10308         struct drm_i915_gem_object *obj;
10309         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10310
10311         obj = i915_gem_object_create(dev,
10312                                     intel_framebuffer_size_for_mode(mode, bpp));
10313         if (IS_ERR(obj))
10314                 return ERR_CAST(obj);
10315
10316         mode_cmd.width = mode->hdisplay;
10317         mode_cmd.height = mode->vdisplay;
10318         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10319                                                                 bpp);
10320         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10321
10322         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10323         if (IS_ERR(fb))
10324                 drm_gem_object_unreference_unlocked(&obj->base);
10325
10326         return fb;
10327 }
10328
10329 static struct drm_framebuffer *
10330 mode_fits_in_fbdev(struct drm_device *dev,
10331                    struct drm_display_mode *mode)
10332 {
10333 #ifdef CONFIG_DRM_FBDEV_EMULATION
10334         struct drm_i915_private *dev_priv = dev->dev_private;
10335         struct drm_i915_gem_object *obj;
10336         struct drm_framebuffer *fb;
10337
10338         if (!dev_priv->fbdev)
10339                 return NULL;
10340
10341         if (!dev_priv->fbdev->fb)
10342                 return NULL;
10343
10344         obj = dev_priv->fbdev->fb->obj;
10345         BUG_ON(!obj);
10346
10347         fb = &dev_priv->fbdev->fb->base;
10348         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10349                                                                fb->bits_per_pixel))
10350                 return NULL;
10351
10352         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10353                 return NULL;
10354
10355         drm_framebuffer_reference(fb);
10356         return fb;
10357 #else
10358         return NULL;
10359 #endif
10360 }
10361
10362 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10363                                            struct drm_crtc *crtc,
10364                                            struct drm_display_mode *mode,
10365                                            struct drm_framebuffer *fb,
10366                                            int x, int y)
10367 {
10368         struct drm_plane_state *plane_state;
10369         int hdisplay, vdisplay;
10370         int ret;
10371
10372         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10373         if (IS_ERR(plane_state))
10374                 return PTR_ERR(plane_state);
10375
10376         if (mode)
10377                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10378         else
10379                 hdisplay = vdisplay = 0;
10380
10381         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10382         if (ret)
10383                 return ret;
10384         drm_atomic_set_fb_for_plane(plane_state, fb);
10385         plane_state->crtc_x = 0;
10386         plane_state->crtc_y = 0;
10387         plane_state->crtc_w = hdisplay;
10388         plane_state->crtc_h = vdisplay;
10389         plane_state->src_x = x << 16;
10390         plane_state->src_y = y << 16;
10391         plane_state->src_w = hdisplay << 16;
10392         plane_state->src_h = vdisplay << 16;
10393
10394         return 0;
10395 }
10396
10397 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10398                                 struct drm_display_mode *mode,
10399                                 struct intel_load_detect_pipe *old,
10400                                 struct drm_modeset_acquire_ctx *ctx)
10401 {
10402         struct intel_crtc *intel_crtc;
10403         struct intel_encoder *intel_encoder =
10404                 intel_attached_encoder(connector);
10405         struct drm_crtc *possible_crtc;
10406         struct drm_encoder *encoder = &intel_encoder->base;
10407         struct drm_crtc *crtc = NULL;
10408         struct drm_device *dev = encoder->dev;
10409         struct drm_framebuffer *fb;
10410         struct drm_mode_config *config = &dev->mode_config;
10411         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10412         struct drm_connector_state *connector_state;
10413         struct intel_crtc_state *crtc_state;
10414         int ret, i = -1;
10415
10416         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10417                       connector->base.id, connector->name,
10418                       encoder->base.id, encoder->name);
10419
10420         old->restore_state = NULL;
10421
10422 retry:
10423         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10424         if (ret)
10425                 goto fail;
10426
10427         /*
10428          * Algorithm gets a little messy:
10429          *
10430          *   - if the connector already has an assigned crtc, use it (but make
10431          *     sure it's on first)
10432          *
10433          *   - try to find the first unused crtc that can drive this connector,
10434          *     and use that if we find one
10435          */
10436
10437         /* See if we already have a CRTC for this connector */
10438         if (connector->state->crtc) {
10439                 crtc = connector->state->crtc;
10440
10441                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10442                 if (ret)
10443                         goto fail;
10444
10445                 /* Make sure the crtc and connector are running */
10446                 goto found;
10447         }
10448
10449         /* Find an unused one (if possible) */
10450         for_each_crtc(dev, possible_crtc) {
10451                 i++;
10452                 if (!(encoder->possible_crtcs & (1 << i)))
10453                         continue;
10454
10455                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10456                 if (ret)
10457                         goto fail;
10458
10459                 if (possible_crtc->state->enable) {
10460                         drm_modeset_unlock(&possible_crtc->mutex);
10461                         continue;
10462                 }
10463
10464                 crtc = possible_crtc;
10465                 break;
10466         }
10467
10468         /*
10469          * If we didn't find an unused CRTC, don't use any.
10470          */
10471         if (!crtc) {
10472                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10473                 goto fail;
10474         }
10475
10476 found:
10477         intel_crtc = to_intel_crtc(crtc);
10478
10479         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10480         if (ret)
10481                 goto fail;
10482
10483         state = drm_atomic_state_alloc(dev);
10484         restore_state = drm_atomic_state_alloc(dev);
10485         if (!state || !restore_state) {
10486                 ret = -ENOMEM;
10487                 goto fail;
10488         }
10489
10490         state->acquire_ctx = ctx;
10491         restore_state->acquire_ctx = ctx;
10492
10493         connector_state = drm_atomic_get_connector_state(state, connector);
10494         if (IS_ERR(connector_state)) {
10495                 ret = PTR_ERR(connector_state);
10496                 goto fail;
10497         }
10498
10499         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10500         if (ret)
10501                 goto fail;
10502
10503         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10504         if (IS_ERR(crtc_state)) {
10505                 ret = PTR_ERR(crtc_state);
10506                 goto fail;
10507         }
10508
10509         crtc_state->base.active = crtc_state->base.enable = true;
10510
10511         if (!mode)
10512                 mode = &load_detect_mode;
10513
10514         /* We need a framebuffer large enough to accommodate all accesses
10515          * that the plane may generate whilst we perform load detection.
10516          * We can not rely on the fbcon either being present (we get called
10517          * during its initialisation to detect all boot displays, or it may
10518          * not even exist) or that it is large enough to satisfy the
10519          * requested mode.
10520          */
10521         fb = mode_fits_in_fbdev(dev, mode);
10522         if (fb == NULL) {
10523                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10524                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10525         } else
10526                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10527         if (IS_ERR(fb)) {
10528                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10529                 goto fail;
10530         }
10531
10532         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10533         if (ret)
10534                 goto fail;
10535
10536         drm_framebuffer_unreference(fb);
10537
10538         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10539         if (ret)
10540                 goto fail;
10541
10542         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10543         if (!ret)
10544                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10545         if (!ret)
10546                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10547         if (ret) {
10548                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10549                 goto fail;
10550         }
10551
10552         ret = drm_atomic_commit(state);
10553         if (ret) {
10554                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10555                 goto fail;
10556         }
10557
10558         old->restore_state = restore_state;
10559
10560         /* let the connector get through one full cycle before testing */
10561         intel_wait_for_vblank(dev, intel_crtc->pipe);
10562         return true;
10563
10564 fail:
10565         drm_atomic_state_free(state);
10566         drm_atomic_state_free(restore_state);
10567         restore_state = state = NULL;
10568
10569         if (ret == -EDEADLK) {
10570                 drm_modeset_backoff(ctx);
10571                 goto retry;
10572         }
10573
10574         return false;
10575 }
10576
10577 void intel_release_load_detect_pipe(struct drm_connector *connector,
10578                                     struct intel_load_detect_pipe *old,
10579                                     struct drm_modeset_acquire_ctx *ctx)
10580 {
10581         struct intel_encoder *intel_encoder =
10582                 intel_attached_encoder(connector);
10583         struct drm_encoder *encoder = &intel_encoder->base;
10584         struct drm_atomic_state *state = old->restore_state;
10585         int ret;
10586
10587         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10588                       connector->base.id, connector->name,
10589                       encoder->base.id, encoder->name);
10590
10591         if (!state)
10592                 return;
10593
10594         ret = drm_atomic_commit(state);
10595         if (ret) {
10596                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10597                 drm_atomic_state_free(state);
10598         }
10599 }
10600
10601 static int i9xx_pll_refclk(struct drm_device *dev,
10602                            const struct intel_crtc_state *pipe_config)
10603 {
10604         struct drm_i915_private *dev_priv = dev->dev_private;
10605         u32 dpll = pipe_config->dpll_hw_state.dpll;
10606
10607         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10608                 return dev_priv->vbt.lvds_ssc_freq;
10609         else if (HAS_PCH_SPLIT(dev))
10610                 return 120000;
10611         else if (!IS_GEN2(dev))
10612                 return 96000;
10613         else
10614                 return 48000;
10615 }
10616
10617 /* Returns the clock of the currently programmed mode of the given pipe. */
10618 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10619                                 struct intel_crtc_state *pipe_config)
10620 {
10621         struct drm_device *dev = crtc->base.dev;
10622         struct drm_i915_private *dev_priv = dev->dev_private;
10623         int pipe = pipe_config->cpu_transcoder;
10624         u32 dpll = pipe_config->dpll_hw_state.dpll;
10625         u32 fp;
10626         struct dpll clock;
10627         int port_clock;
10628         int refclk = i9xx_pll_refclk(dev, pipe_config);
10629
10630         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10631                 fp = pipe_config->dpll_hw_state.fp0;
10632         else
10633                 fp = pipe_config->dpll_hw_state.fp1;
10634
10635         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10636         if (IS_PINEVIEW(dev)) {
10637                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10638                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10639         } else {
10640                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10641                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10642         }
10643
10644         if (!IS_GEN2(dev)) {
10645                 if (IS_PINEVIEW(dev))
10646                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10647                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10648                 else
10649                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10650                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10651
10652                 switch (dpll & DPLL_MODE_MASK) {
10653                 case DPLLB_MODE_DAC_SERIAL:
10654                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10655                                 5 : 10;
10656                         break;
10657                 case DPLLB_MODE_LVDS:
10658                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10659                                 7 : 14;
10660                         break;
10661                 default:
10662                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10663                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10664                         return;
10665                 }
10666
10667                 if (IS_PINEVIEW(dev))
10668                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10669                 else
10670                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10671         } else {
10672                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10673                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10674
10675                 if (is_lvds) {
10676                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10677                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10678
10679                         if (lvds & LVDS_CLKB_POWER_UP)
10680                                 clock.p2 = 7;
10681                         else
10682                                 clock.p2 = 14;
10683                 } else {
10684                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10685                                 clock.p1 = 2;
10686                         else {
10687                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10688                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10689                         }
10690                         if (dpll & PLL_P2_DIVIDE_BY_4)
10691                                 clock.p2 = 4;
10692                         else
10693                                 clock.p2 = 2;
10694                 }
10695
10696                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10697         }
10698
10699         /*
10700          * This value includes pixel_multiplier. We will use
10701          * port_clock to compute adjusted_mode.crtc_clock in the
10702          * encoder's get_config() function.
10703          */
10704         pipe_config->port_clock = port_clock;
10705 }
10706
10707 int intel_dotclock_calculate(int link_freq,
10708                              const struct intel_link_m_n *m_n)
10709 {
10710         /*
10711          * The calculation for the data clock is:
10712          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10713          * But we want to avoid losing precison if possible, so:
10714          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10715          *
10716          * and the link clock is simpler:
10717          * link_clock = (m * link_clock) / n
10718          */
10719
10720         if (!m_n->link_n)
10721                 return 0;
10722
10723         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10724 }
10725
10726 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10727                                    struct intel_crtc_state *pipe_config)
10728 {
10729         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10730
10731         /* read out port_clock from the DPLL */
10732         i9xx_crtc_clock_get(crtc, pipe_config);
10733
10734         /*
10735          * In case there is an active pipe without active ports,
10736          * we may need some idea for the dotclock anyway.
10737          * Calculate one based on the FDI configuration.
10738          */
10739         pipe_config->base.adjusted_mode.crtc_clock =
10740                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10741                                          &pipe_config->fdi_m_n);
10742 }
10743
10744 /** Returns the currently programmed mode of the given pipe. */
10745 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10746                                              struct drm_crtc *crtc)
10747 {
10748         struct drm_i915_private *dev_priv = dev->dev_private;
10749         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10750         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10751         struct drm_display_mode *mode;
10752         struct intel_crtc_state *pipe_config;
10753         int htot = I915_READ(HTOTAL(cpu_transcoder));
10754         int hsync = I915_READ(HSYNC(cpu_transcoder));
10755         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10756         int vsync = I915_READ(VSYNC(cpu_transcoder));
10757         enum pipe pipe = intel_crtc->pipe;
10758
10759         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10760         if (!mode)
10761                 return NULL;
10762
10763         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10764         if (!pipe_config) {
10765                 kfree(mode);
10766                 return NULL;
10767         }
10768
10769         /*
10770          * Construct a pipe_config sufficient for getting the clock info
10771          * back out of crtc_clock_get.
10772          *
10773          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10774          * to use a real value here instead.
10775          */
10776         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10777         pipe_config->pixel_multiplier = 1;
10778         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10779         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10780         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10781         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10782
10783         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10784         mode->hdisplay = (htot & 0xffff) + 1;
10785         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10786         mode->hsync_start = (hsync & 0xffff) + 1;
10787         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10788         mode->vdisplay = (vtot & 0xffff) + 1;
10789         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10790         mode->vsync_start = (vsync & 0xffff) + 1;
10791         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10792
10793         drm_mode_set_name(mode);
10794
10795         kfree(pipe_config);
10796
10797         return mode;
10798 }
10799
10800 void intel_mark_busy(struct drm_i915_private *dev_priv)
10801 {
10802         if (dev_priv->mm.busy)
10803                 return;
10804
10805         intel_runtime_pm_get(dev_priv);
10806         i915_update_gfx_val(dev_priv);
10807         if (INTEL_GEN(dev_priv) >= 6)
10808                 gen6_rps_busy(dev_priv);
10809         dev_priv->mm.busy = true;
10810 }
10811
10812 void intel_mark_idle(struct drm_i915_private *dev_priv)
10813 {
10814         if (!dev_priv->mm.busy)
10815                 return;
10816
10817         dev_priv->mm.busy = false;
10818
10819         if (INTEL_GEN(dev_priv) >= 6)
10820                 gen6_rps_idle(dev_priv);
10821
10822         intel_runtime_pm_put(dev_priv);
10823 }
10824
10825 static void intel_crtc_destroy(struct drm_crtc *crtc)
10826 {
10827         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10828         struct drm_device *dev = crtc->dev;
10829         struct intel_unpin_work *work;
10830
10831         spin_lock_irq(&dev->event_lock);
10832         work = intel_crtc->unpin_work;
10833         intel_crtc->unpin_work = NULL;
10834         spin_unlock_irq(&dev->event_lock);
10835
10836         if (work) {
10837                 cancel_work_sync(&work->work);
10838                 kfree(work);
10839         }
10840
10841         drm_crtc_cleanup(crtc);
10842
10843         kfree(intel_crtc);
10844 }
10845
10846 static void intel_unpin_work_fn(struct work_struct *__work)
10847 {
10848         struct intel_unpin_work *work =
10849                 container_of(__work, struct intel_unpin_work, work);
10850         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10851         struct drm_device *dev = crtc->base.dev;
10852         struct drm_plane *primary = crtc->base.primary;
10853
10854         mutex_lock(&dev->struct_mutex);
10855         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
10856         drm_gem_object_unreference(&work->pending_flip_obj->base);
10857
10858         if (work->flip_queued_req)
10859                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10860         mutex_unlock(&dev->struct_mutex);
10861
10862         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10863         intel_fbc_post_update(crtc);
10864         drm_framebuffer_unreference(work->old_fb);
10865
10866         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10867         atomic_dec(&crtc->unpin_work_count);
10868
10869         kfree(work);
10870 }
10871
10872 static void do_intel_finish_page_flip(struct drm_i915_private *dev_priv,
10873                                       struct drm_crtc *crtc)
10874 {
10875         struct drm_device *dev = dev_priv->dev;
10876         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10877         struct intel_unpin_work *work;
10878         unsigned long flags;
10879
10880         /* Ignore early vblank irqs */
10881         if (intel_crtc == NULL)
10882                 return;
10883
10884         /*
10885          * This is called both by irq handlers and the reset code (to complete
10886          * lost pageflips) so needs the full irqsave spinlocks.
10887          */
10888         spin_lock_irqsave(&dev->event_lock, flags);
10889         work = intel_crtc->unpin_work;
10890
10891         if (work && atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE) {
10892                 /* ensure that the unpin work is consistent wrt ->pending. */
10893                 smp_rmb();
10894
10895                 page_flip_completed(intel_crtc);
10896         }
10897
10898         spin_unlock_irqrestore(&dev->event_lock, flags);
10899 }
10900
10901 void intel_finish_page_flip(struct drm_i915_private *dev_priv, int pipe)
10902 {
10903         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10904
10905         do_intel_finish_page_flip(dev_priv, crtc);
10906 }
10907
10908 void intel_finish_page_flip_plane(struct drm_i915_private *dev_priv, int plane)
10909 {
10910         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10911
10912         do_intel_finish_page_flip(dev_priv, crtc);
10913 }
10914
10915 /* Is 'a' after or equal to 'b'? */
10916 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10917 {
10918         return !((a - b) & 0x80000000);
10919 }
10920
10921 static bool page_flip_finished(struct intel_crtc *crtc)
10922 {
10923         struct drm_device *dev = crtc->base.dev;
10924         struct drm_i915_private *dev_priv = dev->dev_private;
10925         unsigned reset_counter;
10926
10927         reset_counter = i915_reset_counter(&dev_priv->gpu_error);
10928         if (crtc->reset_counter != reset_counter)
10929                 return true;
10930
10931         /*
10932          * The relevant registers doen't exist on pre-ctg.
10933          * As the flip done interrupt doesn't trigger for mmio
10934          * flips on gmch platforms, a flip count check isn't
10935          * really needed there. But since ctg has the registers,
10936          * include it in the check anyway.
10937          */
10938         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10939                 return true;
10940
10941         /*
10942          * BDW signals flip done immediately if the plane
10943          * is disabled, even if the plane enable is already
10944          * armed to occur at the next vblank :(
10945          */
10946
10947         /*
10948          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10949          * used the same base address. In that case the mmio flip might
10950          * have completed, but the CS hasn't even executed the flip yet.
10951          *
10952          * A flip count check isn't enough as the CS might have updated
10953          * the base address just after start of vblank, but before we
10954          * managed to process the interrupt. This means we'd complete the
10955          * CS flip too soon.
10956          *
10957          * Combining both checks should get us a good enough result. It may
10958          * still happen that the CS flip has been executed, but has not
10959          * yet actually completed. But in case the base address is the same
10960          * anyway, we don't really care.
10961          */
10962         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10963                 crtc->unpin_work->gtt_offset &&
10964                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10965                                     crtc->unpin_work->flip_count);
10966 }
10967
10968 void intel_prepare_page_flip(struct drm_i915_private *dev_priv, int plane)
10969 {
10970         struct drm_device *dev = dev_priv->dev;
10971         struct intel_crtc *intel_crtc =
10972                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10973         unsigned long flags;
10974
10975
10976         /*
10977          * This is called both by irq handlers and the reset code (to complete
10978          * lost pageflips) so needs the full irqsave spinlocks.
10979          *
10980          * NB: An MMIO update of the plane base pointer will also
10981          * generate a page-flip completion irq, i.e. every modeset
10982          * is also accompanied by a spurious intel_prepare_page_flip().
10983          */
10984         spin_lock_irqsave(&dev->event_lock, flags);
10985         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10986                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10987         spin_unlock_irqrestore(&dev->event_lock, flags);
10988 }
10989
10990 static inline void intel_mark_page_flip_active(struct intel_unpin_work *work)
10991 {
10992         /* Ensure that the work item is consistent when activating it ... */
10993         smp_mb__before_atomic();
10994         atomic_set(&work->pending, INTEL_FLIP_PENDING);
10995 }
10996
10997 static int intel_gen2_queue_flip(struct drm_device *dev,
10998                                  struct drm_crtc *crtc,
10999                                  struct drm_framebuffer *fb,
11000                                  struct drm_i915_gem_object *obj,
11001                                  struct drm_i915_gem_request *req,
11002                                  uint32_t flags)
11003 {
11004         struct intel_engine_cs *engine = req->engine;
11005         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11006         u32 flip_mask;
11007         int ret;
11008
11009         ret = intel_ring_begin(req, 6);
11010         if (ret)
11011                 return ret;
11012
11013         /* Can't queue multiple flips, so wait for the previous
11014          * one to finish before executing the next.
11015          */
11016         if (intel_crtc->plane)
11017                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11018         else
11019                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11020         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11021         intel_ring_emit(engine, MI_NOOP);
11022         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11023                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11024         intel_ring_emit(engine, fb->pitches[0]);
11025         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11026         intel_ring_emit(engine, 0); /* aux display base address, unused */
11027
11028         return 0;
11029 }
11030
11031 static int intel_gen3_queue_flip(struct drm_device *dev,
11032                                  struct drm_crtc *crtc,
11033                                  struct drm_framebuffer *fb,
11034                                  struct drm_i915_gem_object *obj,
11035                                  struct drm_i915_gem_request *req,
11036                                  uint32_t flags)
11037 {
11038         struct intel_engine_cs *engine = req->engine;
11039         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11040         u32 flip_mask;
11041         int ret;
11042
11043         ret = intel_ring_begin(req, 6);
11044         if (ret)
11045                 return ret;
11046
11047         if (intel_crtc->plane)
11048                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11049         else
11050                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11051         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11052         intel_ring_emit(engine, MI_NOOP);
11053         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 |
11054                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11055         intel_ring_emit(engine, fb->pitches[0]);
11056         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11057         intel_ring_emit(engine, MI_NOOP);
11058
11059         return 0;
11060 }
11061
11062 static int intel_gen4_queue_flip(struct drm_device *dev,
11063                                  struct drm_crtc *crtc,
11064                                  struct drm_framebuffer *fb,
11065                                  struct drm_i915_gem_object *obj,
11066                                  struct drm_i915_gem_request *req,
11067                                  uint32_t flags)
11068 {
11069         struct intel_engine_cs *engine = req->engine;
11070         struct drm_i915_private *dev_priv = dev->dev_private;
11071         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11072         uint32_t pf, pipesrc;
11073         int ret;
11074
11075         ret = intel_ring_begin(req, 4);
11076         if (ret)
11077                 return ret;
11078
11079         /* i965+ uses the linear or tiled offsets from the
11080          * Display Registers (which do not change across a page-flip)
11081          * so we need only reprogram the base address.
11082          */
11083         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11084                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11085         intel_ring_emit(engine, fb->pitches[0]);
11086         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset |
11087                         obj->tiling_mode);
11088
11089         /* XXX Enabling the panel-fitter across page-flip is so far
11090          * untested on non-native modes, so ignore it for now.
11091          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11092          */
11093         pf = 0;
11094         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11095         intel_ring_emit(engine, pf | pipesrc);
11096
11097         return 0;
11098 }
11099
11100 static int intel_gen6_queue_flip(struct drm_device *dev,
11101                                  struct drm_crtc *crtc,
11102                                  struct drm_framebuffer *fb,
11103                                  struct drm_i915_gem_object *obj,
11104                                  struct drm_i915_gem_request *req,
11105                                  uint32_t flags)
11106 {
11107         struct intel_engine_cs *engine = req->engine;
11108         struct drm_i915_private *dev_priv = dev->dev_private;
11109         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11110         uint32_t pf, pipesrc;
11111         int ret;
11112
11113         ret = intel_ring_begin(req, 4);
11114         if (ret)
11115                 return ret;
11116
11117         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11118                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11119         intel_ring_emit(engine, fb->pitches[0] | obj->tiling_mode);
11120         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11121
11122         /* Contrary to the suggestions in the documentation,
11123          * "Enable Panel Fitter" does not seem to be required when page
11124          * flipping with a non-native mode, and worse causes a normal
11125          * modeset to fail.
11126          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11127          */
11128         pf = 0;
11129         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11130         intel_ring_emit(engine, pf | pipesrc);
11131
11132         return 0;
11133 }
11134
11135 static int intel_gen7_queue_flip(struct drm_device *dev,
11136                                  struct drm_crtc *crtc,
11137                                  struct drm_framebuffer *fb,
11138                                  struct drm_i915_gem_object *obj,
11139                                  struct drm_i915_gem_request *req,
11140                                  uint32_t flags)
11141 {
11142         struct intel_engine_cs *engine = req->engine;
11143         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11144         uint32_t plane_bit = 0;
11145         int len, ret;
11146
11147         switch (intel_crtc->plane) {
11148         case PLANE_A:
11149                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11150                 break;
11151         case PLANE_B:
11152                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11153                 break;
11154         case PLANE_C:
11155                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11156                 break;
11157         default:
11158                 WARN_ONCE(1, "unknown plane in flip command\n");
11159                 return -ENODEV;
11160         }
11161
11162         len = 4;
11163         if (engine->id == RCS) {
11164                 len += 6;
11165                 /*
11166                  * On Gen 8, SRM is now taking an extra dword to accommodate
11167                  * 48bits addresses, and we need a NOOP for the batch size to
11168                  * stay even.
11169                  */
11170                 if (IS_GEN8(dev))
11171                         len += 2;
11172         }
11173
11174         /*
11175          * BSpec MI_DISPLAY_FLIP for IVB:
11176          * "The full packet must be contained within the same cache line."
11177          *
11178          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11179          * cacheline, if we ever start emitting more commands before
11180          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11181          * then do the cacheline alignment, and finally emit the
11182          * MI_DISPLAY_FLIP.
11183          */
11184         ret = intel_ring_cacheline_align(req);
11185         if (ret)
11186                 return ret;
11187
11188         ret = intel_ring_begin(req, len);
11189         if (ret)
11190                 return ret;
11191
11192         /* Unmask the flip-done completion message. Note that the bspec says that
11193          * we should do this for both the BCS and RCS, and that we must not unmask
11194          * more than one flip event at any time (or ensure that one flip message
11195          * can be sent by waiting for flip-done prior to queueing new flips).
11196          * Experimentation says that BCS works despite DERRMR masking all
11197          * flip-done completion events and that unmasking all planes at once
11198          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11199          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11200          */
11201         if (engine->id == RCS) {
11202                 intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
11203                 intel_ring_emit_reg(engine, DERRMR);
11204                 intel_ring_emit(engine, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11205                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11206                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11207                 if (IS_GEN8(dev))
11208                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM_GEN8 |
11209                                               MI_SRM_LRM_GLOBAL_GTT);
11210                 else
11211                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM |
11212                                               MI_SRM_LRM_GLOBAL_GTT);
11213                 intel_ring_emit_reg(engine, DERRMR);
11214                 intel_ring_emit(engine, engine->scratch.gtt_offset + 256);
11215                 if (IS_GEN8(dev)) {
11216                         intel_ring_emit(engine, 0);
11217                         intel_ring_emit(engine, MI_NOOP);
11218                 }
11219         }
11220
11221         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 | plane_bit);
11222         intel_ring_emit(engine, (fb->pitches[0] | obj->tiling_mode));
11223         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11224         intel_ring_emit(engine, (MI_NOOP));
11225
11226         return 0;
11227 }
11228
11229 static bool use_mmio_flip(struct intel_engine_cs *engine,
11230                           struct drm_i915_gem_object *obj)
11231 {
11232         /*
11233          * This is not being used for older platforms, because
11234          * non-availability of flip done interrupt forces us to use
11235          * CS flips. Older platforms derive flip done using some clever
11236          * tricks involving the flip_pending status bits and vblank irqs.
11237          * So using MMIO flips there would disrupt this mechanism.
11238          */
11239
11240         if (engine == NULL)
11241                 return true;
11242
11243         if (INTEL_GEN(engine->i915) < 5)
11244                 return false;
11245
11246         if (i915.use_mmio_flip < 0)
11247                 return false;
11248         else if (i915.use_mmio_flip > 0)
11249                 return true;
11250         else if (i915.enable_execlists)
11251                 return true;
11252         else if (obj->base.dma_buf &&
11253                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11254                                                        false))
11255                 return true;
11256         else
11257                 return engine != i915_gem_request_get_engine(obj->last_write_req);
11258 }
11259
11260 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11261                              unsigned int rotation,
11262                              struct intel_unpin_work *work)
11263 {
11264         struct drm_device *dev = intel_crtc->base.dev;
11265         struct drm_i915_private *dev_priv = dev->dev_private;
11266         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11267         const enum pipe pipe = intel_crtc->pipe;
11268         u32 ctl, stride, tile_height;
11269
11270         ctl = I915_READ(PLANE_CTL(pipe, 0));
11271         ctl &= ~PLANE_CTL_TILED_MASK;
11272         switch (fb->modifier[0]) {
11273         case DRM_FORMAT_MOD_NONE:
11274                 break;
11275         case I915_FORMAT_MOD_X_TILED:
11276                 ctl |= PLANE_CTL_TILED_X;
11277                 break;
11278         case I915_FORMAT_MOD_Y_TILED:
11279                 ctl |= PLANE_CTL_TILED_Y;
11280                 break;
11281         case I915_FORMAT_MOD_Yf_TILED:
11282                 ctl |= PLANE_CTL_TILED_YF;
11283                 break;
11284         default:
11285                 MISSING_CASE(fb->modifier[0]);
11286         }
11287
11288         /*
11289          * The stride is either expressed as a multiple of 64 bytes chunks for
11290          * linear buffers or in number of tiles for tiled buffers.
11291          */
11292         if (intel_rotation_90_or_270(rotation)) {
11293                 /* stride = Surface height in tiles */
11294                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11295                 stride = DIV_ROUND_UP(fb->height, tile_height);
11296         } else {
11297                 stride = fb->pitches[0] /
11298                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11299                                                   fb->pixel_format);
11300         }
11301
11302         /*
11303          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11304          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11305          */
11306         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11307         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11308
11309         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11310         POSTING_READ(PLANE_SURF(pipe, 0));
11311 }
11312
11313 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11314                              struct intel_unpin_work *work)
11315 {
11316         struct drm_device *dev = intel_crtc->base.dev;
11317         struct drm_i915_private *dev_priv = dev->dev_private;
11318         struct intel_framebuffer *intel_fb =
11319                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11320         struct drm_i915_gem_object *obj = intel_fb->obj;
11321         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11322         u32 dspcntr;
11323
11324         dspcntr = I915_READ(reg);
11325
11326         if (obj->tiling_mode != I915_TILING_NONE)
11327                 dspcntr |= DISPPLANE_TILED;
11328         else
11329                 dspcntr &= ~DISPPLANE_TILED;
11330
11331         I915_WRITE(reg, dspcntr);
11332
11333         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11334         POSTING_READ(DSPSURF(intel_crtc->plane));
11335 }
11336
11337 /*
11338  * XXX: This is the temporary way to update the plane registers until we get
11339  * around to using the usual plane update functions for MMIO flips
11340  */
11341 static void intel_do_mmio_flip(struct intel_mmio_flip *mmio_flip)
11342 {
11343         struct intel_crtc *crtc = mmio_flip->crtc;
11344         struct intel_unpin_work *work;
11345
11346         spin_lock_irq(&crtc->base.dev->event_lock);
11347         work = crtc->unpin_work;
11348         spin_unlock_irq(&crtc->base.dev->event_lock);
11349         if (work == NULL)
11350                 return;
11351
11352         intel_pipe_update_start(crtc);
11353
11354         if (INTEL_INFO(mmio_flip->i915)->gen >= 9)
11355                 skl_do_mmio_flip(crtc, mmio_flip->rotation, work);
11356         else
11357                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11358                 ilk_do_mmio_flip(crtc, work);
11359
11360         intel_pipe_update_end(crtc);
11361
11362         intel_mark_page_flip_active(work);
11363 }
11364
11365 static void intel_mmio_flip_work_func(struct work_struct *work)
11366 {
11367         struct intel_mmio_flip *mmio_flip =
11368                 container_of(work, struct intel_mmio_flip, work);
11369         struct intel_framebuffer *intel_fb =
11370                 to_intel_framebuffer(mmio_flip->crtc->base.primary->fb);
11371         struct drm_i915_gem_object *obj = intel_fb->obj;
11372
11373         if (mmio_flip->req) {
11374                 WARN_ON(__i915_wait_request(mmio_flip->req,
11375                                             false, NULL,
11376                                             &mmio_flip->i915->rps.mmioflips));
11377                 i915_gem_request_unreference(mmio_flip->req);
11378         }
11379
11380         /* For framebuffer backed by dmabuf, wait for fence */
11381         if (obj->base.dma_buf)
11382                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11383                                                             false, false,
11384                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11385
11386         intel_do_mmio_flip(mmio_flip);
11387         kfree(mmio_flip);
11388 }
11389
11390 static int intel_queue_mmio_flip(struct drm_device *dev,
11391                                  struct drm_crtc *crtc,
11392                                  struct drm_i915_gem_object *obj)
11393 {
11394         struct intel_mmio_flip *mmio_flip;
11395
11396         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11397         if (mmio_flip == NULL)
11398                 return -ENOMEM;
11399
11400         mmio_flip->i915 = to_i915(dev);
11401         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11402         mmio_flip->crtc = to_intel_crtc(crtc);
11403         mmio_flip->rotation = crtc->primary->state->rotation;
11404
11405         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11406         schedule_work(&mmio_flip->work);
11407
11408         return 0;
11409 }
11410
11411 static int intel_default_queue_flip(struct drm_device *dev,
11412                                     struct drm_crtc *crtc,
11413                                     struct drm_framebuffer *fb,
11414                                     struct drm_i915_gem_object *obj,
11415                                     struct drm_i915_gem_request *req,
11416                                     uint32_t flags)
11417 {
11418         return -ENODEV;
11419 }
11420
11421 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11422                                          struct drm_crtc *crtc)
11423 {
11424         struct drm_i915_private *dev_priv = dev->dev_private;
11425         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11426         struct intel_unpin_work *work = intel_crtc->unpin_work;
11427         u32 addr;
11428         u32 pending;
11429
11430         pending = atomic_read(&work->pending);
11431         /* ensure that the unpin work is consistent wrt ->pending. */
11432         smp_rmb();
11433
11434         if (pending != INTEL_FLIP_PENDING)
11435                 return pending == INTEL_FLIP_COMPLETE;
11436
11437         if (work->flip_ready_vblank == 0) {
11438                 if (work->flip_queued_req &&
11439                     !i915_gem_request_completed(work->flip_queued_req, true))
11440                         return false;
11441
11442                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11443         }
11444
11445         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11446                 return false;
11447
11448         /* Potential stall - if we see that the flip has happened,
11449          * assume a missed interrupt. */
11450         if (INTEL_INFO(dev)->gen >= 4)
11451                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11452         else
11453                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11454
11455         /* There is a potential issue here with a false positive after a flip
11456          * to the same address. We could address this by checking for a
11457          * non-incrementing frame counter.
11458          */
11459         return addr == work->gtt_offset;
11460 }
11461
11462 void intel_check_page_flip(struct drm_i915_private *dev_priv, int pipe)
11463 {
11464         struct drm_device *dev = dev_priv->dev;
11465         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11466         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11467         struct intel_unpin_work *work;
11468
11469         WARN_ON(!in_interrupt());
11470
11471         if (crtc == NULL)
11472                 return;
11473
11474         spin_lock(&dev->event_lock);
11475         work = intel_crtc->unpin_work;
11476         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11477                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11478                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11479                 page_flip_completed(intel_crtc);
11480                 work = NULL;
11481         }
11482         if (work != NULL &&
11483             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11484                 intel_queue_rps_boost_for_request(work->flip_queued_req);
11485         spin_unlock(&dev->event_lock);
11486 }
11487
11488 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11489                                 struct drm_framebuffer *fb,
11490                                 struct drm_pending_vblank_event *event,
11491                                 uint32_t page_flip_flags)
11492 {
11493         struct drm_device *dev = crtc->dev;
11494         struct drm_i915_private *dev_priv = dev->dev_private;
11495         struct drm_framebuffer *old_fb = crtc->primary->fb;
11496         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11497         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11498         struct drm_plane *primary = crtc->primary;
11499         enum pipe pipe = intel_crtc->pipe;
11500         struct intel_unpin_work *work;
11501         struct intel_engine_cs *engine;
11502         bool mmio_flip;
11503         struct drm_i915_gem_request *request = NULL;
11504         int ret;
11505
11506         /*
11507          * drm_mode_page_flip_ioctl() should already catch this, but double
11508          * check to be safe.  In the future we may enable pageflipping from
11509          * a disabled primary plane.
11510          */
11511         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11512                 return -EBUSY;
11513
11514         /* Can't change pixel format via MI display flips. */
11515         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11516                 return -EINVAL;
11517
11518         /*
11519          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11520          * Note that pitch changes could also affect these register.
11521          */
11522         if (INTEL_INFO(dev)->gen > 3 &&
11523             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11524              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11525                 return -EINVAL;
11526
11527         if (i915_terminally_wedged(&dev_priv->gpu_error))
11528                 goto out_hang;
11529
11530         work = kzalloc(sizeof(*work), GFP_KERNEL);
11531         if (work == NULL)
11532                 return -ENOMEM;
11533
11534         work->event = event;
11535         work->crtc = crtc;
11536         work->old_fb = old_fb;
11537         INIT_WORK(&work->work, intel_unpin_work_fn);
11538
11539         ret = drm_crtc_vblank_get(crtc);
11540         if (ret)
11541                 goto free_work;
11542
11543         /* We borrow the event spin lock for protecting unpin_work */
11544         spin_lock_irq(&dev->event_lock);
11545         if (intel_crtc->unpin_work) {
11546                 /* Before declaring the flip queue wedged, check if
11547                  * the hardware completed the operation behind our backs.
11548                  */
11549                 if (__intel_pageflip_stall_check(dev, crtc)) {
11550                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11551                         page_flip_completed(intel_crtc);
11552                 } else {
11553                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11554                         spin_unlock_irq(&dev->event_lock);
11555
11556                         drm_crtc_vblank_put(crtc);
11557                         kfree(work);
11558                         return -EBUSY;
11559                 }
11560         }
11561         intel_crtc->unpin_work = work;
11562         spin_unlock_irq(&dev->event_lock);
11563
11564         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11565                 flush_workqueue(dev_priv->wq);
11566
11567         /* Reference the objects for the scheduled work. */
11568         drm_framebuffer_reference(work->old_fb);
11569         drm_gem_object_reference(&obj->base);
11570
11571         crtc->primary->fb = fb;
11572         update_state_fb(crtc->primary);
11573         intel_fbc_pre_update(intel_crtc);
11574
11575         work->pending_flip_obj = obj;
11576
11577         ret = i915_mutex_lock_interruptible(dev);
11578         if (ret)
11579                 goto cleanup;
11580
11581         intel_crtc->reset_counter = i915_reset_counter(&dev_priv->gpu_error);
11582         if (__i915_reset_in_progress_or_wedged(intel_crtc->reset_counter)) {
11583                 ret = -EIO;
11584                 goto cleanup;
11585         }
11586
11587         atomic_inc(&intel_crtc->unpin_work_count);
11588
11589         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11590                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11591
11592         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11593                 engine = &dev_priv->engine[BCS];
11594                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11595                         /* vlv: DISPLAY_FLIP fails to change tiling */
11596                         engine = NULL;
11597         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11598                 engine = &dev_priv->engine[BCS];
11599         } else if (INTEL_INFO(dev)->gen >= 7) {
11600                 engine = i915_gem_request_get_engine(obj->last_write_req);
11601                 if (engine == NULL || engine->id != RCS)
11602                         engine = &dev_priv->engine[BCS];
11603         } else {
11604                 engine = &dev_priv->engine[RCS];
11605         }
11606
11607         mmio_flip = use_mmio_flip(engine, obj);
11608
11609         /* When using CS flips, we want to emit semaphores between rings.
11610          * However, when using mmio flips we will create a task to do the
11611          * synchronisation, so all we want here is to pin the framebuffer
11612          * into the display plane and skip any waits.
11613          */
11614         if (!mmio_flip) {
11615                 ret = i915_gem_object_sync(obj, engine, &request);
11616                 if (!ret && !request) {
11617                         request = i915_gem_request_alloc(engine, NULL);
11618                         ret = PTR_ERR_OR_ZERO(request);
11619                 }
11620
11621                 if (ret)
11622                         goto cleanup_pending;
11623         }
11624
11625         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11626         if (ret)
11627                 goto cleanup_pending;
11628
11629         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11630                                                   obj, 0);
11631         work->gtt_offset += intel_crtc->dspaddr_offset;
11632
11633         if (mmio_flip) {
11634                 work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11635
11636                 i915_gem_request_assign(&work->flip_queued_req,
11637                                         obj->last_write_req);
11638
11639                 ret = intel_queue_mmio_flip(dev, crtc, obj);
11640                 if (ret)
11641                         goto cleanup_unpin;
11642         } else {
11643                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11644                                                    page_flip_flags);
11645                 if (ret)
11646                         goto cleanup_unpin;
11647
11648                 i915_gem_request_assign(&work->flip_queued_req, request);
11649
11650                 work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11651                 intel_mark_page_flip_active(work);
11652
11653                 i915_add_request_no_flush(request);
11654         }
11655
11656         i915_gem_track_fb(intel_fb_obj(old_fb), obj,
11657                           to_intel_plane(primary)->frontbuffer_bit);
11658         mutex_unlock(&dev->struct_mutex);
11659
11660         intel_frontbuffer_flip_prepare(dev,
11661                                        to_intel_plane(primary)->frontbuffer_bit);
11662
11663         trace_i915_flip_request(intel_crtc->plane, obj);
11664
11665         return 0;
11666
11667 cleanup_unpin:
11668         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11669 cleanup_pending:
11670         if (!IS_ERR_OR_NULL(request))
11671                 i915_add_request_no_flush(request);
11672         atomic_dec(&intel_crtc->unpin_work_count);
11673         mutex_unlock(&dev->struct_mutex);
11674 cleanup:
11675         crtc->primary->fb = old_fb;
11676         update_state_fb(crtc->primary);
11677
11678         drm_gem_object_unreference_unlocked(&obj->base);
11679         drm_framebuffer_unreference(work->old_fb);
11680
11681         spin_lock_irq(&dev->event_lock);
11682         intel_crtc->unpin_work = NULL;
11683         spin_unlock_irq(&dev->event_lock);
11684
11685         drm_crtc_vblank_put(crtc);
11686 free_work:
11687         kfree(work);
11688
11689         if (ret == -EIO) {
11690                 struct drm_atomic_state *state;
11691                 struct drm_plane_state *plane_state;
11692
11693 out_hang:
11694                 state = drm_atomic_state_alloc(dev);
11695                 if (!state)
11696                         return -ENOMEM;
11697                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11698
11699 retry:
11700                 plane_state = drm_atomic_get_plane_state(state, primary);
11701                 ret = PTR_ERR_OR_ZERO(plane_state);
11702                 if (!ret) {
11703                         drm_atomic_set_fb_for_plane(plane_state, fb);
11704
11705                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11706                         if (!ret)
11707                                 ret = drm_atomic_commit(state);
11708                 }
11709
11710                 if (ret == -EDEADLK) {
11711                         drm_modeset_backoff(state->acquire_ctx);
11712                         drm_atomic_state_clear(state);
11713                         goto retry;
11714                 }
11715
11716                 if (ret)
11717                         drm_atomic_state_free(state);
11718
11719                 if (ret == 0 && event) {
11720                         spin_lock_irq(&dev->event_lock);
11721                         drm_crtc_send_vblank_event(crtc, event);
11722                         spin_unlock_irq(&dev->event_lock);
11723                 }
11724         }
11725         return ret;
11726 }
11727
11728
11729 /**
11730  * intel_wm_need_update - Check whether watermarks need updating
11731  * @plane: drm plane
11732  * @state: new plane state
11733  *
11734  * Check current plane state versus the new one to determine whether
11735  * watermarks need to be recalculated.
11736  *
11737  * Returns true or false.
11738  */
11739 static bool intel_wm_need_update(struct drm_plane *plane,
11740                                  struct drm_plane_state *state)
11741 {
11742         struct intel_plane_state *new = to_intel_plane_state(state);
11743         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11744
11745         /* Update watermarks on tiling or size changes. */
11746         if (new->visible != cur->visible)
11747                 return true;
11748
11749         if (!cur->base.fb || !new->base.fb)
11750                 return false;
11751
11752         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11753             cur->base.rotation != new->base.rotation ||
11754             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11755             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11756             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11757             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11758                 return true;
11759
11760         return false;
11761 }
11762
11763 static bool needs_scaling(struct intel_plane_state *state)
11764 {
11765         int src_w = drm_rect_width(&state->src) >> 16;
11766         int src_h = drm_rect_height(&state->src) >> 16;
11767         int dst_w = drm_rect_width(&state->dst);
11768         int dst_h = drm_rect_height(&state->dst);
11769
11770         return (src_w != dst_w || src_h != dst_h);
11771 }
11772
11773 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11774                                     struct drm_plane_state *plane_state)
11775 {
11776         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11777         struct drm_crtc *crtc = crtc_state->crtc;
11778         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11779         struct drm_plane *plane = plane_state->plane;
11780         struct drm_device *dev = crtc->dev;
11781         struct drm_i915_private *dev_priv = to_i915(dev);
11782         struct intel_plane_state *old_plane_state =
11783                 to_intel_plane_state(plane->state);
11784         int idx = intel_crtc->base.base.id, ret;
11785         bool mode_changed = needs_modeset(crtc_state);
11786         bool was_crtc_enabled = crtc->state->active;
11787         bool is_crtc_enabled = crtc_state->active;
11788         bool turn_off, turn_on, visible, was_visible;
11789         struct drm_framebuffer *fb = plane_state->fb;
11790
11791         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11792             plane->type != DRM_PLANE_TYPE_CURSOR) {
11793                 ret = skl_update_scaler_plane(
11794                         to_intel_crtc_state(crtc_state),
11795                         to_intel_plane_state(plane_state));
11796                 if (ret)
11797                         return ret;
11798         }
11799
11800         was_visible = old_plane_state->visible;
11801         visible = to_intel_plane_state(plane_state)->visible;
11802
11803         if (!was_crtc_enabled && WARN_ON(was_visible))
11804                 was_visible = false;
11805
11806         /*
11807          * Visibility is calculated as if the crtc was on, but
11808          * after scaler setup everything depends on it being off
11809          * when the crtc isn't active.
11810          *
11811          * FIXME this is wrong for watermarks. Watermarks should also
11812          * be computed as if the pipe would be active. Perhaps move
11813          * per-plane wm computation to the .check_plane() hook, and
11814          * only combine the results from all planes in the current place?
11815          */
11816         if (!is_crtc_enabled)
11817                 to_intel_plane_state(plane_state)->visible = visible = false;
11818
11819         if (!was_visible && !visible)
11820                 return 0;
11821
11822         if (fb != old_plane_state->base.fb)
11823                 pipe_config->fb_changed = true;
11824
11825         turn_off = was_visible && (!visible || mode_changed);
11826         turn_on = visible && (!was_visible || mode_changed);
11827
11828         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11829                          plane->base.id, fb ? fb->base.id : -1);
11830
11831         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11832                          plane->base.id, was_visible, visible,
11833                          turn_off, turn_on, mode_changed);
11834
11835         if (turn_on) {
11836                 pipe_config->update_wm_pre = true;
11837
11838                 /* must disable cxsr around plane enable/disable */
11839                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11840                         pipe_config->disable_cxsr = true;
11841         } else if (turn_off) {
11842                 pipe_config->update_wm_post = true;
11843
11844                 /* must disable cxsr around plane enable/disable */
11845                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11846                         pipe_config->disable_cxsr = true;
11847         } else if (intel_wm_need_update(plane, plane_state)) {
11848                 /* FIXME bollocks */
11849                 pipe_config->update_wm_pre = true;
11850                 pipe_config->update_wm_post = true;
11851         }
11852
11853         /* Pre-gen9 platforms need two-step watermark updates */
11854         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11855             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11856                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11857
11858         if (visible || was_visible)
11859                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11860
11861         /*
11862          * WaCxSRDisabledForSpriteScaling:ivb
11863          *
11864          * cstate->update_wm was already set above, so this flag will
11865          * take effect when we commit and program watermarks.
11866          */
11867         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
11868             needs_scaling(to_intel_plane_state(plane_state)) &&
11869             !needs_scaling(old_plane_state))
11870                 pipe_config->disable_lp_wm = true;
11871
11872         return 0;
11873 }
11874
11875 static bool encoders_cloneable(const struct intel_encoder *a,
11876                                const struct intel_encoder *b)
11877 {
11878         /* masks could be asymmetric, so check both ways */
11879         return a == b || (a->cloneable & (1 << b->type) &&
11880                           b->cloneable & (1 << a->type));
11881 }
11882
11883 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11884                                          struct intel_crtc *crtc,
11885                                          struct intel_encoder *encoder)
11886 {
11887         struct intel_encoder *source_encoder;
11888         struct drm_connector *connector;
11889         struct drm_connector_state *connector_state;
11890         int i;
11891
11892         for_each_connector_in_state(state, connector, connector_state, i) {
11893                 if (connector_state->crtc != &crtc->base)
11894                         continue;
11895
11896                 source_encoder =
11897                         to_intel_encoder(connector_state->best_encoder);
11898                 if (!encoders_cloneable(encoder, source_encoder))
11899                         return false;
11900         }
11901
11902         return true;
11903 }
11904
11905 static bool check_encoder_cloning(struct drm_atomic_state *state,
11906                                   struct intel_crtc *crtc)
11907 {
11908         struct intel_encoder *encoder;
11909         struct drm_connector *connector;
11910         struct drm_connector_state *connector_state;
11911         int i;
11912
11913         for_each_connector_in_state(state, connector, connector_state, i) {
11914                 if (connector_state->crtc != &crtc->base)
11915                         continue;
11916
11917                 encoder = to_intel_encoder(connector_state->best_encoder);
11918                 if (!check_single_encoder_cloning(state, crtc, encoder))
11919                         return false;
11920         }
11921
11922         return true;
11923 }
11924
11925 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11926                                    struct drm_crtc_state *crtc_state)
11927 {
11928         struct drm_device *dev = crtc->dev;
11929         struct drm_i915_private *dev_priv = dev->dev_private;
11930         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11931         struct intel_crtc_state *pipe_config =
11932                 to_intel_crtc_state(crtc_state);
11933         struct drm_atomic_state *state = crtc_state->state;
11934         int ret;
11935         bool mode_changed = needs_modeset(crtc_state);
11936
11937         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11938                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11939                 return -EINVAL;
11940         }
11941
11942         if (mode_changed && !crtc_state->active)
11943                 pipe_config->update_wm_post = true;
11944
11945         if (mode_changed && crtc_state->enable &&
11946             dev_priv->display.crtc_compute_clock &&
11947             !WARN_ON(pipe_config->shared_dpll)) {
11948                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11949                                                            pipe_config);
11950                 if (ret)
11951                         return ret;
11952         }
11953
11954         if (crtc_state->color_mgmt_changed) {
11955                 ret = intel_color_check(crtc, crtc_state);
11956                 if (ret)
11957                         return ret;
11958         }
11959
11960         ret = 0;
11961         if (dev_priv->display.compute_pipe_wm) {
11962                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11963                 if (ret) {
11964                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11965                         return ret;
11966                 }
11967         }
11968
11969         if (dev_priv->display.compute_intermediate_wm &&
11970             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11971                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11972                         return 0;
11973
11974                 /*
11975                  * Calculate 'intermediate' watermarks that satisfy both the
11976                  * old state and the new state.  We can program these
11977                  * immediately.
11978                  */
11979                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
11980                                                                 intel_crtc,
11981                                                                 pipe_config);
11982                 if (ret) {
11983                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11984                         return ret;
11985                 }
11986         } else if (dev_priv->display.compute_intermediate_wm) {
11987                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
11988                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
11989         }
11990
11991         if (INTEL_INFO(dev)->gen >= 9) {
11992                 if (mode_changed)
11993                         ret = skl_update_scaler_crtc(pipe_config);
11994
11995                 if (!ret)
11996                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11997                                                          pipe_config);
11998         }
11999
12000         return ret;
12001 }
12002
12003 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12004         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12005         .atomic_begin = intel_begin_crtc_commit,
12006         .atomic_flush = intel_finish_crtc_commit,
12007         .atomic_check = intel_crtc_atomic_check,
12008 };
12009
12010 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12011 {
12012         struct intel_connector *connector;
12013
12014         for_each_intel_connector(dev, connector) {
12015                 if (connector->base.state->crtc)
12016                         drm_connector_unreference(&connector->base);
12017
12018                 if (connector->base.encoder) {
12019                         connector->base.state->best_encoder =
12020                                 connector->base.encoder;
12021                         connector->base.state->crtc =
12022                                 connector->base.encoder->crtc;
12023
12024                         drm_connector_reference(&connector->base);
12025                 } else {
12026                         connector->base.state->best_encoder = NULL;
12027                         connector->base.state->crtc = NULL;
12028                 }
12029         }
12030 }
12031
12032 static void
12033 connected_sink_compute_bpp(struct intel_connector *connector,
12034                            struct intel_crtc_state *pipe_config)
12035 {
12036         int bpp = pipe_config->pipe_bpp;
12037
12038         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12039                 connector->base.base.id,
12040                 connector->base.name);
12041
12042         /* Don't use an invalid EDID bpc value */
12043         if (connector->base.display_info.bpc &&
12044             connector->base.display_info.bpc * 3 < bpp) {
12045                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12046                               bpp, connector->base.display_info.bpc*3);
12047                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12048         }
12049
12050         /* Clamp bpp to default limit on screens without EDID 1.4 */
12051         if (connector->base.display_info.bpc == 0) {
12052                 int type = connector->base.connector_type;
12053                 int clamp_bpp = 24;
12054
12055                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12056                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12057                     type == DRM_MODE_CONNECTOR_eDP)
12058                         clamp_bpp = 18;
12059
12060                 if (bpp > clamp_bpp) {
12061                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12062                                       bpp, clamp_bpp);
12063                         pipe_config->pipe_bpp = clamp_bpp;
12064                 }
12065         }
12066 }
12067
12068 static int
12069 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12070                           struct intel_crtc_state *pipe_config)
12071 {
12072         struct drm_device *dev = crtc->base.dev;
12073         struct drm_atomic_state *state;
12074         struct drm_connector *connector;
12075         struct drm_connector_state *connector_state;
12076         int bpp, i;
12077
12078         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12079                 bpp = 10*3;
12080         else if (INTEL_INFO(dev)->gen >= 5)
12081                 bpp = 12*3;
12082         else
12083                 bpp = 8*3;
12084
12085
12086         pipe_config->pipe_bpp = bpp;
12087
12088         state = pipe_config->base.state;
12089
12090         /* Clamp display bpp to EDID value */
12091         for_each_connector_in_state(state, connector, connector_state, i) {
12092                 if (connector_state->crtc != &crtc->base)
12093                         continue;
12094
12095                 connected_sink_compute_bpp(to_intel_connector(connector),
12096                                            pipe_config);
12097         }
12098
12099         return bpp;
12100 }
12101
12102 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12103 {
12104         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12105                         "type: 0x%x flags: 0x%x\n",
12106                 mode->crtc_clock,
12107                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12108                 mode->crtc_hsync_end, mode->crtc_htotal,
12109                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12110                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12111 }
12112
12113 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12114                                    struct intel_crtc_state *pipe_config,
12115                                    const char *context)
12116 {
12117         struct drm_device *dev = crtc->base.dev;
12118         struct drm_plane *plane;
12119         struct intel_plane *intel_plane;
12120         struct intel_plane_state *state;
12121         struct drm_framebuffer *fb;
12122
12123         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12124                       context, pipe_config, pipe_name(crtc->pipe));
12125
12126         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12127         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12128                       pipe_config->pipe_bpp, pipe_config->dither);
12129         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12130                       pipe_config->has_pch_encoder,
12131                       pipe_config->fdi_lanes,
12132                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12133                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12134                       pipe_config->fdi_m_n.tu);
12135         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12136                       pipe_config->has_dp_encoder,
12137                       pipe_config->lane_count,
12138                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12139                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12140                       pipe_config->dp_m_n.tu);
12141
12142         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12143                       pipe_config->has_dp_encoder,
12144                       pipe_config->lane_count,
12145                       pipe_config->dp_m2_n2.gmch_m,
12146                       pipe_config->dp_m2_n2.gmch_n,
12147                       pipe_config->dp_m2_n2.link_m,
12148                       pipe_config->dp_m2_n2.link_n,
12149                       pipe_config->dp_m2_n2.tu);
12150
12151         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12152                       pipe_config->has_audio,
12153                       pipe_config->has_infoframe);
12154
12155         DRM_DEBUG_KMS("requested mode:\n");
12156         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12157         DRM_DEBUG_KMS("adjusted mode:\n");
12158         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12159         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12160         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12161         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12162                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12163         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12164                       crtc->num_scalers,
12165                       pipe_config->scaler_state.scaler_users,
12166                       pipe_config->scaler_state.scaler_id);
12167         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12168                       pipe_config->gmch_pfit.control,
12169                       pipe_config->gmch_pfit.pgm_ratios,
12170                       pipe_config->gmch_pfit.lvds_border_bits);
12171         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12172                       pipe_config->pch_pfit.pos,
12173                       pipe_config->pch_pfit.size,
12174                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12175         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12176         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12177
12178         if (IS_BROXTON(dev)) {
12179                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12180                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12181                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12182                               pipe_config->ddi_pll_sel,
12183                               pipe_config->dpll_hw_state.ebb0,
12184                               pipe_config->dpll_hw_state.ebb4,
12185                               pipe_config->dpll_hw_state.pll0,
12186                               pipe_config->dpll_hw_state.pll1,
12187                               pipe_config->dpll_hw_state.pll2,
12188                               pipe_config->dpll_hw_state.pll3,
12189                               pipe_config->dpll_hw_state.pll6,
12190                               pipe_config->dpll_hw_state.pll8,
12191                               pipe_config->dpll_hw_state.pll9,
12192                               pipe_config->dpll_hw_state.pll10,
12193                               pipe_config->dpll_hw_state.pcsdw12);
12194         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12195                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12196                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12197                               pipe_config->ddi_pll_sel,
12198                               pipe_config->dpll_hw_state.ctrl1,
12199                               pipe_config->dpll_hw_state.cfgcr1,
12200                               pipe_config->dpll_hw_state.cfgcr2);
12201         } else if (HAS_DDI(dev)) {
12202                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12203                               pipe_config->ddi_pll_sel,
12204                               pipe_config->dpll_hw_state.wrpll,
12205                               pipe_config->dpll_hw_state.spll);
12206         } else {
12207                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12208                               "fp0: 0x%x, fp1: 0x%x\n",
12209                               pipe_config->dpll_hw_state.dpll,
12210                               pipe_config->dpll_hw_state.dpll_md,
12211                               pipe_config->dpll_hw_state.fp0,
12212                               pipe_config->dpll_hw_state.fp1);
12213         }
12214
12215         DRM_DEBUG_KMS("planes on this crtc\n");
12216         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12217                 intel_plane = to_intel_plane(plane);
12218                 if (intel_plane->pipe != crtc->pipe)
12219                         continue;
12220
12221                 state = to_intel_plane_state(plane->state);
12222                 fb = state->base.fb;
12223                 if (!fb) {
12224                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12225                                 "disabled, scaler_id = %d\n",
12226                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12227                                 plane->base.id, intel_plane->pipe,
12228                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12229                                 drm_plane_index(plane), state->scaler_id);
12230                         continue;
12231                 }
12232
12233                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12234                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12235                         plane->base.id, intel_plane->pipe,
12236                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12237                         drm_plane_index(plane));
12238                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12239                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12240                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12241                         state->scaler_id,
12242                         state->src.x1 >> 16, state->src.y1 >> 16,
12243                         drm_rect_width(&state->src) >> 16,
12244                         drm_rect_height(&state->src) >> 16,
12245                         state->dst.x1, state->dst.y1,
12246                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12247         }
12248 }
12249
12250 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12251 {
12252         struct drm_device *dev = state->dev;
12253         struct drm_connector *connector;
12254         unsigned int used_ports = 0;
12255
12256         /*
12257          * Walk the connector list instead of the encoder
12258          * list to detect the problem on ddi platforms
12259          * where there's just one encoder per digital port.
12260          */
12261         drm_for_each_connector(connector, dev) {
12262                 struct drm_connector_state *connector_state;
12263                 struct intel_encoder *encoder;
12264
12265                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12266                 if (!connector_state)
12267                         connector_state = connector->state;
12268
12269                 if (!connector_state->best_encoder)
12270                         continue;
12271
12272                 encoder = to_intel_encoder(connector_state->best_encoder);
12273
12274                 WARN_ON(!connector_state->crtc);
12275
12276                 switch (encoder->type) {
12277                         unsigned int port_mask;
12278                 case INTEL_OUTPUT_UNKNOWN:
12279                         if (WARN_ON(!HAS_DDI(dev)))
12280                                 break;
12281                 case INTEL_OUTPUT_DISPLAYPORT:
12282                 case INTEL_OUTPUT_HDMI:
12283                 case INTEL_OUTPUT_EDP:
12284                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12285
12286                         /* the same port mustn't appear more than once */
12287                         if (used_ports & port_mask)
12288                                 return false;
12289
12290                         used_ports |= port_mask;
12291                 default:
12292                         break;
12293                 }
12294         }
12295
12296         return true;
12297 }
12298
12299 static void
12300 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12301 {
12302         struct drm_crtc_state tmp_state;
12303         struct intel_crtc_scaler_state scaler_state;
12304         struct intel_dpll_hw_state dpll_hw_state;
12305         struct intel_shared_dpll *shared_dpll;
12306         uint32_t ddi_pll_sel;
12307         bool force_thru;
12308
12309         /* FIXME: before the switch to atomic started, a new pipe_config was
12310          * kzalloc'd. Code that depends on any field being zero should be
12311          * fixed, so that the crtc_state can be safely duplicated. For now,
12312          * only fields that are know to not cause problems are preserved. */
12313
12314         tmp_state = crtc_state->base;
12315         scaler_state = crtc_state->scaler_state;
12316         shared_dpll = crtc_state->shared_dpll;
12317         dpll_hw_state = crtc_state->dpll_hw_state;
12318         ddi_pll_sel = crtc_state->ddi_pll_sel;
12319         force_thru = crtc_state->pch_pfit.force_thru;
12320
12321         memset(crtc_state, 0, sizeof *crtc_state);
12322
12323         crtc_state->base = tmp_state;
12324         crtc_state->scaler_state = scaler_state;
12325         crtc_state->shared_dpll = shared_dpll;
12326         crtc_state->dpll_hw_state = dpll_hw_state;
12327         crtc_state->ddi_pll_sel = ddi_pll_sel;
12328         crtc_state->pch_pfit.force_thru = force_thru;
12329 }
12330
12331 static int
12332 intel_modeset_pipe_config(struct drm_crtc *crtc,
12333                           struct intel_crtc_state *pipe_config)
12334 {
12335         struct drm_atomic_state *state = pipe_config->base.state;
12336         struct intel_encoder *encoder;
12337         struct drm_connector *connector;
12338         struct drm_connector_state *connector_state;
12339         int base_bpp, ret = -EINVAL;
12340         int i;
12341         bool retry = true;
12342
12343         clear_intel_crtc_state(pipe_config);
12344
12345         pipe_config->cpu_transcoder =
12346                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12347
12348         /*
12349          * Sanitize sync polarity flags based on requested ones. If neither
12350          * positive or negative polarity is requested, treat this as meaning
12351          * negative polarity.
12352          */
12353         if (!(pipe_config->base.adjusted_mode.flags &
12354               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12355                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12356
12357         if (!(pipe_config->base.adjusted_mode.flags &
12358               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12359                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12360
12361         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12362                                              pipe_config);
12363         if (base_bpp < 0)
12364                 goto fail;
12365
12366         /*
12367          * Determine the real pipe dimensions. Note that stereo modes can
12368          * increase the actual pipe size due to the frame doubling and
12369          * insertion of additional space for blanks between the frame. This
12370          * is stored in the crtc timings. We use the requested mode to do this
12371          * computation to clearly distinguish it from the adjusted mode, which
12372          * can be changed by the connectors in the below retry loop.
12373          */
12374         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12375                                &pipe_config->pipe_src_w,
12376                                &pipe_config->pipe_src_h);
12377
12378 encoder_retry:
12379         /* Ensure the port clock defaults are reset when retrying. */
12380         pipe_config->port_clock = 0;
12381         pipe_config->pixel_multiplier = 1;
12382
12383         /* Fill in default crtc timings, allow encoders to overwrite them. */
12384         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12385                               CRTC_STEREO_DOUBLE);
12386
12387         /* Pass our mode to the connectors and the CRTC to give them a chance to
12388          * adjust it according to limitations or connector properties, and also
12389          * a chance to reject the mode entirely.
12390          */
12391         for_each_connector_in_state(state, connector, connector_state, i) {
12392                 if (connector_state->crtc != crtc)
12393                         continue;
12394
12395                 encoder = to_intel_encoder(connector_state->best_encoder);
12396
12397                 if (!(encoder->compute_config(encoder, pipe_config))) {
12398                         DRM_DEBUG_KMS("Encoder config failure\n");
12399                         goto fail;
12400                 }
12401         }
12402
12403         /* Set default port clock if not overwritten by the encoder. Needs to be
12404          * done afterwards in case the encoder adjusts the mode. */
12405         if (!pipe_config->port_clock)
12406                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12407                         * pipe_config->pixel_multiplier;
12408
12409         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12410         if (ret < 0) {
12411                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12412                 goto fail;
12413         }
12414
12415         if (ret == RETRY) {
12416                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12417                         ret = -EINVAL;
12418                         goto fail;
12419                 }
12420
12421                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12422                 retry = false;
12423                 goto encoder_retry;
12424         }
12425
12426         /* Dithering seems to not pass-through bits correctly when it should, so
12427          * only enable it on 6bpc panels. */
12428         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12429         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12430                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12431
12432 fail:
12433         return ret;
12434 }
12435
12436 static void
12437 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12438 {
12439         struct drm_crtc *crtc;
12440         struct drm_crtc_state *crtc_state;
12441         int i;
12442
12443         /* Double check state. */
12444         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12445                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12446
12447                 /* Update hwmode for vblank functions */
12448                 if (crtc->state->active)
12449                         crtc->hwmode = crtc->state->adjusted_mode;
12450                 else
12451                         crtc->hwmode.crtc_clock = 0;
12452
12453                 /*
12454                  * Update legacy state to satisfy fbc code. This can
12455                  * be removed when fbc uses the atomic state.
12456                  */
12457                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12458                         struct drm_plane_state *plane_state = crtc->primary->state;
12459
12460                         crtc->primary->fb = plane_state->fb;
12461                         crtc->x = plane_state->src_x >> 16;
12462                         crtc->y = plane_state->src_y >> 16;
12463                 }
12464         }
12465 }
12466
12467 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12468 {
12469         int diff;
12470
12471         if (clock1 == clock2)
12472                 return true;
12473
12474         if (!clock1 || !clock2)
12475                 return false;
12476
12477         diff = abs(clock1 - clock2);
12478
12479         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12480                 return true;
12481
12482         return false;
12483 }
12484
12485 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12486         list_for_each_entry((intel_crtc), \
12487                             &(dev)->mode_config.crtc_list, \
12488                             base.head) \
12489                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12490
12491 static bool
12492 intel_compare_m_n(unsigned int m, unsigned int n,
12493                   unsigned int m2, unsigned int n2,
12494                   bool exact)
12495 {
12496         if (m == m2 && n == n2)
12497                 return true;
12498
12499         if (exact || !m || !n || !m2 || !n2)
12500                 return false;
12501
12502         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12503
12504         if (n > n2) {
12505                 while (n > n2) {
12506                         m2 <<= 1;
12507                         n2 <<= 1;
12508                 }
12509         } else if (n < n2) {
12510                 while (n < n2) {
12511                         m <<= 1;
12512                         n <<= 1;
12513                 }
12514         }
12515
12516         if (n != n2)
12517                 return false;
12518
12519         return intel_fuzzy_clock_check(m, m2);
12520 }
12521
12522 static bool
12523 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12524                        struct intel_link_m_n *m2_n2,
12525                        bool adjust)
12526 {
12527         if (m_n->tu == m2_n2->tu &&
12528             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12529                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12530             intel_compare_m_n(m_n->link_m, m_n->link_n,
12531                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12532                 if (adjust)
12533                         *m2_n2 = *m_n;
12534
12535                 return true;
12536         }
12537
12538         return false;
12539 }
12540
12541 static bool
12542 intel_pipe_config_compare(struct drm_device *dev,
12543                           struct intel_crtc_state *current_config,
12544                           struct intel_crtc_state *pipe_config,
12545                           bool adjust)
12546 {
12547         bool ret = true;
12548
12549 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12550         do { \
12551                 if (!adjust) \
12552                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12553                 else \
12554                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12555         } while (0)
12556
12557 #define PIPE_CONF_CHECK_X(name) \
12558         if (current_config->name != pipe_config->name) { \
12559                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12560                           "(expected 0x%08x, found 0x%08x)\n", \
12561                           current_config->name, \
12562                           pipe_config->name); \
12563                 ret = false; \
12564         }
12565
12566 #define PIPE_CONF_CHECK_I(name) \
12567         if (current_config->name != pipe_config->name) { \
12568                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12569                           "(expected %i, found %i)\n", \
12570                           current_config->name, \
12571                           pipe_config->name); \
12572                 ret = false; \
12573         }
12574
12575 #define PIPE_CONF_CHECK_P(name) \
12576         if (current_config->name != pipe_config->name) { \
12577                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12578                           "(expected %p, found %p)\n", \
12579                           current_config->name, \
12580                           pipe_config->name); \
12581                 ret = false; \
12582         }
12583
12584 #define PIPE_CONF_CHECK_M_N(name) \
12585         if (!intel_compare_link_m_n(&current_config->name, \
12586                                     &pipe_config->name,\
12587                                     adjust)) { \
12588                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12589                           "(expected tu %i gmch %i/%i link %i/%i, " \
12590                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12591                           current_config->name.tu, \
12592                           current_config->name.gmch_m, \
12593                           current_config->name.gmch_n, \
12594                           current_config->name.link_m, \
12595                           current_config->name.link_n, \
12596                           pipe_config->name.tu, \
12597                           pipe_config->name.gmch_m, \
12598                           pipe_config->name.gmch_n, \
12599                           pipe_config->name.link_m, \
12600                           pipe_config->name.link_n); \
12601                 ret = false; \
12602         }
12603
12604 /* This is required for BDW+ where there is only one set of registers for
12605  * switching between high and low RR.
12606  * This macro can be used whenever a comparison has to be made between one
12607  * hw state and multiple sw state variables.
12608  */
12609 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12610         if (!intel_compare_link_m_n(&current_config->name, \
12611                                     &pipe_config->name, adjust) && \
12612             !intel_compare_link_m_n(&current_config->alt_name, \
12613                                     &pipe_config->name, adjust)) { \
12614                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12615                           "(expected tu %i gmch %i/%i link %i/%i, " \
12616                           "or tu %i gmch %i/%i link %i/%i, " \
12617                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12618                           current_config->name.tu, \
12619                           current_config->name.gmch_m, \
12620                           current_config->name.gmch_n, \
12621                           current_config->name.link_m, \
12622                           current_config->name.link_n, \
12623                           current_config->alt_name.tu, \
12624                           current_config->alt_name.gmch_m, \
12625                           current_config->alt_name.gmch_n, \
12626                           current_config->alt_name.link_m, \
12627                           current_config->alt_name.link_n, \
12628                           pipe_config->name.tu, \
12629                           pipe_config->name.gmch_m, \
12630                           pipe_config->name.gmch_n, \
12631                           pipe_config->name.link_m, \
12632                           pipe_config->name.link_n); \
12633                 ret = false; \
12634         }
12635
12636 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12637         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12638                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12639                           "(expected %i, found %i)\n", \
12640                           current_config->name & (mask), \
12641                           pipe_config->name & (mask)); \
12642                 ret = false; \
12643         }
12644
12645 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12646         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12647                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12648                           "(expected %i, found %i)\n", \
12649                           current_config->name, \
12650                           pipe_config->name); \
12651                 ret = false; \
12652         }
12653
12654 #define PIPE_CONF_QUIRK(quirk)  \
12655         ((current_config->quirks | pipe_config->quirks) & (quirk))
12656
12657         PIPE_CONF_CHECK_I(cpu_transcoder);
12658
12659         PIPE_CONF_CHECK_I(has_pch_encoder);
12660         PIPE_CONF_CHECK_I(fdi_lanes);
12661         PIPE_CONF_CHECK_M_N(fdi_m_n);
12662
12663         PIPE_CONF_CHECK_I(has_dp_encoder);
12664         PIPE_CONF_CHECK_I(lane_count);
12665
12666         if (INTEL_INFO(dev)->gen < 8) {
12667                 PIPE_CONF_CHECK_M_N(dp_m_n);
12668
12669                 if (current_config->has_drrs)
12670                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12671         } else
12672                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12673
12674         PIPE_CONF_CHECK_I(has_dsi_encoder);
12675
12676         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12677         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12678         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12679         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12680         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12681         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12682
12683         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12684         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12685         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12686         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12687         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12688         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12689
12690         PIPE_CONF_CHECK_I(pixel_multiplier);
12691         PIPE_CONF_CHECK_I(has_hdmi_sink);
12692         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12693             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12694                 PIPE_CONF_CHECK_I(limited_color_range);
12695         PIPE_CONF_CHECK_I(has_infoframe);
12696
12697         PIPE_CONF_CHECK_I(has_audio);
12698
12699         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12700                               DRM_MODE_FLAG_INTERLACE);
12701
12702         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12703                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12704                                       DRM_MODE_FLAG_PHSYNC);
12705                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12706                                       DRM_MODE_FLAG_NHSYNC);
12707                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12708                                       DRM_MODE_FLAG_PVSYNC);
12709                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12710                                       DRM_MODE_FLAG_NVSYNC);
12711         }
12712
12713         PIPE_CONF_CHECK_X(gmch_pfit.control);
12714         /* pfit ratios are autocomputed by the hw on gen4+ */
12715         if (INTEL_INFO(dev)->gen < 4)
12716                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
12717         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12718
12719         if (!adjust) {
12720                 PIPE_CONF_CHECK_I(pipe_src_w);
12721                 PIPE_CONF_CHECK_I(pipe_src_h);
12722
12723                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12724                 if (current_config->pch_pfit.enabled) {
12725                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12726                         PIPE_CONF_CHECK_X(pch_pfit.size);
12727                 }
12728
12729                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12730         }
12731
12732         /* BDW+ don't expose a synchronous way to read the state */
12733         if (IS_HASWELL(dev))
12734                 PIPE_CONF_CHECK_I(ips_enabled);
12735
12736         PIPE_CONF_CHECK_I(double_wide);
12737
12738         PIPE_CONF_CHECK_X(ddi_pll_sel);
12739
12740         PIPE_CONF_CHECK_P(shared_dpll);
12741         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12742         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12743         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12744         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12745         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12746         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12747         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12748         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12749         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12750
12751         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12752         PIPE_CONF_CHECK_X(dsi_pll.div);
12753
12754         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12755                 PIPE_CONF_CHECK_I(pipe_bpp);
12756
12757         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12758         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12759
12760 #undef PIPE_CONF_CHECK_X
12761 #undef PIPE_CONF_CHECK_I
12762 #undef PIPE_CONF_CHECK_P
12763 #undef PIPE_CONF_CHECK_FLAGS
12764 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12765 #undef PIPE_CONF_QUIRK
12766 #undef INTEL_ERR_OR_DBG_KMS
12767
12768         return ret;
12769 }
12770
12771 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12772                                            const struct intel_crtc_state *pipe_config)
12773 {
12774         if (pipe_config->has_pch_encoder) {
12775                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12776                                                             &pipe_config->fdi_m_n);
12777                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12778
12779                 /*
12780                  * FDI already provided one idea for the dotclock.
12781                  * Yell if the encoder disagrees.
12782                  */
12783                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12784                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12785                      fdi_dotclock, dotclock);
12786         }
12787 }
12788
12789 static void verify_wm_state(struct drm_crtc *crtc,
12790                             struct drm_crtc_state *new_state)
12791 {
12792         struct drm_device *dev = crtc->dev;
12793         struct drm_i915_private *dev_priv = dev->dev_private;
12794         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12795         struct skl_ddb_entry *hw_entry, *sw_entry;
12796         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12797         const enum pipe pipe = intel_crtc->pipe;
12798         int plane;
12799
12800         if (INTEL_INFO(dev)->gen < 9 || !new_state->active)
12801                 return;
12802
12803         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12804         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12805
12806         /* planes */
12807         for_each_plane(dev_priv, pipe, plane) {
12808                 hw_entry = &hw_ddb.plane[pipe][plane];
12809                 sw_entry = &sw_ddb->plane[pipe][plane];
12810
12811                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12812                         continue;
12813
12814                 DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12815                           "(expected (%u,%u), found (%u,%u))\n",
12816                           pipe_name(pipe), plane + 1,
12817                           sw_entry->start, sw_entry->end,
12818                           hw_entry->start, hw_entry->end);
12819         }
12820
12821         /* cursor */
12822         hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12823         sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12824
12825         if (!skl_ddb_entry_equal(hw_entry, sw_entry)) {
12826                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12827                           "(expected (%u,%u), found (%u,%u))\n",
12828                           pipe_name(pipe),
12829                           sw_entry->start, sw_entry->end,
12830                           hw_entry->start, hw_entry->end);
12831         }
12832 }
12833
12834 static void
12835 verify_connector_state(struct drm_device *dev, struct drm_crtc *crtc)
12836 {
12837         struct drm_connector *connector;
12838
12839         drm_for_each_connector(connector, dev) {
12840                 struct drm_encoder *encoder = connector->encoder;
12841                 struct drm_connector_state *state = connector->state;
12842
12843                 if (state->crtc != crtc)
12844                         continue;
12845
12846                 intel_connector_verify_state(to_intel_connector(connector));
12847
12848                 I915_STATE_WARN(state->best_encoder != encoder,
12849                      "connector's atomic encoder doesn't match legacy encoder\n");
12850         }
12851 }
12852
12853 static void
12854 verify_encoder_state(struct drm_device *dev)
12855 {
12856         struct intel_encoder *encoder;
12857         struct intel_connector *connector;
12858
12859         for_each_intel_encoder(dev, encoder) {
12860                 bool enabled = false;
12861                 enum pipe pipe;
12862
12863                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12864                               encoder->base.base.id,
12865                               encoder->base.name);
12866
12867                 for_each_intel_connector(dev, connector) {
12868                         if (connector->base.state->best_encoder != &encoder->base)
12869                                 continue;
12870                         enabled = true;
12871
12872                         I915_STATE_WARN(connector->base.state->crtc !=
12873                                         encoder->base.crtc,
12874                              "connector's crtc doesn't match encoder crtc\n");
12875                 }
12876
12877                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12878                      "encoder's enabled state mismatch "
12879                      "(expected %i, found %i)\n",
12880                      !!encoder->base.crtc, enabled);
12881
12882                 if (!encoder->base.crtc) {
12883                         bool active;
12884
12885                         active = encoder->get_hw_state(encoder, &pipe);
12886                         I915_STATE_WARN(active,
12887                              "encoder detached but still enabled on pipe %c.\n",
12888                              pipe_name(pipe));
12889                 }
12890         }
12891 }
12892
12893 static void
12894 verify_crtc_state(struct drm_crtc *crtc,
12895                   struct drm_crtc_state *old_crtc_state,
12896                   struct drm_crtc_state *new_crtc_state)
12897 {
12898         struct drm_device *dev = crtc->dev;
12899         struct drm_i915_private *dev_priv = dev->dev_private;
12900         struct intel_encoder *encoder;
12901         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12902         struct intel_crtc_state *pipe_config, *sw_config;
12903         struct drm_atomic_state *old_state;
12904         bool active;
12905
12906         old_state = old_crtc_state->state;
12907         __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12908         pipe_config = to_intel_crtc_state(old_crtc_state);
12909         memset(pipe_config, 0, sizeof(*pipe_config));
12910         pipe_config->base.crtc = crtc;
12911         pipe_config->base.state = old_state;
12912
12913         DRM_DEBUG_KMS("[CRTC:%d]\n", crtc->base.id);
12914
12915         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12916
12917         /* hw state is inconsistent with the pipe quirk */
12918         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12919             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12920                 active = new_crtc_state->active;
12921
12922         I915_STATE_WARN(new_crtc_state->active != active,
12923              "crtc active state doesn't match with hw state "
12924              "(expected %i, found %i)\n", new_crtc_state->active, active);
12925
12926         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12927              "transitional active state does not match atomic hw state "
12928              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12929
12930         for_each_encoder_on_crtc(dev, crtc, encoder) {
12931                 enum pipe pipe;
12932
12933                 active = encoder->get_hw_state(encoder, &pipe);
12934                 I915_STATE_WARN(active != new_crtc_state->active,
12935                         "[ENCODER:%i] active %i with crtc active %i\n",
12936                         encoder->base.base.id, active, new_crtc_state->active);
12937
12938                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12939                                 "Encoder connected to wrong pipe %c\n",
12940                                 pipe_name(pipe));
12941
12942                 if (active)
12943                         encoder->get_config(encoder, pipe_config);
12944         }
12945
12946         if (!new_crtc_state->active)
12947                 return;
12948
12949         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12950
12951         sw_config = to_intel_crtc_state(crtc->state);
12952         if (!intel_pipe_config_compare(dev, sw_config,
12953                                        pipe_config, false)) {
12954                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12955                 intel_dump_pipe_config(intel_crtc, pipe_config,
12956                                        "[hw state]");
12957                 intel_dump_pipe_config(intel_crtc, sw_config,
12958                                        "[sw state]");
12959         }
12960 }
12961
12962 static void
12963 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12964                          struct intel_shared_dpll *pll,
12965                          struct drm_crtc *crtc,
12966                          struct drm_crtc_state *new_state)
12967 {
12968         struct intel_dpll_hw_state dpll_hw_state;
12969         unsigned crtc_mask;
12970         bool active;
12971
12972         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12973
12974         DRM_DEBUG_KMS("%s\n", pll->name);
12975
12976         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12977
12978         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12979                 I915_STATE_WARN(!pll->on && pll->active_mask,
12980                      "pll in active use but not on in sw tracking\n");
12981                 I915_STATE_WARN(pll->on && !pll->active_mask,
12982                      "pll is on but not used by any active crtc\n");
12983                 I915_STATE_WARN(pll->on != active,
12984                      "pll on state mismatch (expected %i, found %i)\n",
12985                      pll->on, active);
12986         }
12987
12988         if (!crtc) {
12989                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
12990                                 "more active pll users than references: %x vs %x\n",
12991                                 pll->active_mask, pll->config.crtc_mask);
12992
12993                 return;
12994         }
12995
12996         crtc_mask = 1 << drm_crtc_index(crtc);
12997
12998         if (new_state->active)
12999                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
13000                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
13001                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13002         else
13003                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13004                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
13005                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
13006
13007         I915_STATE_WARN(!(pll->config.crtc_mask & crtc_mask),
13008                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
13009                         crtc_mask, pll->config.crtc_mask);
13010
13011         I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state,
13012                                           &dpll_hw_state,
13013                                           sizeof(dpll_hw_state)),
13014                         "pll hw state mismatch\n");
13015 }
13016
13017 static void
13018 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
13019                          struct drm_crtc_state *old_crtc_state,
13020                          struct drm_crtc_state *new_crtc_state)
13021 {
13022         struct drm_i915_private *dev_priv = dev->dev_private;
13023         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
13024         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
13025
13026         if (new_state->shared_dpll)
13027                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
13028
13029         if (old_state->shared_dpll &&
13030             old_state->shared_dpll != new_state->shared_dpll) {
13031                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
13032                 struct intel_shared_dpll *pll = old_state->shared_dpll;
13033
13034                 I915_STATE_WARN(pll->active_mask & crtc_mask,
13035                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
13036                                 pipe_name(drm_crtc_index(crtc)));
13037                 I915_STATE_WARN(pll->config.crtc_mask & crtc_mask,
13038                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
13039                                 pipe_name(drm_crtc_index(crtc)));
13040         }
13041 }
13042
13043 static void
13044 intel_modeset_verify_crtc(struct drm_crtc *crtc,
13045                          struct drm_crtc_state *old_state,
13046                          struct drm_crtc_state *new_state)
13047 {
13048         if (!needs_modeset(new_state) &&
13049             !to_intel_crtc_state(new_state)->update_pipe)
13050                 return;
13051
13052         verify_wm_state(crtc, new_state);
13053         verify_connector_state(crtc->dev, crtc);
13054         verify_crtc_state(crtc, old_state, new_state);
13055         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
13056 }
13057
13058 static void
13059 verify_disabled_dpll_state(struct drm_device *dev)
13060 {
13061         struct drm_i915_private *dev_priv = dev->dev_private;
13062         int i;
13063
13064         for (i = 0; i < dev_priv->num_shared_dpll; i++)
13065                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
13066 }
13067
13068 static void
13069 intel_modeset_verify_disabled(struct drm_device *dev)
13070 {
13071         verify_encoder_state(dev);
13072         verify_connector_state(dev, NULL);
13073         verify_disabled_dpll_state(dev);
13074 }
13075
13076 static void update_scanline_offset(struct intel_crtc *crtc)
13077 {
13078         struct drm_device *dev = crtc->base.dev;
13079
13080         /*
13081          * The scanline counter increments at the leading edge of hsync.
13082          *
13083          * On most platforms it starts counting from vtotal-1 on the
13084          * first active line. That means the scanline counter value is
13085          * always one less than what we would expect. Ie. just after
13086          * start of vblank, which also occurs at start of hsync (on the
13087          * last active line), the scanline counter will read vblank_start-1.
13088          *
13089          * On gen2 the scanline counter starts counting from 1 instead
13090          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13091          * to keep the value positive), instead of adding one.
13092          *
13093          * On HSW+ the behaviour of the scanline counter depends on the output
13094          * type. For DP ports it behaves like most other platforms, but on HDMI
13095          * there's an extra 1 line difference. So we need to add two instead of
13096          * one to the value.
13097          */
13098         if (IS_GEN2(dev)) {
13099                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13100                 int vtotal;
13101
13102                 vtotal = adjusted_mode->crtc_vtotal;
13103                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13104                         vtotal /= 2;
13105
13106                 crtc->scanline_offset = vtotal - 1;
13107         } else if (HAS_DDI(dev) &&
13108                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13109                 crtc->scanline_offset = 2;
13110         } else
13111                 crtc->scanline_offset = 1;
13112 }
13113
13114 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13115 {
13116         struct drm_device *dev = state->dev;
13117         struct drm_i915_private *dev_priv = to_i915(dev);
13118         struct intel_shared_dpll_config *shared_dpll = NULL;
13119         struct drm_crtc *crtc;
13120         struct drm_crtc_state *crtc_state;
13121         int i;
13122
13123         if (!dev_priv->display.crtc_compute_clock)
13124                 return;
13125
13126         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13127                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13128                 struct intel_shared_dpll *old_dpll =
13129                         to_intel_crtc_state(crtc->state)->shared_dpll;
13130
13131                 if (!needs_modeset(crtc_state))
13132                         continue;
13133
13134                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13135
13136                 if (!old_dpll)
13137                         continue;
13138
13139                 if (!shared_dpll)
13140                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13141
13142                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13143         }
13144 }
13145
13146 /*
13147  * This implements the workaround described in the "notes" section of the mode
13148  * set sequence documentation. When going from no pipes or single pipe to
13149  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13150  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13151  */
13152 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13153 {
13154         struct drm_crtc_state *crtc_state;
13155         struct intel_crtc *intel_crtc;
13156         struct drm_crtc *crtc;
13157         struct intel_crtc_state *first_crtc_state = NULL;
13158         struct intel_crtc_state *other_crtc_state = NULL;
13159         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13160         int i;
13161
13162         /* look at all crtc's that are going to be enabled in during modeset */
13163         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13164                 intel_crtc = to_intel_crtc(crtc);
13165
13166                 if (!crtc_state->active || !needs_modeset(crtc_state))
13167                         continue;
13168
13169                 if (first_crtc_state) {
13170                         other_crtc_state = to_intel_crtc_state(crtc_state);
13171                         break;
13172                 } else {
13173                         first_crtc_state = to_intel_crtc_state(crtc_state);
13174                         first_pipe = intel_crtc->pipe;
13175                 }
13176         }
13177
13178         /* No workaround needed? */
13179         if (!first_crtc_state)
13180                 return 0;
13181
13182         /* w/a possibly needed, check how many crtc's are already enabled. */
13183         for_each_intel_crtc(state->dev, intel_crtc) {
13184                 struct intel_crtc_state *pipe_config;
13185
13186                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13187                 if (IS_ERR(pipe_config))
13188                         return PTR_ERR(pipe_config);
13189
13190                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13191
13192                 if (!pipe_config->base.active ||
13193                     needs_modeset(&pipe_config->base))
13194                         continue;
13195
13196                 /* 2 or more enabled crtcs means no need for w/a */
13197                 if (enabled_pipe != INVALID_PIPE)
13198                         return 0;
13199
13200                 enabled_pipe = intel_crtc->pipe;
13201         }
13202
13203         if (enabled_pipe != INVALID_PIPE)
13204                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13205         else if (other_crtc_state)
13206                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13207
13208         return 0;
13209 }
13210
13211 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13212 {
13213         struct drm_crtc *crtc;
13214         struct drm_crtc_state *crtc_state;
13215         int ret = 0;
13216
13217         /* add all active pipes to the state */
13218         for_each_crtc(state->dev, crtc) {
13219                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13220                 if (IS_ERR(crtc_state))
13221                         return PTR_ERR(crtc_state);
13222
13223                 if (!crtc_state->active || needs_modeset(crtc_state))
13224                         continue;
13225
13226                 crtc_state->mode_changed = true;
13227
13228                 ret = drm_atomic_add_affected_connectors(state, crtc);
13229                 if (ret)
13230                         break;
13231
13232                 ret = drm_atomic_add_affected_planes(state, crtc);
13233                 if (ret)
13234                         break;
13235         }
13236
13237         return ret;
13238 }
13239
13240 static int intel_modeset_checks(struct drm_atomic_state *state)
13241 {
13242         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13243         struct drm_i915_private *dev_priv = state->dev->dev_private;
13244         struct drm_crtc *crtc;
13245         struct drm_crtc_state *crtc_state;
13246         int ret = 0, i;
13247
13248         if (!check_digital_port_conflicts(state)) {
13249                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13250                 return -EINVAL;
13251         }
13252
13253         intel_state->modeset = true;
13254         intel_state->active_crtcs = dev_priv->active_crtcs;
13255
13256         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13257                 if (crtc_state->active)
13258                         intel_state->active_crtcs |= 1 << i;
13259                 else
13260                         intel_state->active_crtcs &= ~(1 << i);
13261
13262                 if (crtc_state->active != crtc->state->active)
13263                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
13264         }
13265
13266         /*
13267          * See if the config requires any additional preparation, e.g.
13268          * to adjust global state with pipes off.  We need to do this
13269          * here so we can get the modeset_pipe updated config for the new
13270          * mode set on this crtc.  For other crtcs we need to use the
13271          * adjusted_mode bits in the crtc directly.
13272          */
13273         if (dev_priv->display.modeset_calc_cdclk) {
13274                 ret = dev_priv->display.modeset_calc_cdclk(state);
13275
13276                 if (!ret && intel_state->dev_cdclk != dev_priv->cdclk_freq)
13277                         ret = intel_modeset_all_pipes(state);
13278
13279                 if (ret < 0)
13280                         return ret;
13281
13282                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13283                               intel_state->cdclk, intel_state->dev_cdclk);
13284         } else
13285                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13286
13287         intel_modeset_clear_plls(state);
13288
13289         if (IS_HASWELL(dev_priv))
13290                 return haswell_mode_set_planes_workaround(state);
13291
13292         return 0;
13293 }
13294
13295 /*
13296  * Handle calculation of various watermark data at the end of the atomic check
13297  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13298  * handlers to ensure that all derived state has been updated.
13299  */
13300 static int calc_watermark_data(struct drm_atomic_state *state)
13301 {
13302         struct drm_device *dev = state->dev;
13303         struct drm_i915_private *dev_priv = to_i915(dev);
13304
13305         /* Is there platform-specific watermark information to calculate? */
13306         if (dev_priv->display.compute_global_watermarks)
13307                 return dev_priv->display.compute_global_watermarks(state);
13308
13309         return 0;
13310 }
13311
13312 /**
13313  * intel_atomic_check - validate state object
13314  * @dev: drm device
13315  * @state: state to validate
13316  */
13317 static int intel_atomic_check(struct drm_device *dev,
13318                               struct drm_atomic_state *state)
13319 {
13320         struct drm_i915_private *dev_priv = to_i915(dev);
13321         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13322         struct drm_crtc *crtc;
13323         struct drm_crtc_state *crtc_state;
13324         int ret, i;
13325         bool any_ms = false;
13326
13327         ret = drm_atomic_helper_check_modeset(dev, state);
13328         if (ret)
13329                 return ret;
13330
13331         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13332                 struct intel_crtc_state *pipe_config =
13333                         to_intel_crtc_state(crtc_state);
13334
13335                 /* Catch I915_MODE_FLAG_INHERITED */
13336                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13337                         crtc_state->mode_changed = true;
13338
13339                 if (!needs_modeset(crtc_state))
13340                         continue;
13341
13342                 if (!crtc_state->enable) {
13343                         any_ms = true;
13344                         continue;
13345                 }
13346
13347                 /* FIXME: For only active_changed we shouldn't need to do any
13348                  * state recomputation at all. */
13349
13350                 ret = drm_atomic_add_affected_connectors(state, crtc);
13351                 if (ret)
13352                         return ret;
13353
13354                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13355                 if (ret) {
13356                         intel_dump_pipe_config(to_intel_crtc(crtc),
13357                                                pipe_config, "[failed]");
13358                         return ret;
13359                 }
13360
13361                 if (i915.fastboot &&
13362                     intel_pipe_config_compare(dev,
13363                                         to_intel_crtc_state(crtc->state),
13364                                         pipe_config, true)) {
13365                         crtc_state->mode_changed = false;
13366                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13367                 }
13368
13369                 if (needs_modeset(crtc_state))
13370                         any_ms = true;
13371
13372                 ret = drm_atomic_add_affected_planes(state, crtc);
13373                 if (ret)
13374                         return ret;
13375
13376                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13377                                        needs_modeset(crtc_state) ?
13378                                        "[modeset]" : "[fastset]");
13379         }
13380
13381         if (any_ms) {
13382                 ret = intel_modeset_checks(state);
13383
13384                 if (ret)
13385                         return ret;
13386         } else
13387                 intel_state->cdclk = dev_priv->cdclk_freq;
13388
13389         ret = drm_atomic_helper_check_planes(dev, state);
13390         if (ret)
13391                 return ret;
13392
13393         intel_fbc_choose_crtc(dev_priv, state);
13394         return calc_watermark_data(state);
13395 }
13396
13397 static int intel_atomic_prepare_commit(struct drm_device *dev,
13398                                        struct drm_atomic_state *state,
13399                                        bool nonblock)
13400 {
13401         struct drm_i915_private *dev_priv = dev->dev_private;
13402         struct drm_plane_state *plane_state;
13403         struct drm_crtc_state *crtc_state;
13404         struct drm_plane *plane;
13405         struct drm_crtc *crtc;
13406         int i, ret;
13407
13408         if (nonblock) {
13409                 DRM_DEBUG_KMS("i915 does not yet support nonblocking commit\n");
13410                 return -EINVAL;
13411         }
13412
13413         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13414                 if (state->legacy_cursor_update)
13415                         continue;
13416
13417                 ret = intel_crtc_wait_for_pending_flips(crtc);
13418                 if (ret)
13419                         return ret;
13420
13421                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13422                         flush_workqueue(dev_priv->wq);
13423         }
13424
13425         ret = mutex_lock_interruptible(&dev->struct_mutex);
13426         if (ret)
13427                 return ret;
13428
13429         ret = drm_atomic_helper_prepare_planes(dev, state);
13430         mutex_unlock(&dev->struct_mutex);
13431
13432         if (!ret && !nonblock) {
13433                 for_each_plane_in_state(state, plane, plane_state, i) {
13434                         struct intel_plane_state *intel_plane_state =
13435                                 to_intel_plane_state(plane_state);
13436
13437                         if (!intel_plane_state->wait_req)
13438                                 continue;
13439
13440                         ret = __i915_wait_request(intel_plane_state->wait_req,
13441                                                   true, NULL, NULL);
13442                         if (ret) {
13443                                 /* Any hang should be swallowed by the wait */
13444                                 WARN_ON(ret == -EIO);
13445                                 mutex_lock(&dev->struct_mutex);
13446                                 drm_atomic_helper_cleanup_planes(dev, state);
13447                                 mutex_unlock(&dev->struct_mutex);
13448                                 break;
13449                         }
13450                 }
13451         }
13452
13453         return ret;
13454 }
13455
13456 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13457                                           struct drm_i915_private *dev_priv,
13458                                           unsigned crtc_mask)
13459 {
13460         unsigned last_vblank_count[I915_MAX_PIPES];
13461         enum pipe pipe;
13462         int ret;
13463
13464         if (!crtc_mask)
13465                 return;
13466
13467         for_each_pipe(dev_priv, pipe) {
13468                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13469
13470                 if (!((1 << pipe) & crtc_mask))
13471                         continue;
13472
13473                 ret = drm_crtc_vblank_get(crtc);
13474                 if (WARN_ON(ret != 0)) {
13475                         crtc_mask &= ~(1 << pipe);
13476                         continue;
13477                 }
13478
13479                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13480         }
13481
13482         for_each_pipe(dev_priv, pipe) {
13483                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13484                 long lret;
13485
13486                 if (!((1 << pipe) & crtc_mask))
13487                         continue;
13488
13489                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13490                                 last_vblank_count[pipe] !=
13491                                         drm_crtc_vblank_count(crtc),
13492                                 msecs_to_jiffies(50));
13493
13494                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
13495
13496                 drm_crtc_vblank_put(crtc);
13497         }
13498 }
13499
13500 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13501 {
13502         /* fb updated, need to unpin old fb */
13503         if (crtc_state->fb_changed)
13504                 return true;
13505
13506         /* wm changes, need vblank before final wm's */
13507         if (crtc_state->update_wm_post)
13508                 return true;
13509
13510         /*
13511          * cxsr is re-enabled after vblank.
13512          * This is already handled by crtc_state->update_wm_post,
13513          * but added for clarity.
13514          */
13515         if (crtc_state->disable_cxsr)
13516                 return true;
13517
13518         return false;
13519 }
13520
13521 /**
13522  * intel_atomic_commit - commit validated state object
13523  * @dev: DRM device
13524  * @state: the top-level driver state object
13525  * @nonblock: nonblocking commit
13526  *
13527  * This function commits a top-level state object that has been validated
13528  * with drm_atomic_helper_check().
13529  *
13530  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13531  * we can only handle plane-related operations and do not yet support
13532  * nonblocking commit.
13533  *
13534  * RETURNS
13535  * Zero for success or -errno.
13536  */
13537 static int intel_atomic_commit(struct drm_device *dev,
13538                                struct drm_atomic_state *state,
13539                                bool nonblock)
13540 {
13541         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13542         struct drm_i915_private *dev_priv = dev->dev_private;
13543         struct drm_crtc_state *old_crtc_state;
13544         struct drm_crtc *crtc;
13545         struct intel_crtc_state *intel_cstate;
13546         int ret = 0, i;
13547         bool hw_check = intel_state->modeset;
13548         unsigned long put_domains[I915_MAX_PIPES] = {};
13549         unsigned crtc_vblank_mask = 0;
13550
13551         ret = intel_atomic_prepare_commit(dev, state, nonblock);
13552         if (ret) {
13553                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13554                 return ret;
13555         }
13556
13557         drm_atomic_helper_swap_state(dev, state);
13558         dev_priv->wm.distrust_bios_wm = false;
13559         dev_priv->wm.skl_results = intel_state->wm_results;
13560         intel_shared_dpll_commit(state);
13561
13562         if (intel_state->modeset) {
13563                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13564                        sizeof(intel_state->min_pixclk));
13565                 dev_priv->active_crtcs = intel_state->active_crtcs;
13566                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13567
13568                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13569         }
13570
13571         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13572                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13573
13574                 if (needs_modeset(crtc->state) ||
13575                     to_intel_crtc_state(crtc->state)->update_pipe) {
13576                         hw_check = true;
13577
13578                         put_domains[to_intel_crtc(crtc)->pipe] =
13579                                 modeset_get_crtc_power_domains(crtc,
13580                                         to_intel_crtc_state(crtc->state));
13581                 }
13582
13583                 if (!needs_modeset(crtc->state))
13584                         continue;
13585
13586                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13587
13588                 if (old_crtc_state->active) {
13589                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13590                         dev_priv->display.crtc_disable(crtc);
13591                         intel_crtc->active = false;
13592                         intel_fbc_disable(intel_crtc);
13593                         intel_disable_shared_dpll(intel_crtc);
13594
13595                         /*
13596                          * Underruns don't always raise
13597                          * interrupts, so check manually.
13598                          */
13599                         intel_check_cpu_fifo_underruns(dev_priv);
13600                         intel_check_pch_fifo_underruns(dev_priv);
13601
13602                         if (!crtc->state->active)
13603                                 intel_update_watermarks(crtc);
13604                 }
13605         }
13606
13607         /* Only after disabling all output pipelines that will be changed can we
13608          * update the the output configuration. */
13609         intel_modeset_update_crtc_state(state);
13610
13611         if (intel_state->modeset) {
13612                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13613
13614                 if (dev_priv->display.modeset_commit_cdclk &&
13615                     intel_state->dev_cdclk != dev_priv->cdclk_freq)
13616                         dev_priv->display.modeset_commit_cdclk(state);
13617
13618                 intel_modeset_verify_disabled(dev);
13619         }
13620
13621         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13622         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13623                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13624                 bool modeset = needs_modeset(crtc->state);
13625                 struct intel_crtc_state *pipe_config =
13626                         to_intel_crtc_state(crtc->state);
13627                 bool update_pipe = !modeset && pipe_config->update_pipe;
13628
13629                 if (modeset && crtc->state->active) {
13630                         update_scanline_offset(to_intel_crtc(crtc));
13631                         dev_priv->display.crtc_enable(crtc);
13632                 }
13633
13634                 if (!modeset)
13635                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13636
13637                 if (crtc->state->active &&
13638                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13639                         intel_fbc_enable(intel_crtc);
13640
13641                 if (crtc->state->active &&
13642                     (crtc->state->planes_changed || update_pipe))
13643                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13644
13645                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13646                         crtc_vblank_mask |= 1 << i;
13647         }
13648
13649         /* FIXME: add subpixel order */
13650
13651         if (!state->legacy_cursor_update)
13652                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13653
13654         /*
13655          * Now that the vblank has passed, we can go ahead and program the
13656          * optimal watermarks on platforms that need two-step watermark
13657          * programming.
13658          *
13659          * TODO: Move this (and other cleanup) to an async worker eventually.
13660          */
13661         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13662                 intel_cstate = to_intel_crtc_state(crtc->state);
13663
13664                 if (dev_priv->display.optimize_watermarks)
13665                         dev_priv->display.optimize_watermarks(intel_cstate);
13666         }
13667
13668         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13669                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13670
13671                 if (put_domains[i])
13672                         modeset_put_power_domains(dev_priv, put_domains[i]);
13673
13674                 intel_modeset_verify_crtc(crtc, old_crtc_state, crtc->state);
13675         }
13676
13677         if (intel_state->modeset)
13678                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13679
13680         mutex_lock(&dev->struct_mutex);
13681         drm_atomic_helper_cleanup_planes(dev, state);
13682         mutex_unlock(&dev->struct_mutex);
13683
13684         drm_atomic_state_free(state);
13685
13686         /* As one of the primary mmio accessors, KMS has a high likelihood
13687          * of triggering bugs in unclaimed access. After we finish
13688          * modesetting, see if an error has been flagged, and if so
13689          * enable debugging for the next modeset - and hope we catch
13690          * the culprit.
13691          *
13692          * XXX note that we assume display power is on at this point.
13693          * This might hold true now but we need to add pm helper to check
13694          * unclaimed only when the hardware is on, as atomic commits
13695          * can happen also when the device is completely off.
13696          */
13697         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13698
13699         return 0;
13700 }
13701
13702 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13703 {
13704         struct drm_device *dev = crtc->dev;
13705         struct drm_atomic_state *state;
13706         struct drm_crtc_state *crtc_state;
13707         int ret;
13708
13709         state = drm_atomic_state_alloc(dev);
13710         if (!state) {
13711                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13712                               crtc->base.id);
13713                 return;
13714         }
13715
13716         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13717
13718 retry:
13719         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13720         ret = PTR_ERR_OR_ZERO(crtc_state);
13721         if (!ret) {
13722                 if (!crtc_state->active)
13723                         goto out;
13724
13725                 crtc_state->mode_changed = true;
13726                 ret = drm_atomic_commit(state);
13727         }
13728
13729         if (ret == -EDEADLK) {
13730                 drm_atomic_state_clear(state);
13731                 drm_modeset_backoff(state->acquire_ctx);
13732                 goto retry;
13733         }
13734
13735         if (ret)
13736 out:
13737                 drm_atomic_state_free(state);
13738 }
13739
13740 #undef for_each_intel_crtc_masked
13741
13742 static const struct drm_crtc_funcs intel_crtc_funcs = {
13743         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13744         .set_config = drm_atomic_helper_set_config,
13745         .set_property = drm_atomic_helper_crtc_set_property,
13746         .destroy = intel_crtc_destroy,
13747         .page_flip = intel_crtc_page_flip,
13748         .atomic_duplicate_state = intel_crtc_duplicate_state,
13749         .atomic_destroy_state = intel_crtc_destroy_state,
13750 };
13751
13752 /**
13753  * intel_prepare_plane_fb - Prepare fb for usage on plane
13754  * @plane: drm plane to prepare for
13755  * @fb: framebuffer to prepare for presentation
13756  *
13757  * Prepares a framebuffer for usage on a display plane.  Generally this
13758  * involves pinning the underlying object and updating the frontbuffer tracking
13759  * bits.  Some older platforms need special physical address handling for
13760  * cursor planes.
13761  *
13762  * Must be called with struct_mutex held.
13763  *
13764  * Returns 0 on success, negative error code on failure.
13765  */
13766 int
13767 intel_prepare_plane_fb(struct drm_plane *plane,
13768                        const struct drm_plane_state *new_state)
13769 {
13770         struct drm_device *dev = plane->dev;
13771         struct drm_framebuffer *fb = new_state->fb;
13772         struct intel_plane *intel_plane = to_intel_plane(plane);
13773         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13774         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13775         int ret = 0;
13776
13777         if (!obj && !old_obj)
13778                 return 0;
13779
13780         if (old_obj) {
13781                 struct drm_crtc_state *crtc_state =
13782                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13783
13784                 /* Big Hammer, we also need to ensure that any pending
13785                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13786                  * current scanout is retired before unpinning the old
13787                  * framebuffer. Note that we rely on userspace rendering
13788                  * into the buffer attached to the pipe they are waiting
13789                  * on. If not, userspace generates a GPU hang with IPEHR
13790                  * point to the MI_WAIT_FOR_EVENT.
13791                  *
13792                  * This should only fail upon a hung GPU, in which case we
13793                  * can safely continue.
13794                  */
13795                 if (needs_modeset(crtc_state))
13796                         ret = i915_gem_object_wait_rendering(old_obj, true);
13797                 if (ret) {
13798                         /* GPU hangs should have been swallowed by the wait */
13799                         WARN_ON(ret == -EIO);
13800                         return ret;
13801                 }
13802         }
13803
13804         /* For framebuffer backed by dmabuf, wait for fence */
13805         if (obj && obj->base.dma_buf) {
13806                 long lret;
13807
13808                 lret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
13809                                                            false, true,
13810                                                            MAX_SCHEDULE_TIMEOUT);
13811                 if (lret == -ERESTARTSYS)
13812                         return lret;
13813
13814                 WARN(lret < 0, "waiting returns %li\n", lret);
13815         }
13816
13817         if (!obj) {
13818                 ret = 0;
13819         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13820             INTEL_INFO(dev)->cursor_needs_physical) {
13821                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13822                 ret = i915_gem_object_attach_phys(obj, align);
13823                 if (ret)
13824                         DRM_DEBUG_KMS("failed to attach phys object\n");
13825         } else {
13826                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13827         }
13828
13829         if (ret == 0) {
13830                 if (obj) {
13831                         struct intel_plane_state *plane_state =
13832                                 to_intel_plane_state(new_state);
13833
13834                         i915_gem_request_assign(&plane_state->wait_req,
13835                                                 obj->last_write_req);
13836                 }
13837
13838                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13839         }
13840
13841         return ret;
13842 }
13843
13844 /**
13845  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13846  * @plane: drm plane to clean up for
13847  * @fb: old framebuffer that was on plane
13848  *
13849  * Cleans up a framebuffer that has just been removed from a plane.
13850  *
13851  * Must be called with struct_mutex held.
13852  */
13853 void
13854 intel_cleanup_plane_fb(struct drm_plane *plane,
13855                        const struct drm_plane_state *old_state)
13856 {
13857         struct drm_device *dev = plane->dev;
13858         struct intel_plane *intel_plane = to_intel_plane(plane);
13859         struct intel_plane_state *old_intel_state;
13860         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
13861         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
13862
13863         old_intel_state = to_intel_plane_state(old_state);
13864
13865         if (!obj && !old_obj)
13866                 return;
13867
13868         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
13869             !INTEL_INFO(dev)->cursor_needs_physical))
13870                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
13871
13872         /* prepare_fb aborted? */
13873         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
13874             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
13875                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13876
13877         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
13878 }
13879
13880 int
13881 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13882 {
13883         int max_scale;
13884         struct drm_device *dev;
13885         struct drm_i915_private *dev_priv;
13886         int crtc_clock, cdclk;
13887
13888         if (!intel_crtc || !crtc_state->base.enable)
13889                 return DRM_PLANE_HELPER_NO_SCALING;
13890
13891         dev = intel_crtc->base.dev;
13892         dev_priv = dev->dev_private;
13893         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13894         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13895
13896         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
13897                 return DRM_PLANE_HELPER_NO_SCALING;
13898
13899         /*
13900          * skl max scale is lower of:
13901          *    close to 3 but not 3, -1 is for that purpose
13902          *            or
13903          *    cdclk/crtc_clock
13904          */
13905         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13906
13907         return max_scale;
13908 }
13909
13910 static int
13911 intel_check_primary_plane(struct drm_plane *plane,
13912                           struct intel_crtc_state *crtc_state,
13913                           struct intel_plane_state *state)
13914 {
13915         struct drm_crtc *crtc = state->base.crtc;
13916         struct drm_framebuffer *fb = state->base.fb;
13917         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13918         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13919         bool can_position = false;
13920
13921         if (INTEL_INFO(plane->dev)->gen >= 9) {
13922                 /* use scaler when colorkey is not required */
13923                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13924                         min_scale = 1;
13925                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13926                 }
13927                 can_position = true;
13928         }
13929
13930         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13931                                              &state->dst, &state->clip,
13932                                              min_scale, max_scale,
13933                                              can_position, true,
13934                                              &state->visible);
13935 }
13936
13937 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13938                                     struct drm_crtc_state *old_crtc_state)
13939 {
13940         struct drm_device *dev = crtc->dev;
13941         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13942         struct intel_crtc_state *old_intel_state =
13943                 to_intel_crtc_state(old_crtc_state);
13944         bool modeset = needs_modeset(crtc->state);
13945
13946         /* Perform vblank evasion around commit operation */
13947         intel_pipe_update_start(intel_crtc);
13948
13949         if (modeset)
13950                 return;
13951
13952         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
13953                 intel_color_set_csc(crtc->state);
13954                 intel_color_load_luts(crtc->state);
13955         }
13956
13957         if (to_intel_crtc_state(crtc->state)->update_pipe)
13958                 intel_update_pipe_config(intel_crtc, old_intel_state);
13959         else if (INTEL_INFO(dev)->gen >= 9)
13960                 skl_detach_scalers(intel_crtc);
13961 }
13962
13963 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13964                                      struct drm_crtc_state *old_crtc_state)
13965 {
13966         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13967
13968         intel_pipe_update_end(intel_crtc);
13969 }
13970
13971 /**
13972  * intel_plane_destroy - destroy a plane
13973  * @plane: plane to destroy
13974  *
13975  * Common destruction function for all types of planes (primary, cursor,
13976  * sprite).
13977  */
13978 void intel_plane_destroy(struct drm_plane *plane)
13979 {
13980         struct intel_plane *intel_plane = to_intel_plane(plane);
13981         drm_plane_cleanup(plane);
13982         kfree(intel_plane);
13983 }
13984
13985 const struct drm_plane_funcs intel_plane_funcs = {
13986         .update_plane = drm_atomic_helper_update_plane,
13987         .disable_plane = drm_atomic_helper_disable_plane,
13988         .destroy = intel_plane_destroy,
13989         .set_property = drm_atomic_helper_plane_set_property,
13990         .atomic_get_property = intel_plane_atomic_get_property,
13991         .atomic_set_property = intel_plane_atomic_set_property,
13992         .atomic_duplicate_state = intel_plane_duplicate_state,
13993         .atomic_destroy_state = intel_plane_destroy_state,
13994
13995 };
13996
13997 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13998                                                     int pipe)
13999 {
14000         struct intel_plane *primary = NULL;
14001         struct intel_plane_state *state = NULL;
14002         const uint32_t *intel_primary_formats;
14003         unsigned int num_formats;
14004         int ret;
14005
14006         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14007         if (!primary)
14008                 goto fail;
14009
14010         state = intel_create_plane_state(&primary->base);
14011         if (!state)
14012                 goto fail;
14013         primary->base.state = &state->base;
14014
14015         primary->can_scale = false;
14016         primary->max_downscale = 1;
14017         if (INTEL_INFO(dev)->gen >= 9) {
14018                 primary->can_scale = true;
14019                 state->scaler_id = -1;
14020         }
14021         primary->pipe = pipe;
14022         primary->plane = pipe;
14023         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14024         primary->check_plane = intel_check_primary_plane;
14025         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14026                 primary->plane = !pipe;
14027
14028         if (INTEL_INFO(dev)->gen >= 9) {
14029                 intel_primary_formats = skl_primary_formats;
14030                 num_formats = ARRAY_SIZE(skl_primary_formats);
14031
14032                 primary->update_plane = skylake_update_primary_plane;
14033                 primary->disable_plane = skylake_disable_primary_plane;
14034         } else if (HAS_PCH_SPLIT(dev)) {
14035                 intel_primary_formats = i965_primary_formats;
14036                 num_formats = ARRAY_SIZE(i965_primary_formats);
14037
14038                 primary->update_plane = ironlake_update_primary_plane;
14039                 primary->disable_plane = i9xx_disable_primary_plane;
14040         } else if (INTEL_INFO(dev)->gen >= 4) {
14041                 intel_primary_formats = i965_primary_formats;
14042                 num_formats = ARRAY_SIZE(i965_primary_formats);
14043
14044                 primary->update_plane = i9xx_update_primary_plane;
14045                 primary->disable_plane = i9xx_disable_primary_plane;
14046         } else {
14047                 intel_primary_formats = i8xx_primary_formats;
14048                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14049
14050                 primary->update_plane = i9xx_update_primary_plane;
14051                 primary->disable_plane = i9xx_disable_primary_plane;
14052         }
14053
14054         ret = drm_universal_plane_init(dev, &primary->base, 0,
14055                                        &intel_plane_funcs,
14056                                        intel_primary_formats, num_formats,
14057                                        DRM_PLANE_TYPE_PRIMARY, NULL);
14058         if (ret)
14059                 goto fail;
14060
14061         if (INTEL_INFO(dev)->gen >= 4)
14062                 intel_create_rotation_property(dev, primary);
14063
14064         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14065
14066         return &primary->base;
14067
14068 fail:
14069         kfree(state);
14070         kfree(primary);
14071
14072         return NULL;
14073 }
14074
14075 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14076 {
14077         if (!dev->mode_config.rotation_property) {
14078                 unsigned long flags = BIT(DRM_ROTATE_0) |
14079                         BIT(DRM_ROTATE_180);
14080
14081                 if (INTEL_INFO(dev)->gen >= 9)
14082                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14083
14084                 dev->mode_config.rotation_property =
14085                         drm_mode_create_rotation_property(dev, flags);
14086         }
14087         if (dev->mode_config.rotation_property)
14088                 drm_object_attach_property(&plane->base.base,
14089                                 dev->mode_config.rotation_property,
14090                                 plane->base.state->rotation);
14091 }
14092
14093 static int
14094 intel_check_cursor_plane(struct drm_plane *plane,
14095                          struct intel_crtc_state *crtc_state,
14096                          struct intel_plane_state *state)
14097 {
14098         struct drm_crtc *crtc = crtc_state->base.crtc;
14099         struct drm_framebuffer *fb = state->base.fb;
14100         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14101         enum pipe pipe = to_intel_plane(plane)->pipe;
14102         unsigned stride;
14103         int ret;
14104
14105         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14106                                             &state->dst, &state->clip,
14107                                             DRM_PLANE_HELPER_NO_SCALING,
14108                                             DRM_PLANE_HELPER_NO_SCALING,
14109                                             true, true, &state->visible);
14110         if (ret)
14111                 return ret;
14112
14113         /* if we want to turn off the cursor ignore width and height */
14114         if (!obj)
14115                 return 0;
14116
14117         /* Check for which cursor types we support */
14118         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14119                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14120                           state->base.crtc_w, state->base.crtc_h);
14121                 return -EINVAL;
14122         }
14123
14124         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14125         if (obj->base.size < stride * state->base.crtc_h) {
14126                 DRM_DEBUG_KMS("buffer is too small\n");
14127                 return -ENOMEM;
14128         }
14129
14130         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14131                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14132                 return -EINVAL;
14133         }
14134
14135         /*
14136          * There's something wrong with the cursor on CHV pipe C.
14137          * If it straddles the left edge of the screen then
14138          * moving it away from the edge or disabling it often
14139          * results in a pipe underrun, and often that can lead to
14140          * dead pipe (constant underrun reported, and it scans
14141          * out just a solid color). To recover from that, the
14142          * display power well must be turned off and on again.
14143          * Refuse the put the cursor into that compromised position.
14144          */
14145         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14146             state->visible && state->base.crtc_x < 0) {
14147                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14148                 return -EINVAL;
14149         }
14150
14151         return 0;
14152 }
14153
14154 static void
14155 intel_disable_cursor_plane(struct drm_plane *plane,
14156                            struct drm_crtc *crtc)
14157 {
14158         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14159
14160         intel_crtc->cursor_addr = 0;
14161         intel_crtc_update_cursor(crtc, NULL);
14162 }
14163
14164 static void
14165 intel_update_cursor_plane(struct drm_plane *plane,
14166                           const struct intel_crtc_state *crtc_state,
14167                           const struct intel_plane_state *state)
14168 {
14169         struct drm_crtc *crtc = crtc_state->base.crtc;
14170         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14171         struct drm_device *dev = plane->dev;
14172         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14173         uint32_t addr;
14174
14175         if (!obj)
14176                 addr = 0;
14177         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14178                 addr = i915_gem_obj_ggtt_offset(obj);
14179         else
14180                 addr = obj->phys_handle->busaddr;
14181
14182         intel_crtc->cursor_addr = addr;
14183         intel_crtc_update_cursor(crtc, state);
14184 }
14185
14186 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14187                                                    int pipe)
14188 {
14189         struct intel_plane *cursor = NULL;
14190         struct intel_plane_state *state = NULL;
14191         int ret;
14192
14193         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14194         if (!cursor)
14195                 goto fail;
14196
14197         state = intel_create_plane_state(&cursor->base);
14198         if (!state)
14199                 goto fail;
14200         cursor->base.state = &state->base;
14201
14202         cursor->can_scale = false;
14203         cursor->max_downscale = 1;
14204         cursor->pipe = pipe;
14205         cursor->plane = pipe;
14206         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14207         cursor->check_plane = intel_check_cursor_plane;
14208         cursor->update_plane = intel_update_cursor_plane;
14209         cursor->disable_plane = intel_disable_cursor_plane;
14210
14211         ret = drm_universal_plane_init(dev, &cursor->base, 0,
14212                                        &intel_plane_funcs,
14213                                        intel_cursor_formats,
14214                                        ARRAY_SIZE(intel_cursor_formats),
14215                                        DRM_PLANE_TYPE_CURSOR, NULL);
14216         if (ret)
14217                 goto fail;
14218
14219         if (INTEL_INFO(dev)->gen >= 4) {
14220                 if (!dev->mode_config.rotation_property)
14221                         dev->mode_config.rotation_property =
14222                                 drm_mode_create_rotation_property(dev,
14223                                                         BIT(DRM_ROTATE_0) |
14224                                                         BIT(DRM_ROTATE_180));
14225                 if (dev->mode_config.rotation_property)
14226                         drm_object_attach_property(&cursor->base.base,
14227                                 dev->mode_config.rotation_property,
14228                                 state->base.rotation);
14229         }
14230
14231         if (INTEL_INFO(dev)->gen >=9)
14232                 state->scaler_id = -1;
14233
14234         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14235
14236         return &cursor->base;
14237
14238 fail:
14239         kfree(state);
14240         kfree(cursor);
14241
14242         return NULL;
14243 }
14244
14245 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14246         struct intel_crtc_state *crtc_state)
14247 {
14248         int i;
14249         struct intel_scaler *intel_scaler;
14250         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14251
14252         for (i = 0; i < intel_crtc->num_scalers; i++) {
14253                 intel_scaler = &scaler_state->scalers[i];
14254                 intel_scaler->in_use = 0;
14255                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14256         }
14257
14258         scaler_state->scaler_id = -1;
14259 }
14260
14261 static void intel_crtc_init(struct drm_device *dev, int pipe)
14262 {
14263         struct drm_i915_private *dev_priv = dev->dev_private;
14264         struct intel_crtc *intel_crtc;
14265         struct intel_crtc_state *crtc_state = NULL;
14266         struct drm_plane *primary = NULL;
14267         struct drm_plane *cursor = NULL;
14268         int ret;
14269
14270         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14271         if (intel_crtc == NULL)
14272                 return;
14273
14274         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14275         if (!crtc_state)
14276                 goto fail;
14277         intel_crtc->config = crtc_state;
14278         intel_crtc->base.state = &crtc_state->base;
14279         crtc_state->base.crtc = &intel_crtc->base;
14280
14281         /* initialize shared scalers */
14282         if (INTEL_INFO(dev)->gen >= 9) {
14283                 if (pipe == PIPE_C)
14284                         intel_crtc->num_scalers = 1;
14285                 else
14286                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14287
14288                 skl_init_scalers(dev, intel_crtc, crtc_state);
14289         }
14290
14291         primary = intel_primary_plane_create(dev, pipe);
14292         if (!primary)
14293                 goto fail;
14294
14295         cursor = intel_cursor_plane_create(dev, pipe);
14296         if (!cursor)
14297                 goto fail;
14298
14299         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14300                                         cursor, &intel_crtc_funcs, NULL);
14301         if (ret)
14302                 goto fail;
14303
14304         /*
14305          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14306          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14307          */
14308         intel_crtc->pipe = pipe;
14309         intel_crtc->plane = pipe;
14310         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14311                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14312                 intel_crtc->plane = !pipe;
14313         }
14314
14315         intel_crtc->cursor_base = ~0;
14316         intel_crtc->cursor_cntl = ~0;
14317         intel_crtc->cursor_size = ~0;
14318
14319         intel_crtc->wm.cxsr_allowed = true;
14320
14321         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14322                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14323         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14324         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14325
14326         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14327
14328         intel_color_init(&intel_crtc->base);
14329
14330         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14331         return;
14332
14333 fail:
14334         if (primary)
14335                 drm_plane_cleanup(primary);
14336         if (cursor)
14337                 drm_plane_cleanup(cursor);
14338         kfree(crtc_state);
14339         kfree(intel_crtc);
14340 }
14341
14342 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14343 {
14344         struct drm_encoder *encoder = connector->base.encoder;
14345         struct drm_device *dev = connector->base.dev;
14346
14347         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14348
14349         if (!encoder || WARN_ON(!encoder->crtc))
14350                 return INVALID_PIPE;
14351
14352         return to_intel_crtc(encoder->crtc)->pipe;
14353 }
14354
14355 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14356                                 struct drm_file *file)
14357 {
14358         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14359         struct drm_crtc *drmmode_crtc;
14360         struct intel_crtc *crtc;
14361
14362         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14363
14364         if (!drmmode_crtc) {
14365                 DRM_ERROR("no such CRTC id\n");
14366                 return -ENOENT;
14367         }
14368
14369         crtc = to_intel_crtc(drmmode_crtc);
14370         pipe_from_crtc_id->pipe = crtc->pipe;
14371
14372         return 0;
14373 }
14374
14375 static int intel_encoder_clones(struct intel_encoder *encoder)
14376 {
14377         struct drm_device *dev = encoder->base.dev;
14378         struct intel_encoder *source_encoder;
14379         int index_mask = 0;
14380         int entry = 0;
14381
14382         for_each_intel_encoder(dev, source_encoder) {
14383                 if (encoders_cloneable(encoder, source_encoder))
14384                         index_mask |= (1 << entry);
14385
14386                 entry++;
14387         }
14388
14389         return index_mask;
14390 }
14391
14392 static bool has_edp_a(struct drm_device *dev)
14393 {
14394         struct drm_i915_private *dev_priv = dev->dev_private;
14395
14396         if (!IS_MOBILE(dev))
14397                 return false;
14398
14399         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14400                 return false;
14401
14402         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14403                 return false;
14404
14405         return true;
14406 }
14407
14408 static bool intel_crt_present(struct drm_device *dev)
14409 {
14410         struct drm_i915_private *dev_priv = dev->dev_private;
14411
14412         if (INTEL_INFO(dev)->gen >= 9)
14413                 return false;
14414
14415         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14416                 return false;
14417
14418         if (IS_CHERRYVIEW(dev))
14419                 return false;
14420
14421         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14422                 return false;
14423
14424         /* DDI E can't be used if DDI A requires 4 lanes */
14425         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14426                 return false;
14427
14428         if (!dev_priv->vbt.int_crt_support)
14429                 return false;
14430
14431         return true;
14432 }
14433
14434 static void intel_setup_outputs(struct drm_device *dev)
14435 {
14436         struct drm_i915_private *dev_priv = dev->dev_private;
14437         struct intel_encoder *encoder;
14438         bool dpd_is_edp = false;
14439
14440         intel_lvds_init(dev);
14441
14442         if (intel_crt_present(dev))
14443                 intel_crt_init(dev);
14444
14445         if (IS_BROXTON(dev)) {
14446                 /*
14447                  * FIXME: Broxton doesn't support port detection via the
14448                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14449                  * detect the ports.
14450                  */
14451                 intel_ddi_init(dev, PORT_A);
14452                 intel_ddi_init(dev, PORT_B);
14453                 intel_ddi_init(dev, PORT_C);
14454
14455                 intel_dsi_init(dev);
14456         } else if (HAS_DDI(dev)) {
14457                 int found;
14458
14459                 /*
14460                  * Haswell uses DDI functions to detect digital outputs.
14461                  * On SKL pre-D0 the strap isn't connected, so we assume
14462                  * it's there.
14463                  */
14464                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14465                 /* WaIgnoreDDIAStrap: skl */
14466                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14467                         intel_ddi_init(dev, PORT_A);
14468
14469                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14470                  * register */
14471                 found = I915_READ(SFUSE_STRAP);
14472
14473                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14474                         intel_ddi_init(dev, PORT_B);
14475                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14476                         intel_ddi_init(dev, PORT_C);
14477                 if (found & SFUSE_STRAP_DDID_DETECTED)
14478                         intel_ddi_init(dev, PORT_D);
14479                 /*
14480                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14481                  */
14482                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14483                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14484                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14485                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14486                         intel_ddi_init(dev, PORT_E);
14487
14488         } else if (HAS_PCH_SPLIT(dev)) {
14489                 int found;
14490                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14491
14492                 if (has_edp_a(dev))
14493                         intel_dp_init(dev, DP_A, PORT_A);
14494
14495                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14496                         /* PCH SDVOB multiplex with HDMIB */
14497                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14498                         if (!found)
14499                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14500                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14501                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14502                 }
14503
14504                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14505                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14506
14507                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14508                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14509
14510                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14511                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14512
14513                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14514                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14515         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14516                 /*
14517                  * The DP_DETECTED bit is the latched state of the DDC
14518                  * SDA pin at boot. However since eDP doesn't require DDC
14519                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14520                  * eDP ports may have been muxed to an alternate function.
14521                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14522                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14523                  * detect eDP ports.
14524                  */
14525                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14526                     !intel_dp_is_edp(dev, PORT_B))
14527                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14528                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14529                     intel_dp_is_edp(dev, PORT_B))
14530                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14531
14532                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14533                     !intel_dp_is_edp(dev, PORT_C))
14534                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14535                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14536                     intel_dp_is_edp(dev, PORT_C))
14537                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14538
14539                 if (IS_CHERRYVIEW(dev)) {
14540                         /* eDP not supported on port D, so don't check VBT */
14541                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14542                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14543                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14544                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14545                 }
14546
14547                 intel_dsi_init(dev);
14548         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14549                 bool found = false;
14550
14551                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14552                         DRM_DEBUG_KMS("probing SDVOB\n");
14553                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14554                         if (!found && IS_G4X(dev)) {
14555                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14556                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14557                         }
14558
14559                         if (!found && IS_G4X(dev))
14560                                 intel_dp_init(dev, DP_B, PORT_B);
14561                 }
14562
14563                 /* Before G4X SDVOC doesn't have its own detect register */
14564
14565                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14566                         DRM_DEBUG_KMS("probing SDVOC\n");
14567                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14568                 }
14569
14570                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14571
14572                         if (IS_G4X(dev)) {
14573                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14574                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14575                         }
14576                         if (IS_G4X(dev))
14577                                 intel_dp_init(dev, DP_C, PORT_C);
14578                 }
14579
14580                 if (IS_G4X(dev) &&
14581                     (I915_READ(DP_D) & DP_DETECTED))
14582                         intel_dp_init(dev, DP_D, PORT_D);
14583         } else if (IS_GEN2(dev))
14584                 intel_dvo_init(dev);
14585
14586         if (SUPPORTS_TV(dev))
14587                 intel_tv_init(dev);
14588
14589         intel_psr_init(dev);
14590
14591         for_each_intel_encoder(dev, encoder) {
14592                 encoder->base.possible_crtcs = encoder->crtc_mask;
14593                 encoder->base.possible_clones =
14594                         intel_encoder_clones(encoder);
14595         }
14596
14597         intel_init_pch_refclk(dev);
14598
14599         drm_helper_move_panel_connectors_to_head(dev);
14600 }
14601
14602 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14603 {
14604         struct drm_device *dev = fb->dev;
14605         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14606
14607         drm_framebuffer_cleanup(fb);
14608         mutex_lock(&dev->struct_mutex);
14609         WARN_ON(!intel_fb->obj->framebuffer_references--);
14610         drm_gem_object_unreference(&intel_fb->obj->base);
14611         mutex_unlock(&dev->struct_mutex);
14612         kfree(intel_fb);
14613 }
14614
14615 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14616                                                 struct drm_file *file,
14617                                                 unsigned int *handle)
14618 {
14619         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14620         struct drm_i915_gem_object *obj = intel_fb->obj;
14621
14622         if (obj->userptr.mm) {
14623                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14624                 return -EINVAL;
14625         }
14626
14627         return drm_gem_handle_create(file, &obj->base, handle);
14628 }
14629
14630 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14631                                         struct drm_file *file,
14632                                         unsigned flags, unsigned color,
14633                                         struct drm_clip_rect *clips,
14634                                         unsigned num_clips)
14635 {
14636         struct drm_device *dev = fb->dev;
14637         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14638         struct drm_i915_gem_object *obj = intel_fb->obj;
14639
14640         mutex_lock(&dev->struct_mutex);
14641         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14642         mutex_unlock(&dev->struct_mutex);
14643
14644         return 0;
14645 }
14646
14647 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14648         .destroy = intel_user_framebuffer_destroy,
14649         .create_handle = intel_user_framebuffer_create_handle,
14650         .dirty = intel_user_framebuffer_dirty,
14651 };
14652
14653 static
14654 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14655                          uint32_t pixel_format)
14656 {
14657         u32 gen = INTEL_INFO(dev)->gen;
14658
14659         if (gen >= 9) {
14660                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14661
14662                 /* "The stride in bytes must not exceed the of the size of 8K
14663                  *  pixels and 32K bytes."
14664                  */
14665                 return min(8192 * cpp, 32768);
14666         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14667                 return 32*1024;
14668         } else if (gen >= 4) {
14669                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14670                         return 16*1024;
14671                 else
14672                         return 32*1024;
14673         } else if (gen >= 3) {
14674                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14675                         return 8*1024;
14676                 else
14677                         return 16*1024;
14678         } else {
14679                 /* XXX DSPC is limited to 4k tiled */
14680                 return 8*1024;
14681         }
14682 }
14683
14684 static int intel_framebuffer_init(struct drm_device *dev,
14685                                   struct intel_framebuffer *intel_fb,
14686                                   struct drm_mode_fb_cmd2 *mode_cmd,
14687                                   struct drm_i915_gem_object *obj)
14688 {
14689         struct drm_i915_private *dev_priv = to_i915(dev);
14690         unsigned int aligned_height;
14691         int ret;
14692         u32 pitch_limit, stride_alignment;
14693
14694         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14695
14696         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14697                 /* Enforce that fb modifier and tiling mode match, but only for
14698                  * X-tiled. This is needed for FBC. */
14699                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14700                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14701                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14702                         return -EINVAL;
14703                 }
14704         } else {
14705                 if (obj->tiling_mode == I915_TILING_X)
14706                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14707                 else if (obj->tiling_mode == I915_TILING_Y) {
14708                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14709                         return -EINVAL;
14710                 }
14711         }
14712
14713         /* Passed in modifier sanity checking. */
14714         switch (mode_cmd->modifier[0]) {
14715         case I915_FORMAT_MOD_Y_TILED:
14716         case I915_FORMAT_MOD_Yf_TILED:
14717                 if (INTEL_INFO(dev)->gen < 9) {
14718                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14719                                   mode_cmd->modifier[0]);
14720                         return -EINVAL;
14721                 }
14722         case DRM_FORMAT_MOD_NONE:
14723         case I915_FORMAT_MOD_X_TILED:
14724                 break;
14725         default:
14726                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14727                           mode_cmd->modifier[0]);
14728                 return -EINVAL;
14729         }
14730
14731         stride_alignment = intel_fb_stride_alignment(dev_priv,
14732                                                      mode_cmd->modifier[0],
14733                                                      mode_cmd->pixel_format);
14734         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14735                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14736                           mode_cmd->pitches[0], stride_alignment);
14737                 return -EINVAL;
14738         }
14739
14740         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14741                                            mode_cmd->pixel_format);
14742         if (mode_cmd->pitches[0] > pitch_limit) {
14743                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14744                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14745                           "tiled" : "linear",
14746                           mode_cmd->pitches[0], pitch_limit);
14747                 return -EINVAL;
14748         }
14749
14750         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14751             mode_cmd->pitches[0] != obj->stride) {
14752                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14753                           mode_cmd->pitches[0], obj->stride);
14754                 return -EINVAL;
14755         }
14756
14757         /* Reject formats not supported by any plane early. */
14758         switch (mode_cmd->pixel_format) {
14759         case DRM_FORMAT_C8:
14760         case DRM_FORMAT_RGB565:
14761         case DRM_FORMAT_XRGB8888:
14762         case DRM_FORMAT_ARGB8888:
14763                 break;
14764         case DRM_FORMAT_XRGB1555:
14765                 if (INTEL_INFO(dev)->gen > 3) {
14766                         DRM_DEBUG("unsupported pixel format: %s\n",
14767                                   drm_get_format_name(mode_cmd->pixel_format));
14768                         return -EINVAL;
14769                 }
14770                 break;
14771         case DRM_FORMAT_ABGR8888:
14772                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14773                     INTEL_INFO(dev)->gen < 9) {
14774                         DRM_DEBUG("unsupported pixel format: %s\n",
14775                                   drm_get_format_name(mode_cmd->pixel_format));
14776                         return -EINVAL;
14777                 }
14778                 break;
14779         case DRM_FORMAT_XBGR8888:
14780         case DRM_FORMAT_XRGB2101010:
14781         case DRM_FORMAT_XBGR2101010:
14782                 if (INTEL_INFO(dev)->gen < 4) {
14783                         DRM_DEBUG("unsupported pixel format: %s\n",
14784                                   drm_get_format_name(mode_cmd->pixel_format));
14785                         return -EINVAL;
14786                 }
14787                 break;
14788         case DRM_FORMAT_ABGR2101010:
14789                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14790                         DRM_DEBUG("unsupported pixel format: %s\n",
14791                                   drm_get_format_name(mode_cmd->pixel_format));
14792                         return -EINVAL;
14793                 }
14794                 break;
14795         case DRM_FORMAT_YUYV:
14796         case DRM_FORMAT_UYVY:
14797         case DRM_FORMAT_YVYU:
14798         case DRM_FORMAT_VYUY:
14799                 if (INTEL_INFO(dev)->gen < 5) {
14800                         DRM_DEBUG("unsupported pixel format: %s\n",
14801                                   drm_get_format_name(mode_cmd->pixel_format));
14802                         return -EINVAL;
14803                 }
14804                 break;
14805         default:
14806                 DRM_DEBUG("unsupported pixel format: %s\n",
14807                           drm_get_format_name(mode_cmd->pixel_format));
14808                 return -EINVAL;
14809         }
14810
14811         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14812         if (mode_cmd->offsets[0] != 0)
14813                 return -EINVAL;
14814
14815         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14816                                                mode_cmd->pixel_format,
14817                                                mode_cmd->modifier[0]);
14818         /* FIXME drm helper for size checks (especially planar formats)? */
14819         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14820                 return -EINVAL;
14821
14822         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14823         intel_fb->obj = obj;
14824
14825         intel_fill_fb_info(dev_priv, &intel_fb->base);
14826
14827         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14828         if (ret) {
14829                 DRM_ERROR("framebuffer init failed %d\n", ret);
14830                 return ret;
14831         }
14832
14833         intel_fb->obj->framebuffer_references++;
14834
14835         return 0;
14836 }
14837
14838 static struct drm_framebuffer *
14839 intel_user_framebuffer_create(struct drm_device *dev,
14840                               struct drm_file *filp,
14841                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14842 {
14843         struct drm_framebuffer *fb;
14844         struct drm_i915_gem_object *obj;
14845         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14846
14847         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14848                                                 mode_cmd.handles[0]));
14849         if (&obj->base == NULL)
14850                 return ERR_PTR(-ENOENT);
14851
14852         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
14853         if (IS_ERR(fb))
14854                 drm_gem_object_unreference_unlocked(&obj->base);
14855
14856         return fb;
14857 }
14858
14859 #ifndef CONFIG_DRM_FBDEV_EMULATION
14860 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14861 {
14862 }
14863 #endif
14864
14865 static const struct drm_mode_config_funcs intel_mode_funcs = {
14866         .fb_create = intel_user_framebuffer_create,
14867         .output_poll_changed = intel_fbdev_output_poll_changed,
14868         .atomic_check = intel_atomic_check,
14869         .atomic_commit = intel_atomic_commit,
14870         .atomic_state_alloc = intel_atomic_state_alloc,
14871         .atomic_state_clear = intel_atomic_state_clear,
14872 };
14873
14874 /**
14875  * intel_init_display_hooks - initialize the display modesetting hooks
14876  * @dev_priv: device private
14877  */
14878 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14879 {
14880         if (INTEL_INFO(dev_priv)->gen >= 9) {
14881                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14882                 dev_priv->display.get_initial_plane_config =
14883                         skylake_get_initial_plane_config;
14884                 dev_priv->display.crtc_compute_clock =
14885                         haswell_crtc_compute_clock;
14886                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14887                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14888         } else if (HAS_DDI(dev_priv)) {
14889                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14890                 dev_priv->display.get_initial_plane_config =
14891                         ironlake_get_initial_plane_config;
14892                 dev_priv->display.crtc_compute_clock =
14893                         haswell_crtc_compute_clock;
14894                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14895                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14896         } else if (HAS_PCH_SPLIT(dev_priv)) {
14897                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14898                 dev_priv->display.get_initial_plane_config =
14899                         ironlake_get_initial_plane_config;
14900                 dev_priv->display.crtc_compute_clock =
14901                         ironlake_crtc_compute_clock;
14902                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14903                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14904         } else if (IS_CHERRYVIEW(dev_priv)) {
14905                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14906                 dev_priv->display.get_initial_plane_config =
14907                         i9xx_get_initial_plane_config;
14908                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14909                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14910                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14911         } else if (IS_VALLEYVIEW(dev_priv)) {
14912                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14913                 dev_priv->display.get_initial_plane_config =
14914                         i9xx_get_initial_plane_config;
14915                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14916                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14917                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14918         } else if (IS_G4X(dev_priv)) {
14919                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14920                 dev_priv->display.get_initial_plane_config =
14921                         i9xx_get_initial_plane_config;
14922                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14923                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14924                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14925         } else if (IS_PINEVIEW(dev_priv)) {
14926                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14927                 dev_priv->display.get_initial_plane_config =
14928                         i9xx_get_initial_plane_config;
14929                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14930                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14931                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14932         } else if (!IS_GEN2(dev_priv)) {
14933                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14934                 dev_priv->display.get_initial_plane_config =
14935                         i9xx_get_initial_plane_config;
14936                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14937                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14938                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14939         } else {
14940                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14941                 dev_priv->display.get_initial_plane_config =
14942                         i9xx_get_initial_plane_config;
14943                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14944                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14945                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14946         }
14947
14948         /* Returns the core display clock speed */
14949         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
14950                 dev_priv->display.get_display_clock_speed =
14951                         skylake_get_display_clock_speed;
14952         else if (IS_BROXTON(dev_priv))
14953                 dev_priv->display.get_display_clock_speed =
14954                         broxton_get_display_clock_speed;
14955         else if (IS_BROADWELL(dev_priv))
14956                 dev_priv->display.get_display_clock_speed =
14957                         broadwell_get_display_clock_speed;
14958         else if (IS_HASWELL(dev_priv))
14959                 dev_priv->display.get_display_clock_speed =
14960                         haswell_get_display_clock_speed;
14961         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14962                 dev_priv->display.get_display_clock_speed =
14963                         valleyview_get_display_clock_speed;
14964         else if (IS_GEN5(dev_priv))
14965                 dev_priv->display.get_display_clock_speed =
14966                         ilk_get_display_clock_speed;
14967         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
14968                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
14969                 dev_priv->display.get_display_clock_speed =
14970                         i945_get_display_clock_speed;
14971         else if (IS_GM45(dev_priv))
14972                 dev_priv->display.get_display_clock_speed =
14973                         gm45_get_display_clock_speed;
14974         else if (IS_CRESTLINE(dev_priv))
14975                 dev_priv->display.get_display_clock_speed =
14976                         i965gm_get_display_clock_speed;
14977         else if (IS_PINEVIEW(dev_priv))
14978                 dev_priv->display.get_display_clock_speed =
14979                         pnv_get_display_clock_speed;
14980         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
14981                 dev_priv->display.get_display_clock_speed =
14982                         g33_get_display_clock_speed;
14983         else if (IS_I915G(dev_priv))
14984                 dev_priv->display.get_display_clock_speed =
14985                         i915_get_display_clock_speed;
14986         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
14987                 dev_priv->display.get_display_clock_speed =
14988                         i9xx_misc_get_display_clock_speed;
14989         else if (IS_I915GM(dev_priv))
14990                 dev_priv->display.get_display_clock_speed =
14991                         i915gm_get_display_clock_speed;
14992         else if (IS_I865G(dev_priv))
14993                 dev_priv->display.get_display_clock_speed =
14994                         i865_get_display_clock_speed;
14995         else if (IS_I85X(dev_priv))
14996                 dev_priv->display.get_display_clock_speed =
14997                         i85x_get_display_clock_speed;
14998         else { /* 830 */
14999                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
15000                 dev_priv->display.get_display_clock_speed =
15001                         i830_get_display_clock_speed;
15002         }
15003
15004         if (IS_GEN5(dev_priv)) {
15005                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
15006         } else if (IS_GEN6(dev_priv)) {
15007                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
15008         } else if (IS_IVYBRIDGE(dev_priv)) {
15009                 /* FIXME: detect B0+ stepping and use auto training */
15010                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
15011         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
15012                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
15013         }
15014
15015         if (IS_BROADWELL(dev_priv)) {
15016                 dev_priv->display.modeset_commit_cdclk =
15017                         broadwell_modeset_commit_cdclk;
15018                 dev_priv->display.modeset_calc_cdclk =
15019                         broadwell_modeset_calc_cdclk;
15020         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15021                 dev_priv->display.modeset_commit_cdclk =
15022                         valleyview_modeset_commit_cdclk;
15023                 dev_priv->display.modeset_calc_cdclk =
15024                         valleyview_modeset_calc_cdclk;
15025         } else if (IS_BROXTON(dev_priv)) {
15026                 dev_priv->display.modeset_commit_cdclk =
15027                         broxton_modeset_commit_cdclk;
15028                 dev_priv->display.modeset_calc_cdclk =
15029                         broxton_modeset_calc_cdclk;
15030         }
15031
15032         switch (INTEL_INFO(dev_priv)->gen) {
15033         case 2:
15034                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15035                 break;
15036
15037         case 3:
15038                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15039                 break;
15040
15041         case 4:
15042         case 5:
15043                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15044                 break;
15045
15046         case 6:
15047                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15048                 break;
15049         case 7:
15050         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15051                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15052                 break;
15053         case 9:
15054                 /* Drop through - unsupported since execlist only. */
15055         default:
15056                 /* Default just returns -ENODEV to indicate unsupported */
15057                 dev_priv->display.queue_flip = intel_default_queue_flip;
15058         }
15059 }
15060
15061 /*
15062  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15063  * resume, or other times.  This quirk makes sure that's the case for
15064  * affected systems.
15065  */
15066 static void quirk_pipea_force(struct drm_device *dev)
15067 {
15068         struct drm_i915_private *dev_priv = dev->dev_private;
15069
15070         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15071         DRM_INFO("applying pipe a force quirk\n");
15072 }
15073
15074 static void quirk_pipeb_force(struct drm_device *dev)
15075 {
15076         struct drm_i915_private *dev_priv = dev->dev_private;
15077
15078         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15079         DRM_INFO("applying pipe b force quirk\n");
15080 }
15081
15082 /*
15083  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15084  */
15085 static void quirk_ssc_force_disable(struct drm_device *dev)
15086 {
15087         struct drm_i915_private *dev_priv = dev->dev_private;
15088         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15089         DRM_INFO("applying lvds SSC disable quirk\n");
15090 }
15091
15092 /*
15093  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15094  * brightness value
15095  */
15096 static void quirk_invert_brightness(struct drm_device *dev)
15097 {
15098         struct drm_i915_private *dev_priv = dev->dev_private;
15099         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15100         DRM_INFO("applying inverted panel brightness quirk\n");
15101 }
15102
15103 /* Some VBT's incorrectly indicate no backlight is present */
15104 static void quirk_backlight_present(struct drm_device *dev)
15105 {
15106         struct drm_i915_private *dev_priv = dev->dev_private;
15107         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15108         DRM_INFO("applying backlight present quirk\n");
15109 }
15110
15111 struct intel_quirk {
15112         int device;
15113         int subsystem_vendor;
15114         int subsystem_device;
15115         void (*hook)(struct drm_device *dev);
15116 };
15117
15118 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15119 struct intel_dmi_quirk {
15120         void (*hook)(struct drm_device *dev);
15121         const struct dmi_system_id (*dmi_id_list)[];
15122 };
15123
15124 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15125 {
15126         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15127         return 1;
15128 }
15129
15130 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15131         {
15132                 .dmi_id_list = &(const struct dmi_system_id[]) {
15133                         {
15134                                 .callback = intel_dmi_reverse_brightness,
15135                                 .ident = "NCR Corporation",
15136                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15137                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15138                                 },
15139                         },
15140                         { }  /* terminating entry */
15141                 },
15142                 .hook = quirk_invert_brightness,
15143         },
15144 };
15145
15146 static struct intel_quirk intel_quirks[] = {
15147         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15148         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15149
15150         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15151         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15152
15153         /* 830 needs to leave pipe A & dpll A up */
15154         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15155
15156         /* 830 needs to leave pipe B & dpll B up */
15157         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15158
15159         /* Lenovo U160 cannot use SSC on LVDS */
15160         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15161
15162         /* Sony Vaio Y cannot use SSC on LVDS */
15163         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15164
15165         /* Acer Aspire 5734Z must invert backlight brightness */
15166         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15167
15168         /* Acer/eMachines G725 */
15169         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15170
15171         /* Acer/eMachines e725 */
15172         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15173
15174         /* Acer/Packard Bell NCL20 */
15175         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15176
15177         /* Acer Aspire 4736Z */
15178         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15179
15180         /* Acer Aspire 5336 */
15181         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15182
15183         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15184         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15185
15186         /* Acer C720 Chromebook (Core i3 4005U) */
15187         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15188
15189         /* Apple Macbook 2,1 (Core 2 T7400) */
15190         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15191
15192         /* Apple Macbook 4,1 */
15193         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15194
15195         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15196         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15197
15198         /* HP Chromebook 14 (Celeron 2955U) */
15199         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15200
15201         /* Dell Chromebook 11 */
15202         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15203
15204         /* Dell Chromebook 11 (2015 version) */
15205         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15206 };
15207
15208 static void intel_init_quirks(struct drm_device *dev)
15209 {
15210         struct pci_dev *d = dev->pdev;
15211         int i;
15212
15213         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15214                 struct intel_quirk *q = &intel_quirks[i];
15215
15216                 if (d->device == q->device &&
15217                     (d->subsystem_vendor == q->subsystem_vendor ||
15218                      q->subsystem_vendor == PCI_ANY_ID) &&
15219                     (d->subsystem_device == q->subsystem_device ||
15220                      q->subsystem_device == PCI_ANY_ID))
15221                         q->hook(dev);
15222         }
15223         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15224                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15225                         intel_dmi_quirks[i].hook(dev);
15226         }
15227 }
15228
15229 /* Disable the VGA plane that we never use */
15230 static void i915_disable_vga(struct drm_device *dev)
15231 {
15232         struct drm_i915_private *dev_priv = dev->dev_private;
15233         u8 sr1;
15234         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15235
15236         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15237         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15238         outb(SR01, VGA_SR_INDEX);
15239         sr1 = inb(VGA_SR_DATA);
15240         outb(sr1 | 1<<5, VGA_SR_DATA);
15241         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15242         udelay(300);
15243
15244         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15245         POSTING_READ(vga_reg);
15246 }
15247
15248 void intel_modeset_init_hw(struct drm_device *dev)
15249 {
15250         struct drm_i915_private *dev_priv = dev->dev_private;
15251
15252         intel_update_cdclk(dev);
15253
15254         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15255
15256         intel_init_clock_gating(dev);
15257         intel_enable_gt_powersave(dev_priv);
15258 }
15259
15260 /*
15261  * Calculate what we think the watermarks should be for the state we've read
15262  * out of the hardware and then immediately program those watermarks so that
15263  * we ensure the hardware settings match our internal state.
15264  *
15265  * We can calculate what we think WM's should be by creating a duplicate of the
15266  * current state (which was constructed during hardware readout) and running it
15267  * through the atomic check code to calculate new watermark values in the
15268  * state object.
15269  */
15270 static void sanitize_watermarks(struct drm_device *dev)
15271 {
15272         struct drm_i915_private *dev_priv = to_i915(dev);
15273         struct drm_atomic_state *state;
15274         struct drm_crtc *crtc;
15275         struct drm_crtc_state *cstate;
15276         struct drm_modeset_acquire_ctx ctx;
15277         int ret;
15278         int i;
15279
15280         /* Only supported on platforms that use atomic watermark design */
15281         if (!dev_priv->display.optimize_watermarks)
15282                 return;
15283
15284         /*
15285          * We need to hold connection_mutex before calling duplicate_state so
15286          * that the connector loop is protected.
15287          */
15288         drm_modeset_acquire_init(&ctx, 0);
15289 retry:
15290         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15291         if (ret == -EDEADLK) {
15292                 drm_modeset_backoff(&ctx);
15293                 goto retry;
15294         } else if (WARN_ON(ret)) {
15295                 goto fail;
15296         }
15297
15298         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15299         if (WARN_ON(IS_ERR(state)))
15300                 goto fail;
15301
15302         /*
15303          * Hardware readout is the only time we don't want to calculate
15304          * intermediate watermarks (since we don't trust the current
15305          * watermarks).
15306          */
15307         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15308
15309         ret = intel_atomic_check(dev, state);
15310         if (ret) {
15311                 /*
15312                  * If we fail here, it means that the hardware appears to be
15313                  * programmed in a way that shouldn't be possible, given our
15314                  * understanding of watermark requirements.  This might mean a
15315                  * mistake in the hardware readout code or a mistake in the
15316                  * watermark calculations for a given platform.  Raise a WARN
15317                  * so that this is noticeable.
15318                  *
15319                  * If this actually happens, we'll have to just leave the
15320                  * BIOS-programmed watermarks untouched and hope for the best.
15321                  */
15322                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15323                 goto fail;
15324         }
15325
15326         /* Write calculated watermark values back */
15327         for_each_crtc_in_state(state, crtc, cstate, i) {
15328                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15329
15330                 cs->wm.need_postvbl_update = true;
15331                 dev_priv->display.optimize_watermarks(cs);
15332         }
15333
15334         drm_atomic_state_free(state);
15335 fail:
15336         drm_modeset_drop_locks(&ctx);
15337         drm_modeset_acquire_fini(&ctx);
15338 }
15339
15340 void intel_modeset_init(struct drm_device *dev)
15341 {
15342         struct drm_i915_private *dev_priv = to_i915(dev);
15343         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15344         int sprite, ret;
15345         enum pipe pipe;
15346         struct intel_crtc *crtc;
15347
15348         drm_mode_config_init(dev);
15349
15350         dev->mode_config.min_width = 0;
15351         dev->mode_config.min_height = 0;
15352
15353         dev->mode_config.preferred_depth = 24;
15354         dev->mode_config.prefer_shadow = 1;
15355
15356         dev->mode_config.allow_fb_modifiers = true;
15357
15358         dev->mode_config.funcs = &intel_mode_funcs;
15359
15360         intel_init_quirks(dev);
15361
15362         intel_init_pm(dev);
15363
15364         if (INTEL_INFO(dev)->num_pipes == 0)
15365                 return;
15366
15367         /*
15368          * There may be no VBT; and if the BIOS enabled SSC we can
15369          * just keep using it to avoid unnecessary flicker.  Whereas if the
15370          * BIOS isn't using it, don't assume it will work even if the VBT
15371          * indicates as much.
15372          */
15373         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15374                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15375                                             DREF_SSC1_ENABLE);
15376
15377                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15378                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15379                                      bios_lvds_use_ssc ? "en" : "dis",
15380                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15381                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15382                 }
15383         }
15384
15385         if (IS_GEN2(dev)) {
15386                 dev->mode_config.max_width = 2048;
15387                 dev->mode_config.max_height = 2048;
15388         } else if (IS_GEN3(dev)) {
15389                 dev->mode_config.max_width = 4096;
15390                 dev->mode_config.max_height = 4096;
15391         } else {
15392                 dev->mode_config.max_width = 8192;
15393                 dev->mode_config.max_height = 8192;
15394         }
15395
15396         if (IS_845G(dev) || IS_I865G(dev)) {
15397                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15398                 dev->mode_config.cursor_height = 1023;
15399         } else if (IS_GEN2(dev)) {
15400                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15401                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15402         } else {
15403                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15404                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15405         }
15406
15407         dev->mode_config.fb_base = ggtt->mappable_base;
15408
15409         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15410                       INTEL_INFO(dev)->num_pipes,
15411                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15412
15413         for_each_pipe(dev_priv, pipe) {
15414                 intel_crtc_init(dev, pipe);
15415                 for_each_sprite(dev_priv, pipe, sprite) {
15416                         ret = intel_plane_init(dev, pipe, sprite);
15417                         if (ret)
15418                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15419                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15420                 }
15421         }
15422
15423         intel_update_czclk(dev_priv);
15424         intel_update_cdclk(dev);
15425
15426         intel_shared_dpll_init(dev);
15427
15428         /* Just disable it once at startup */
15429         i915_disable_vga(dev);
15430         intel_setup_outputs(dev);
15431
15432         drm_modeset_lock_all(dev);
15433         intel_modeset_setup_hw_state(dev);
15434         drm_modeset_unlock_all(dev);
15435
15436         for_each_intel_crtc(dev, crtc) {
15437                 struct intel_initial_plane_config plane_config = {};
15438
15439                 if (!crtc->active)
15440                         continue;
15441
15442                 /*
15443                  * Note that reserving the BIOS fb up front prevents us
15444                  * from stuffing other stolen allocations like the ring
15445                  * on top.  This prevents some ugliness at boot time, and
15446                  * can even allow for smooth boot transitions if the BIOS
15447                  * fb is large enough for the active pipe configuration.
15448                  */
15449                 dev_priv->display.get_initial_plane_config(crtc,
15450                                                            &plane_config);
15451
15452                 /*
15453                  * If the fb is shared between multiple heads, we'll
15454                  * just get the first one.
15455                  */
15456                 intel_find_initial_plane_obj(crtc, &plane_config);
15457         }
15458
15459         /*
15460          * Make sure hardware watermarks really match the state we read out.
15461          * Note that we need to do this after reconstructing the BIOS fb's
15462          * since the watermark calculation done here will use pstate->fb.
15463          */
15464         sanitize_watermarks(dev);
15465 }
15466
15467 static void intel_enable_pipe_a(struct drm_device *dev)
15468 {
15469         struct intel_connector *connector;
15470         struct drm_connector *crt = NULL;
15471         struct intel_load_detect_pipe load_detect_temp;
15472         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15473
15474         /* We can't just switch on the pipe A, we need to set things up with a
15475          * proper mode and output configuration. As a gross hack, enable pipe A
15476          * by enabling the load detect pipe once. */
15477         for_each_intel_connector(dev, connector) {
15478                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15479                         crt = &connector->base;
15480                         break;
15481                 }
15482         }
15483
15484         if (!crt)
15485                 return;
15486
15487         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15488                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15489 }
15490
15491 static bool
15492 intel_check_plane_mapping(struct intel_crtc *crtc)
15493 {
15494         struct drm_device *dev = crtc->base.dev;
15495         struct drm_i915_private *dev_priv = dev->dev_private;
15496         u32 val;
15497
15498         if (INTEL_INFO(dev)->num_pipes == 1)
15499                 return true;
15500
15501         val = I915_READ(DSPCNTR(!crtc->plane));
15502
15503         if ((val & DISPLAY_PLANE_ENABLE) &&
15504             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15505                 return false;
15506
15507         return true;
15508 }
15509
15510 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15511 {
15512         struct drm_device *dev = crtc->base.dev;
15513         struct intel_encoder *encoder;
15514
15515         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15516                 return true;
15517
15518         return false;
15519 }
15520
15521 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15522 {
15523         struct drm_device *dev = encoder->base.dev;
15524         struct intel_connector *connector;
15525
15526         for_each_connector_on_encoder(dev, &encoder->base, connector)
15527                 return true;
15528
15529         return false;
15530 }
15531
15532 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15533 {
15534         struct drm_device *dev = crtc->base.dev;
15535         struct drm_i915_private *dev_priv = dev->dev_private;
15536         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15537
15538         /* Clear any frame start delays used for debugging left by the BIOS */
15539         if (!transcoder_is_dsi(cpu_transcoder)) {
15540                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15541
15542                 I915_WRITE(reg,
15543                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15544         }
15545
15546         /* restore vblank interrupts to correct state */
15547         drm_crtc_vblank_reset(&crtc->base);
15548         if (crtc->active) {
15549                 struct intel_plane *plane;
15550
15551                 drm_crtc_vblank_on(&crtc->base);
15552
15553                 /* Disable everything but the primary plane */
15554                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15555                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15556                                 continue;
15557
15558                         plane->disable_plane(&plane->base, &crtc->base);
15559                 }
15560         }
15561
15562         /* We need to sanitize the plane -> pipe mapping first because this will
15563          * disable the crtc (and hence change the state) if it is wrong. Note
15564          * that gen4+ has a fixed plane -> pipe mapping.  */
15565         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15566                 bool plane;
15567
15568                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15569                               crtc->base.base.id);
15570
15571                 /* Pipe has the wrong plane attached and the plane is active.
15572                  * Temporarily change the plane mapping and disable everything
15573                  * ...  */
15574                 plane = crtc->plane;
15575                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15576                 crtc->plane = !plane;
15577                 intel_crtc_disable_noatomic(&crtc->base);
15578                 crtc->plane = plane;
15579         }
15580
15581         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15582             crtc->pipe == PIPE_A && !crtc->active) {
15583                 /* BIOS forgot to enable pipe A, this mostly happens after
15584                  * resume. Force-enable the pipe to fix this, the update_dpms
15585                  * call below we restore the pipe to the right state, but leave
15586                  * the required bits on. */
15587                 intel_enable_pipe_a(dev);
15588         }
15589
15590         /* Adjust the state of the output pipe according to whether we
15591          * have active connectors/encoders. */
15592         if (crtc->active && !intel_crtc_has_encoders(crtc))
15593                 intel_crtc_disable_noatomic(&crtc->base);
15594
15595         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15596                 /*
15597                  * We start out with underrun reporting disabled to avoid races.
15598                  * For correct bookkeeping mark this on active crtcs.
15599                  *
15600                  * Also on gmch platforms we dont have any hardware bits to
15601                  * disable the underrun reporting. Which means we need to start
15602                  * out with underrun reporting disabled also on inactive pipes,
15603                  * since otherwise we'll complain about the garbage we read when
15604                  * e.g. coming up after runtime pm.
15605                  *
15606                  * No protection against concurrent access is required - at
15607                  * worst a fifo underrun happens which also sets this to false.
15608                  */
15609                 crtc->cpu_fifo_underrun_disabled = true;
15610                 crtc->pch_fifo_underrun_disabled = true;
15611         }
15612 }
15613
15614 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15615 {
15616         struct intel_connector *connector;
15617         struct drm_device *dev = encoder->base.dev;
15618
15619         /* We need to check both for a crtc link (meaning that the
15620          * encoder is active and trying to read from a pipe) and the
15621          * pipe itself being active. */
15622         bool has_active_crtc = encoder->base.crtc &&
15623                 to_intel_crtc(encoder->base.crtc)->active;
15624
15625         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15626                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15627                               encoder->base.base.id,
15628                               encoder->base.name);
15629
15630                 /* Connector is active, but has no active pipe. This is
15631                  * fallout from our resume register restoring. Disable
15632                  * the encoder manually again. */
15633                 if (encoder->base.crtc) {
15634                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15635                                       encoder->base.base.id,
15636                                       encoder->base.name);
15637                         encoder->disable(encoder);
15638                         if (encoder->post_disable)
15639                                 encoder->post_disable(encoder);
15640                 }
15641                 encoder->base.crtc = NULL;
15642
15643                 /* Inconsistent output/port/pipe state happens presumably due to
15644                  * a bug in one of the get_hw_state functions. Or someplace else
15645                  * in our code, like the register restore mess on resume. Clamp
15646                  * things to off as a safer default. */
15647                 for_each_intel_connector(dev, connector) {
15648                         if (connector->encoder != encoder)
15649                                 continue;
15650                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15651                         connector->base.encoder = NULL;
15652                 }
15653         }
15654         /* Enabled encoders without active connectors will be fixed in
15655          * the crtc fixup. */
15656 }
15657
15658 void i915_redisable_vga_power_on(struct drm_device *dev)
15659 {
15660         struct drm_i915_private *dev_priv = dev->dev_private;
15661         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15662
15663         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15664                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15665                 i915_disable_vga(dev);
15666         }
15667 }
15668
15669 void i915_redisable_vga(struct drm_device *dev)
15670 {
15671         struct drm_i915_private *dev_priv = dev->dev_private;
15672
15673         /* This function can be called both from intel_modeset_setup_hw_state or
15674          * at a very early point in our resume sequence, where the power well
15675          * structures are not yet restored. Since this function is at a very
15676          * paranoid "someone might have enabled VGA while we were not looking"
15677          * level, just check if the power well is enabled instead of trying to
15678          * follow the "don't touch the power well if we don't need it" policy
15679          * the rest of the driver uses. */
15680         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15681                 return;
15682
15683         i915_redisable_vga_power_on(dev);
15684
15685         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15686 }
15687
15688 static bool primary_get_hw_state(struct intel_plane *plane)
15689 {
15690         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15691
15692         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15693 }
15694
15695 /* FIXME read out full plane state for all planes */
15696 static void readout_plane_state(struct intel_crtc *crtc)
15697 {
15698         struct drm_plane *primary = crtc->base.primary;
15699         struct intel_plane_state *plane_state =
15700                 to_intel_plane_state(primary->state);
15701
15702         plane_state->visible = crtc->active &&
15703                 primary_get_hw_state(to_intel_plane(primary));
15704
15705         if (plane_state->visible)
15706                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15707 }
15708
15709 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15710 {
15711         struct drm_i915_private *dev_priv = dev->dev_private;
15712         enum pipe pipe;
15713         struct intel_crtc *crtc;
15714         struct intel_encoder *encoder;
15715         struct intel_connector *connector;
15716         int i;
15717
15718         dev_priv->active_crtcs = 0;
15719
15720         for_each_intel_crtc(dev, crtc) {
15721                 struct intel_crtc_state *crtc_state = crtc->config;
15722                 int pixclk = 0;
15723
15724                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, &crtc_state->base);
15725                 memset(crtc_state, 0, sizeof(*crtc_state));
15726                 crtc_state->base.crtc = &crtc->base;
15727
15728                 crtc_state->base.active = crtc_state->base.enable =
15729                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15730
15731                 crtc->base.enabled = crtc_state->base.enable;
15732                 crtc->active = crtc_state->base.active;
15733
15734                 if (crtc_state->base.active) {
15735                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15736
15737                         if (IS_BROADWELL(dev_priv)) {
15738                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15739
15740                                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15741                                 if (crtc_state->ips_enabled)
15742                                         pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15743                         } else if (IS_VALLEYVIEW(dev_priv) ||
15744                                    IS_CHERRYVIEW(dev_priv) ||
15745                                    IS_BROXTON(dev_priv))
15746                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15747                         else
15748                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15749                 }
15750
15751                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15752
15753                 readout_plane_state(crtc);
15754
15755                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15756                               crtc->base.base.id,
15757                               crtc->active ? "enabled" : "disabled");
15758         }
15759
15760         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15761                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15762
15763                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15764                                                   &pll->config.hw_state);
15765                 pll->config.crtc_mask = 0;
15766                 for_each_intel_crtc(dev, crtc) {
15767                         if (crtc->active && crtc->config->shared_dpll == pll)
15768                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15769                 }
15770                 pll->active_mask = pll->config.crtc_mask;
15771
15772                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15773                               pll->name, pll->config.crtc_mask, pll->on);
15774         }
15775
15776         for_each_intel_encoder(dev, encoder) {
15777                 pipe = 0;
15778
15779                 if (encoder->get_hw_state(encoder, &pipe)) {
15780                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15781                         encoder->base.crtc = &crtc->base;
15782                         encoder->get_config(encoder, crtc->config);
15783                 } else {
15784                         encoder->base.crtc = NULL;
15785                 }
15786
15787                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15788                               encoder->base.base.id,
15789                               encoder->base.name,
15790                               encoder->base.crtc ? "enabled" : "disabled",
15791                               pipe_name(pipe));
15792         }
15793
15794         for_each_intel_connector(dev, connector) {
15795                 if (connector->get_hw_state(connector)) {
15796                         connector->base.dpms = DRM_MODE_DPMS_ON;
15797
15798                         encoder = connector->encoder;
15799                         connector->base.encoder = &encoder->base;
15800
15801                         if (encoder->base.crtc &&
15802                             encoder->base.crtc->state->active) {
15803                                 /*
15804                                  * This has to be done during hardware readout
15805                                  * because anything calling .crtc_disable may
15806                                  * rely on the connector_mask being accurate.
15807                                  */
15808                                 encoder->base.crtc->state->connector_mask |=
15809                                         1 << drm_connector_index(&connector->base);
15810                                 encoder->base.crtc->state->encoder_mask |=
15811                                         1 << drm_encoder_index(&encoder->base);
15812                         }
15813
15814                 } else {
15815                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15816                         connector->base.encoder = NULL;
15817                 }
15818                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15819                               connector->base.base.id,
15820                               connector->base.name,
15821                               connector->base.encoder ? "enabled" : "disabled");
15822         }
15823
15824         for_each_intel_crtc(dev, crtc) {
15825                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15826
15827                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15828                 if (crtc->base.state->active) {
15829                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15830                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15831                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15832
15833                         /*
15834                          * The initial mode needs to be set in order to keep
15835                          * the atomic core happy. It wants a valid mode if the
15836                          * crtc's enabled, so we do the above call.
15837                          *
15838                          * At this point some state updated by the connectors
15839                          * in their ->detect() callback has not run yet, so
15840                          * no recalculation can be done yet.
15841                          *
15842                          * Even if we could do a recalculation and modeset
15843                          * right now it would cause a double modeset if
15844                          * fbdev or userspace chooses a different initial mode.
15845                          *
15846                          * If that happens, someone indicated they wanted a
15847                          * mode change, which means it's safe to do a full
15848                          * recalculation.
15849                          */
15850                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15851
15852                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
15853                         update_scanline_offset(crtc);
15854                 }
15855
15856                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
15857         }
15858 }
15859
15860 /* Scan out the current hw modeset state,
15861  * and sanitizes it to the current state
15862  */
15863 static void
15864 intel_modeset_setup_hw_state(struct drm_device *dev)
15865 {
15866         struct drm_i915_private *dev_priv = dev->dev_private;
15867         enum pipe pipe;
15868         struct intel_crtc *crtc;
15869         struct intel_encoder *encoder;
15870         int i;
15871
15872         intel_modeset_readout_hw_state(dev);
15873
15874         /* HW state is read out, now we need to sanitize this mess. */
15875         for_each_intel_encoder(dev, encoder) {
15876                 intel_sanitize_encoder(encoder);
15877         }
15878
15879         for_each_pipe(dev_priv, pipe) {
15880                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15881                 intel_sanitize_crtc(crtc);
15882                 intel_dump_pipe_config(crtc, crtc->config,
15883                                        "[setup_hw_state]");
15884         }
15885
15886         intel_modeset_update_connector_atomic_state(dev);
15887
15888         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15889                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15890
15891                 if (!pll->on || pll->active_mask)
15892                         continue;
15893
15894                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15895
15896                 pll->funcs.disable(dev_priv, pll);
15897                 pll->on = false;
15898         }
15899
15900         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15901                 vlv_wm_get_hw_state(dev);
15902         else if (IS_GEN9(dev))
15903                 skl_wm_get_hw_state(dev);
15904         else if (HAS_PCH_SPLIT(dev))
15905                 ilk_wm_get_hw_state(dev);
15906
15907         for_each_intel_crtc(dev, crtc) {
15908                 unsigned long put_domains;
15909
15910                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15911                 if (WARN_ON(put_domains))
15912                         modeset_put_power_domains(dev_priv, put_domains);
15913         }
15914         intel_display_set_init_power(dev_priv, false);
15915
15916         intel_fbc_init_pipe_state(dev_priv);
15917 }
15918
15919 void intel_display_resume(struct drm_device *dev)
15920 {
15921         struct drm_i915_private *dev_priv = to_i915(dev);
15922         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15923         struct drm_modeset_acquire_ctx ctx;
15924         int ret;
15925         bool setup = false;
15926
15927         dev_priv->modeset_restore_state = NULL;
15928
15929         /*
15930          * This is a cludge because with real atomic modeset mode_config.mutex
15931          * won't be taken. Unfortunately some probed state like
15932          * audio_codec_enable is still protected by mode_config.mutex, so lock
15933          * it here for now.
15934          */
15935         mutex_lock(&dev->mode_config.mutex);
15936         drm_modeset_acquire_init(&ctx, 0);
15937
15938 retry:
15939         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15940
15941         if (ret == 0 && !setup) {
15942                 setup = true;
15943
15944                 intel_modeset_setup_hw_state(dev);
15945                 i915_redisable_vga(dev);
15946         }
15947
15948         if (ret == 0 && state) {
15949                 struct drm_crtc_state *crtc_state;
15950                 struct drm_crtc *crtc;
15951                 int i;
15952
15953                 state->acquire_ctx = &ctx;
15954
15955                 /* ignore any reset values/BIOS leftovers in the WM registers */
15956                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
15957
15958                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
15959                         /*
15960                          * Force recalculation even if we restore
15961                          * current state. With fast modeset this may not result
15962                          * in a modeset when the state is compatible.
15963                          */
15964                         crtc_state->mode_changed = true;
15965                 }
15966
15967                 ret = drm_atomic_commit(state);
15968         }
15969
15970         if (ret == -EDEADLK) {
15971                 drm_modeset_backoff(&ctx);
15972                 goto retry;
15973         }
15974
15975         drm_modeset_drop_locks(&ctx);
15976         drm_modeset_acquire_fini(&ctx);
15977         mutex_unlock(&dev->mode_config.mutex);
15978
15979         if (ret) {
15980                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15981                 drm_atomic_state_free(state);
15982         }
15983 }
15984
15985 void intel_modeset_gem_init(struct drm_device *dev)
15986 {
15987         struct drm_i915_private *dev_priv = to_i915(dev);
15988         struct drm_crtc *c;
15989         struct drm_i915_gem_object *obj;
15990         int ret;
15991
15992         intel_init_gt_powersave(dev_priv);
15993
15994         intel_modeset_init_hw(dev);
15995
15996         intel_setup_overlay(dev_priv);
15997
15998         /*
15999          * Make sure any fbs we allocated at startup are properly
16000          * pinned & fenced.  When we do the allocation it's too early
16001          * for this.
16002          */
16003         for_each_crtc(dev, c) {
16004                 obj = intel_fb_obj(c->primary->fb);
16005                 if (obj == NULL)
16006                         continue;
16007
16008                 mutex_lock(&dev->struct_mutex);
16009                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
16010                                                  c->primary->state->rotation);
16011                 mutex_unlock(&dev->struct_mutex);
16012                 if (ret) {
16013                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
16014                                   to_intel_crtc(c)->pipe);
16015                         drm_framebuffer_unreference(c->primary->fb);
16016                         c->primary->fb = NULL;
16017                         c->primary->crtc = c->primary->state->crtc = NULL;
16018                         update_state_fb(c->primary);
16019                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
16020                 }
16021         }
16022
16023         intel_backlight_register(dev);
16024 }
16025
16026 void intel_connector_unregister(struct intel_connector *intel_connector)
16027 {
16028         struct drm_connector *connector = &intel_connector->base;
16029
16030         intel_panel_destroy_backlight(connector);
16031         drm_connector_unregister(connector);
16032 }
16033
16034 void intel_modeset_cleanup(struct drm_device *dev)
16035 {
16036         struct drm_i915_private *dev_priv = dev->dev_private;
16037         struct intel_connector *connector;
16038
16039         intel_disable_gt_powersave(dev_priv);
16040
16041         intel_backlight_unregister(dev);
16042
16043         /*
16044          * Interrupts and polling as the first thing to avoid creating havoc.
16045          * Too much stuff here (turning of connectors, ...) would
16046          * experience fancy races otherwise.
16047          */
16048         intel_irq_uninstall(dev_priv);
16049
16050         /*
16051          * Due to the hpd irq storm handling the hotplug work can re-arm the
16052          * poll handlers. Hence disable polling after hpd handling is shut down.
16053          */
16054         drm_kms_helper_poll_fini(dev);
16055
16056         intel_unregister_dsm_handler();
16057
16058         intel_fbc_global_disable(dev_priv);
16059
16060         /* flush any delayed tasks or pending work */
16061         flush_scheduled_work();
16062
16063         /* destroy the backlight and sysfs files before encoders/connectors */
16064         for_each_intel_connector(dev, connector)
16065                 connector->unregister(connector);
16066
16067         drm_mode_config_cleanup(dev);
16068
16069         intel_cleanup_overlay(dev_priv);
16070
16071         intel_cleanup_gt_powersave(dev_priv);
16072
16073         intel_teardown_gmbus(dev);
16074 }
16075
16076 /*
16077  * Return which encoder is currently attached for connector.
16078  */
16079 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
16080 {
16081         return &intel_attached_encoder(connector)->base;
16082 }
16083
16084 void intel_connector_attach_encoder(struct intel_connector *connector,
16085                                     struct intel_encoder *encoder)
16086 {
16087         connector->encoder = encoder;
16088         drm_mode_connector_attach_encoder(&connector->base,
16089                                           &encoder->base);
16090 }
16091
16092 /*
16093  * set vga decode state - true == enable VGA decode
16094  */
16095 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16096 {
16097         struct drm_i915_private *dev_priv = dev->dev_private;
16098         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16099         u16 gmch_ctrl;
16100
16101         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16102                 DRM_ERROR("failed to read control word\n");
16103                 return -EIO;
16104         }
16105
16106         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16107                 return 0;
16108
16109         if (state)
16110                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16111         else
16112                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16113
16114         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16115                 DRM_ERROR("failed to write control word\n");
16116                 return -EIO;
16117         }
16118
16119         return 0;
16120 }
16121
16122 struct intel_display_error_state {
16123
16124         u32 power_well_driver;
16125
16126         int num_transcoders;
16127
16128         struct intel_cursor_error_state {
16129                 u32 control;
16130                 u32 position;
16131                 u32 base;
16132                 u32 size;
16133         } cursor[I915_MAX_PIPES];
16134
16135         struct intel_pipe_error_state {
16136                 bool power_domain_on;
16137                 u32 source;
16138                 u32 stat;
16139         } pipe[I915_MAX_PIPES];
16140
16141         struct intel_plane_error_state {
16142                 u32 control;
16143                 u32 stride;
16144                 u32 size;
16145                 u32 pos;
16146                 u32 addr;
16147                 u32 surface;
16148                 u32 tile_offset;
16149         } plane[I915_MAX_PIPES];
16150
16151         struct intel_transcoder_error_state {
16152                 bool power_domain_on;
16153                 enum transcoder cpu_transcoder;
16154
16155                 u32 conf;
16156
16157                 u32 htotal;
16158                 u32 hblank;
16159                 u32 hsync;
16160                 u32 vtotal;
16161                 u32 vblank;
16162                 u32 vsync;
16163         } transcoder[4];
16164 };
16165
16166 struct intel_display_error_state *
16167 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16168 {
16169         struct intel_display_error_state *error;
16170         int transcoders[] = {
16171                 TRANSCODER_A,
16172                 TRANSCODER_B,
16173                 TRANSCODER_C,
16174                 TRANSCODER_EDP,
16175         };
16176         int i;
16177
16178         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16179                 return NULL;
16180
16181         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16182         if (error == NULL)
16183                 return NULL;
16184
16185         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16186                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16187
16188         for_each_pipe(dev_priv, i) {
16189                 error->pipe[i].power_domain_on =
16190                         __intel_display_power_is_enabled(dev_priv,
16191                                                          POWER_DOMAIN_PIPE(i));
16192                 if (!error->pipe[i].power_domain_on)
16193                         continue;
16194
16195                 error->cursor[i].control = I915_READ(CURCNTR(i));
16196                 error->cursor[i].position = I915_READ(CURPOS(i));
16197                 error->cursor[i].base = I915_READ(CURBASE(i));
16198
16199                 error->plane[i].control = I915_READ(DSPCNTR(i));
16200                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16201                 if (INTEL_GEN(dev_priv) <= 3) {
16202                         error->plane[i].size = I915_READ(DSPSIZE(i));
16203                         error->plane[i].pos = I915_READ(DSPPOS(i));
16204                 }
16205                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16206                         error->plane[i].addr = I915_READ(DSPADDR(i));
16207                 if (INTEL_GEN(dev_priv) >= 4) {
16208                         error->plane[i].surface = I915_READ(DSPSURF(i));
16209                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16210                 }
16211
16212                 error->pipe[i].source = I915_READ(PIPESRC(i));
16213
16214                 if (HAS_GMCH_DISPLAY(dev_priv))
16215                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16216         }
16217
16218         /* Note: this does not include DSI transcoders. */
16219         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16220         if (HAS_DDI(dev_priv))
16221                 error->num_transcoders++; /* Account for eDP. */
16222
16223         for (i = 0; i < error->num_transcoders; i++) {
16224                 enum transcoder cpu_transcoder = transcoders[i];
16225
16226                 error->transcoder[i].power_domain_on =
16227                         __intel_display_power_is_enabled(dev_priv,
16228                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16229                 if (!error->transcoder[i].power_domain_on)
16230                         continue;
16231
16232                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16233
16234                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16235                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16236                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16237                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16238                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16239                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16240                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16241         }
16242
16243         return error;
16244 }
16245
16246 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16247
16248 void
16249 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16250                                 struct drm_device *dev,
16251                                 struct intel_display_error_state *error)
16252 {
16253         struct drm_i915_private *dev_priv = dev->dev_private;
16254         int i;
16255
16256         if (!error)
16257                 return;
16258
16259         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16260         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16261                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16262                            error->power_well_driver);
16263         for_each_pipe(dev_priv, i) {
16264                 err_printf(m, "Pipe [%d]:\n", i);
16265                 err_printf(m, "  Power: %s\n",
16266                            onoff(error->pipe[i].power_domain_on));
16267                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16268                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16269
16270                 err_printf(m, "Plane [%d]:\n", i);
16271                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16272                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16273                 if (INTEL_INFO(dev)->gen <= 3) {
16274                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16275                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16276                 }
16277                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16278                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16279                 if (INTEL_INFO(dev)->gen >= 4) {
16280                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16281                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16282                 }
16283
16284                 err_printf(m, "Cursor [%d]:\n", i);
16285                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16286                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16287                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16288         }
16289
16290         for (i = 0; i < error->num_transcoders; i++) {
16291                 err_printf(m, "CPU transcoder: %s\n",
16292                            transcoder_name(error->transcoder[i].cpu_transcoder));
16293                 err_printf(m, "  Power: %s\n",
16294                            onoff(error->transcoder[i].power_domain_on));
16295                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16296                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16297                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16298                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16299                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16300                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16301                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16302         }
16303 }