drm/i915: split set pipeconf to pipeconf, pipemisc, pipe_gamma
[cascardo/linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "i915_trace.h"
40 #include <drm/drm_atomic.h>
41 #include <drm/drm_atomic_helper.h>
42 #include <drm/drm_dp_helper.h>
43 #include <drm/drm_crtc_helper.h>
44 #include <drm/drm_plane_helper.h>
45 #include <drm/drm_rect.h>
46 #include <linux/dma_remapping.h>
47 #include <linux/reservation.h>
48 #include <linux/dma-buf.h>
49
50 /* Primary plane formats for gen <= 3 */
51 static const uint32_t i8xx_primary_formats[] = {
52         DRM_FORMAT_C8,
53         DRM_FORMAT_RGB565,
54         DRM_FORMAT_XRGB1555,
55         DRM_FORMAT_XRGB8888,
56 };
57
58 /* Primary plane formats for gen >= 4 */
59 static const uint32_t i965_primary_formats[] = {
60         DRM_FORMAT_C8,
61         DRM_FORMAT_RGB565,
62         DRM_FORMAT_XRGB8888,
63         DRM_FORMAT_XBGR8888,
64         DRM_FORMAT_XRGB2101010,
65         DRM_FORMAT_XBGR2101010,
66 };
67
68 static const uint32_t skl_primary_formats[] = {
69         DRM_FORMAT_C8,
70         DRM_FORMAT_RGB565,
71         DRM_FORMAT_XRGB8888,
72         DRM_FORMAT_XBGR8888,
73         DRM_FORMAT_ARGB8888,
74         DRM_FORMAT_ABGR8888,
75         DRM_FORMAT_XRGB2101010,
76         DRM_FORMAT_XBGR2101010,
77         DRM_FORMAT_YUYV,
78         DRM_FORMAT_YVYU,
79         DRM_FORMAT_UYVY,
80         DRM_FORMAT_VYUY,
81 };
82
83 /* Cursor formats */
84 static const uint32_t intel_cursor_formats[] = {
85         DRM_FORMAT_ARGB8888,
86 };
87
88 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
89                                 struct intel_crtc_state *pipe_config);
90 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
91                                    struct intel_crtc_state *pipe_config);
92
93 static int intel_framebuffer_init(struct drm_device *dev,
94                                   struct intel_framebuffer *ifb,
95                                   struct drm_mode_fb_cmd2 *mode_cmd,
96                                   struct drm_i915_gem_object *obj);
97 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
98 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
99 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
100 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
101                                          struct intel_link_m_n *m_n,
102                                          struct intel_link_m_n *m2_n2);
103 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
104 static void haswell_set_pipeconf(struct drm_crtc *crtc);
105 static void haswell_set_pipe_gamma(struct drm_crtc *crtc);
106 static void haswell_set_pipemisc(struct drm_crtc *crtc);
107 static void intel_set_pipe_csc(struct drm_crtc *crtc);
108 static void vlv_prepare_pll(struct intel_crtc *crtc,
109                             const struct intel_crtc_state *pipe_config);
110 static void chv_prepare_pll(struct intel_crtc *crtc,
111                             const struct intel_crtc_state *pipe_config);
112 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
113 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
114 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
115         struct intel_crtc_state *crtc_state);
116 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
117                            int num_connectors);
118 static void skylake_pfit_enable(struct intel_crtc *crtc);
119 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
120 static void ironlake_pfit_enable(struct intel_crtc *crtc);
121 static void intel_modeset_setup_hw_state(struct drm_device *dev);
122 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
123
124 typedef struct {
125         int     min, max;
126 } intel_range_t;
127
128 typedef struct {
129         int     dot_limit;
130         int     p2_slow, p2_fast;
131 } intel_p2_t;
132
133 typedef struct intel_limit intel_limit_t;
134 struct intel_limit {
135         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
136         intel_p2_t          p2;
137 };
138
139 /* returns HPLL frequency in kHz */
140 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
141 {
142         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
143
144         /* Obtain SKU information */
145         mutex_lock(&dev_priv->sb_lock);
146         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
147                 CCK_FUSE_HPLL_FREQ_MASK;
148         mutex_unlock(&dev_priv->sb_lock);
149
150         return vco_freq[hpll_freq] * 1000;
151 }
152
153 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
154                                   const char *name, u32 reg)
155 {
156         u32 val;
157         int divider;
158
159         if (dev_priv->hpll_freq == 0)
160                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
161
162         mutex_lock(&dev_priv->sb_lock);
163         val = vlv_cck_read(dev_priv, reg);
164         mutex_unlock(&dev_priv->sb_lock);
165
166         divider = val & CCK_FREQUENCY_VALUES;
167
168         WARN((val & CCK_FREQUENCY_STATUS) !=
169              (divider << CCK_FREQUENCY_STATUS_SHIFT),
170              "%s change in progress\n", name);
171
172         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
173 }
174
175 static int
176 intel_pch_rawclk(struct drm_i915_private *dev_priv)
177 {
178         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
179 }
180
181 static int
182 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
183 {
184         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
185                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
186 }
187
188 static int
189 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
190 {
191         uint32_t clkcfg;
192
193         /* hrawclock is 1/4 the FSB frequency */
194         clkcfg = I915_READ(CLKCFG);
195         switch (clkcfg & CLKCFG_FSB_MASK) {
196         case CLKCFG_FSB_400:
197                 return 100000;
198         case CLKCFG_FSB_533:
199                 return 133333;
200         case CLKCFG_FSB_667:
201                 return 166667;
202         case CLKCFG_FSB_800:
203                 return 200000;
204         case CLKCFG_FSB_1067:
205                 return 266667;
206         case CLKCFG_FSB_1333:
207                 return 333333;
208         /* these two are just a guess; one of them might be right */
209         case CLKCFG_FSB_1600:
210         case CLKCFG_FSB_1600_ALT:
211                 return 400000;
212         default:
213                 return 133333;
214         }
215 }
216
217 static void intel_update_rawclk(struct drm_i915_private *dev_priv)
218 {
219         if (HAS_PCH_SPLIT(dev_priv))
220                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
221         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
222                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
223         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
224                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
225         else
226                 return; /* no rawclk on other platforms, or no need to know it */
227
228         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
229 }
230
231 static void intel_update_czclk(struct drm_i915_private *dev_priv)
232 {
233         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
234                 return;
235
236         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
237                                                       CCK_CZ_CLOCK_CONTROL);
238
239         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
240 }
241
242 static inline u32 /* units of 100MHz */
243 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
244                     const struct intel_crtc_state *pipe_config)
245 {
246         if (HAS_DDI(dev_priv))
247                 return pipe_config->port_clock; /* SPLL */
248         else if (IS_GEN5(dev_priv))
249                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
250         else
251                 return 270000;
252 }
253
254 static const intel_limit_t intel_limits_i8xx_dac = {
255         .dot = { .min = 25000, .max = 350000 },
256         .vco = { .min = 908000, .max = 1512000 },
257         .n = { .min = 2, .max = 16 },
258         .m = { .min = 96, .max = 140 },
259         .m1 = { .min = 18, .max = 26 },
260         .m2 = { .min = 6, .max = 16 },
261         .p = { .min = 4, .max = 128 },
262         .p1 = { .min = 2, .max = 33 },
263         .p2 = { .dot_limit = 165000,
264                 .p2_slow = 4, .p2_fast = 2 },
265 };
266
267 static const intel_limit_t intel_limits_i8xx_dvo = {
268         .dot = { .min = 25000, .max = 350000 },
269         .vco = { .min = 908000, .max = 1512000 },
270         .n = { .min = 2, .max = 16 },
271         .m = { .min = 96, .max = 140 },
272         .m1 = { .min = 18, .max = 26 },
273         .m2 = { .min = 6, .max = 16 },
274         .p = { .min = 4, .max = 128 },
275         .p1 = { .min = 2, .max = 33 },
276         .p2 = { .dot_limit = 165000,
277                 .p2_slow = 4, .p2_fast = 4 },
278 };
279
280 static const intel_limit_t intel_limits_i8xx_lvds = {
281         .dot = { .min = 25000, .max = 350000 },
282         .vco = { .min = 908000, .max = 1512000 },
283         .n = { .min = 2, .max = 16 },
284         .m = { .min = 96, .max = 140 },
285         .m1 = { .min = 18, .max = 26 },
286         .m2 = { .min = 6, .max = 16 },
287         .p = { .min = 4, .max = 128 },
288         .p1 = { .min = 1, .max = 6 },
289         .p2 = { .dot_limit = 165000,
290                 .p2_slow = 14, .p2_fast = 7 },
291 };
292
293 static const intel_limit_t intel_limits_i9xx_sdvo = {
294         .dot = { .min = 20000, .max = 400000 },
295         .vco = { .min = 1400000, .max = 2800000 },
296         .n = { .min = 1, .max = 6 },
297         .m = { .min = 70, .max = 120 },
298         .m1 = { .min = 8, .max = 18 },
299         .m2 = { .min = 3, .max = 7 },
300         .p = { .min = 5, .max = 80 },
301         .p1 = { .min = 1, .max = 8 },
302         .p2 = { .dot_limit = 200000,
303                 .p2_slow = 10, .p2_fast = 5 },
304 };
305
306 static const intel_limit_t intel_limits_i9xx_lvds = {
307         .dot = { .min = 20000, .max = 400000 },
308         .vco = { .min = 1400000, .max = 2800000 },
309         .n = { .min = 1, .max = 6 },
310         .m = { .min = 70, .max = 120 },
311         .m1 = { .min = 8, .max = 18 },
312         .m2 = { .min = 3, .max = 7 },
313         .p = { .min = 7, .max = 98 },
314         .p1 = { .min = 1, .max = 8 },
315         .p2 = { .dot_limit = 112000,
316                 .p2_slow = 14, .p2_fast = 7 },
317 };
318
319
320 static const intel_limit_t intel_limits_g4x_sdvo = {
321         .dot = { .min = 25000, .max = 270000 },
322         .vco = { .min = 1750000, .max = 3500000},
323         .n = { .min = 1, .max = 4 },
324         .m = { .min = 104, .max = 138 },
325         .m1 = { .min = 17, .max = 23 },
326         .m2 = { .min = 5, .max = 11 },
327         .p = { .min = 10, .max = 30 },
328         .p1 = { .min = 1, .max = 3},
329         .p2 = { .dot_limit = 270000,
330                 .p2_slow = 10,
331                 .p2_fast = 10
332         },
333 };
334
335 static const intel_limit_t intel_limits_g4x_hdmi = {
336         .dot = { .min = 22000, .max = 400000 },
337         .vco = { .min = 1750000, .max = 3500000},
338         .n = { .min = 1, .max = 4 },
339         .m = { .min = 104, .max = 138 },
340         .m1 = { .min = 16, .max = 23 },
341         .m2 = { .min = 5, .max = 11 },
342         .p = { .min = 5, .max = 80 },
343         .p1 = { .min = 1, .max = 8},
344         .p2 = { .dot_limit = 165000,
345                 .p2_slow = 10, .p2_fast = 5 },
346 };
347
348 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
349         .dot = { .min = 20000, .max = 115000 },
350         .vco = { .min = 1750000, .max = 3500000 },
351         .n = { .min = 1, .max = 3 },
352         .m = { .min = 104, .max = 138 },
353         .m1 = { .min = 17, .max = 23 },
354         .m2 = { .min = 5, .max = 11 },
355         .p = { .min = 28, .max = 112 },
356         .p1 = { .min = 2, .max = 8 },
357         .p2 = { .dot_limit = 0,
358                 .p2_slow = 14, .p2_fast = 14
359         },
360 };
361
362 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
363         .dot = { .min = 80000, .max = 224000 },
364         .vco = { .min = 1750000, .max = 3500000 },
365         .n = { .min = 1, .max = 3 },
366         .m = { .min = 104, .max = 138 },
367         .m1 = { .min = 17, .max = 23 },
368         .m2 = { .min = 5, .max = 11 },
369         .p = { .min = 14, .max = 42 },
370         .p1 = { .min = 2, .max = 6 },
371         .p2 = { .dot_limit = 0,
372                 .p2_slow = 7, .p2_fast = 7
373         },
374 };
375
376 static const intel_limit_t intel_limits_pineview_sdvo = {
377         .dot = { .min = 20000, .max = 400000},
378         .vco = { .min = 1700000, .max = 3500000 },
379         /* Pineview's Ncounter is a ring counter */
380         .n = { .min = 3, .max = 6 },
381         .m = { .min = 2, .max = 256 },
382         /* Pineview only has one combined m divider, which we treat as m2. */
383         .m1 = { .min = 0, .max = 0 },
384         .m2 = { .min = 0, .max = 254 },
385         .p = { .min = 5, .max = 80 },
386         .p1 = { .min = 1, .max = 8 },
387         .p2 = { .dot_limit = 200000,
388                 .p2_slow = 10, .p2_fast = 5 },
389 };
390
391 static const intel_limit_t intel_limits_pineview_lvds = {
392         .dot = { .min = 20000, .max = 400000 },
393         .vco = { .min = 1700000, .max = 3500000 },
394         .n = { .min = 3, .max = 6 },
395         .m = { .min = 2, .max = 256 },
396         .m1 = { .min = 0, .max = 0 },
397         .m2 = { .min = 0, .max = 254 },
398         .p = { .min = 7, .max = 112 },
399         .p1 = { .min = 1, .max = 8 },
400         .p2 = { .dot_limit = 112000,
401                 .p2_slow = 14, .p2_fast = 14 },
402 };
403
404 /* Ironlake / Sandybridge
405  *
406  * We calculate clock using (register_value + 2) for N/M1/M2, so here
407  * the range value for them is (actual_value - 2).
408  */
409 static const intel_limit_t intel_limits_ironlake_dac = {
410         .dot = { .min = 25000, .max = 350000 },
411         .vco = { .min = 1760000, .max = 3510000 },
412         .n = { .min = 1, .max = 5 },
413         .m = { .min = 79, .max = 127 },
414         .m1 = { .min = 12, .max = 22 },
415         .m2 = { .min = 5, .max = 9 },
416         .p = { .min = 5, .max = 80 },
417         .p1 = { .min = 1, .max = 8 },
418         .p2 = { .dot_limit = 225000,
419                 .p2_slow = 10, .p2_fast = 5 },
420 };
421
422 static const intel_limit_t intel_limits_ironlake_single_lvds = {
423         .dot = { .min = 25000, .max = 350000 },
424         .vco = { .min = 1760000, .max = 3510000 },
425         .n = { .min = 1, .max = 3 },
426         .m = { .min = 79, .max = 118 },
427         .m1 = { .min = 12, .max = 22 },
428         .m2 = { .min = 5, .max = 9 },
429         .p = { .min = 28, .max = 112 },
430         .p1 = { .min = 2, .max = 8 },
431         .p2 = { .dot_limit = 225000,
432                 .p2_slow = 14, .p2_fast = 14 },
433 };
434
435 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
436         .dot = { .min = 25000, .max = 350000 },
437         .vco = { .min = 1760000, .max = 3510000 },
438         .n = { .min = 1, .max = 3 },
439         .m = { .min = 79, .max = 127 },
440         .m1 = { .min = 12, .max = 22 },
441         .m2 = { .min = 5, .max = 9 },
442         .p = { .min = 14, .max = 56 },
443         .p1 = { .min = 2, .max = 8 },
444         .p2 = { .dot_limit = 225000,
445                 .p2_slow = 7, .p2_fast = 7 },
446 };
447
448 /* LVDS 100mhz refclk limits. */
449 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
450         .dot = { .min = 25000, .max = 350000 },
451         .vco = { .min = 1760000, .max = 3510000 },
452         .n = { .min = 1, .max = 2 },
453         .m = { .min = 79, .max = 126 },
454         .m1 = { .min = 12, .max = 22 },
455         .m2 = { .min = 5, .max = 9 },
456         .p = { .min = 28, .max = 112 },
457         .p1 = { .min = 2, .max = 8 },
458         .p2 = { .dot_limit = 225000,
459                 .p2_slow = 14, .p2_fast = 14 },
460 };
461
462 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
463         .dot = { .min = 25000, .max = 350000 },
464         .vco = { .min = 1760000, .max = 3510000 },
465         .n = { .min = 1, .max = 3 },
466         .m = { .min = 79, .max = 126 },
467         .m1 = { .min = 12, .max = 22 },
468         .m2 = { .min = 5, .max = 9 },
469         .p = { .min = 14, .max = 42 },
470         .p1 = { .min = 2, .max = 6 },
471         .p2 = { .dot_limit = 225000,
472                 .p2_slow = 7, .p2_fast = 7 },
473 };
474
475 static const intel_limit_t intel_limits_vlv = {
476          /*
477           * These are the data rate limits (measured in fast clocks)
478           * since those are the strictest limits we have. The fast
479           * clock and actual rate limits are more relaxed, so checking
480           * them would make no difference.
481           */
482         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
483         .vco = { .min = 4000000, .max = 6000000 },
484         .n = { .min = 1, .max = 7 },
485         .m1 = { .min = 2, .max = 3 },
486         .m2 = { .min = 11, .max = 156 },
487         .p1 = { .min = 2, .max = 3 },
488         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
489 };
490
491 static const intel_limit_t intel_limits_chv = {
492         /*
493          * These are the data rate limits (measured in fast clocks)
494          * since those are the strictest limits we have.  The fast
495          * clock and actual rate limits are more relaxed, so checking
496          * them would make no difference.
497          */
498         .dot = { .min = 25000 * 5, .max = 540000 * 5},
499         .vco = { .min = 4800000, .max = 6480000 },
500         .n = { .min = 1, .max = 1 },
501         .m1 = { .min = 2, .max = 2 },
502         .m2 = { .min = 24 << 22, .max = 175 << 22 },
503         .p1 = { .min = 2, .max = 4 },
504         .p2 = { .p2_slow = 1, .p2_fast = 14 },
505 };
506
507 static const intel_limit_t intel_limits_bxt = {
508         /* FIXME: find real dot limits */
509         .dot = { .min = 0, .max = INT_MAX },
510         .vco = { .min = 4800000, .max = 6700000 },
511         .n = { .min = 1, .max = 1 },
512         .m1 = { .min = 2, .max = 2 },
513         /* FIXME: find real m2 limits */
514         .m2 = { .min = 2 << 22, .max = 255 << 22 },
515         .p1 = { .min = 2, .max = 4 },
516         .p2 = { .p2_slow = 1, .p2_fast = 20 },
517 };
518
519 static bool
520 needs_modeset(struct drm_crtc_state *state)
521 {
522         return drm_atomic_crtc_needs_modeset(state);
523 }
524
525 /**
526  * Returns whether any output on the specified pipe is of the specified type
527  */
528 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
529 {
530         struct drm_device *dev = crtc->base.dev;
531         struct intel_encoder *encoder;
532
533         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
534                 if (encoder->type == type)
535                         return true;
536
537         return false;
538 }
539
540 /**
541  * Returns whether any output on the specified pipe will have the specified
542  * type after a staged modeset is complete, i.e., the same as
543  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
544  * encoder->crtc.
545  */
546 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
547                                       int type)
548 {
549         struct drm_atomic_state *state = crtc_state->base.state;
550         struct drm_connector *connector;
551         struct drm_connector_state *connector_state;
552         struct intel_encoder *encoder;
553         int i, num_connectors = 0;
554
555         for_each_connector_in_state(state, connector, connector_state, i) {
556                 if (connector_state->crtc != crtc_state->base.crtc)
557                         continue;
558
559                 num_connectors++;
560
561                 encoder = to_intel_encoder(connector_state->best_encoder);
562                 if (encoder->type == type)
563                         return true;
564         }
565
566         WARN_ON(num_connectors == 0);
567
568         return false;
569 }
570
571 static const intel_limit_t *
572 intel_ironlake_limit(struct intel_crtc_state *crtc_state, int refclk)
573 {
574         struct drm_device *dev = crtc_state->base.crtc->dev;
575         const intel_limit_t *limit;
576
577         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
578                 if (intel_is_dual_link_lvds(dev)) {
579                         if (refclk == 100000)
580                                 limit = &intel_limits_ironlake_dual_lvds_100m;
581                         else
582                                 limit = &intel_limits_ironlake_dual_lvds;
583                 } else {
584                         if (refclk == 100000)
585                                 limit = &intel_limits_ironlake_single_lvds_100m;
586                         else
587                                 limit = &intel_limits_ironlake_single_lvds;
588                 }
589         } else
590                 limit = &intel_limits_ironlake_dac;
591
592         return limit;
593 }
594
595 static const intel_limit_t *
596 intel_g4x_limit(struct intel_crtc_state *crtc_state)
597 {
598         struct drm_device *dev = crtc_state->base.crtc->dev;
599         const intel_limit_t *limit;
600
601         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
602                 if (intel_is_dual_link_lvds(dev))
603                         limit = &intel_limits_g4x_dual_channel_lvds;
604                 else
605                         limit = &intel_limits_g4x_single_channel_lvds;
606         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
607                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
608                 limit = &intel_limits_g4x_hdmi;
609         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
610                 limit = &intel_limits_g4x_sdvo;
611         } else /* The option is for other outputs */
612                 limit = &intel_limits_i9xx_sdvo;
613
614         return limit;
615 }
616
617 static const intel_limit_t *
618 intel_limit(struct intel_crtc_state *crtc_state, int refclk)
619 {
620         struct drm_device *dev = crtc_state->base.crtc->dev;
621         const intel_limit_t *limit;
622
623         if (IS_BROXTON(dev))
624                 limit = &intel_limits_bxt;
625         else if (HAS_PCH_SPLIT(dev))
626                 limit = intel_ironlake_limit(crtc_state, refclk);
627         else if (IS_G4X(dev)) {
628                 limit = intel_g4x_limit(crtc_state);
629         } else if (IS_PINEVIEW(dev)) {
630                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
631                         limit = &intel_limits_pineview_lvds;
632                 else
633                         limit = &intel_limits_pineview_sdvo;
634         } else if (IS_CHERRYVIEW(dev)) {
635                 limit = &intel_limits_chv;
636         } else if (IS_VALLEYVIEW(dev)) {
637                 limit = &intel_limits_vlv;
638         } else if (!IS_GEN2(dev)) {
639                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
640                         limit = &intel_limits_i9xx_lvds;
641                 else
642                         limit = &intel_limits_i9xx_sdvo;
643         } else {
644                 if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
645                         limit = &intel_limits_i8xx_lvds;
646                 else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
647                         limit = &intel_limits_i8xx_dvo;
648                 else
649                         limit = &intel_limits_i8xx_dac;
650         }
651         return limit;
652 }
653
654 /*
655  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
656  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
657  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
658  * The helpers' return value is the rate of the clock that is fed to the
659  * display engine's pipe which can be the above fast dot clock rate or a
660  * divided-down version of it.
661  */
662 /* m1 is reserved as 0 in Pineview, n is a ring counter */
663 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
664 {
665         clock->m = clock->m2 + 2;
666         clock->p = clock->p1 * clock->p2;
667         if (WARN_ON(clock->n == 0 || clock->p == 0))
668                 return 0;
669         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
670         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
671
672         return clock->dot;
673 }
674
675 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
676 {
677         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
678 }
679
680 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
681 {
682         clock->m = i9xx_dpll_compute_m(clock);
683         clock->p = clock->p1 * clock->p2;
684         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
685                 return 0;
686         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
687         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
688
689         return clock->dot;
690 }
691
692 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
693 {
694         clock->m = clock->m1 * clock->m2;
695         clock->p = clock->p1 * clock->p2;
696         if (WARN_ON(clock->n == 0 || clock->p == 0))
697                 return 0;
698         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
699         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
700
701         return clock->dot / 5;
702 }
703
704 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
705 {
706         clock->m = clock->m1 * clock->m2;
707         clock->p = clock->p1 * clock->p2;
708         if (WARN_ON(clock->n == 0 || clock->p == 0))
709                 return 0;
710         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
711                         clock->n << 22);
712         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
713
714         return clock->dot / 5;
715 }
716
717 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
718 /**
719  * Returns whether the given set of divisors are valid for a given refclk with
720  * the given connectors.
721  */
722
723 static bool intel_PLL_is_valid(struct drm_device *dev,
724                                const intel_limit_t *limit,
725                                const intel_clock_t *clock)
726 {
727         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
728                 INTELPllInvalid("n out of range\n");
729         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
730                 INTELPllInvalid("p1 out of range\n");
731         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
732                 INTELPllInvalid("m2 out of range\n");
733         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
734                 INTELPllInvalid("m1 out of range\n");
735
736         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
737             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
738                 if (clock->m1 <= clock->m2)
739                         INTELPllInvalid("m1 <= m2\n");
740
741         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
742                 if (clock->p < limit->p.min || limit->p.max < clock->p)
743                         INTELPllInvalid("p out of range\n");
744                 if (clock->m < limit->m.min || limit->m.max < clock->m)
745                         INTELPllInvalid("m out of range\n");
746         }
747
748         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
749                 INTELPllInvalid("vco out of range\n");
750         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
751          * connector, etc., rather than just a single range.
752          */
753         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
754                 INTELPllInvalid("dot out of range\n");
755
756         return true;
757 }
758
759 static int
760 i9xx_select_p2_div(const intel_limit_t *limit,
761                    const struct intel_crtc_state *crtc_state,
762                    int target)
763 {
764         struct drm_device *dev = crtc_state->base.crtc->dev;
765
766         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
767                 /*
768                  * For LVDS just rely on its current settings for dual-channel.
769                  * We haven't figured out how to reliably set up different
770                  * single/dual channel state, if we even can.
771                  */
772                 if (intel_is_dual_link_lvds(dev))
773                         return limit->p2.p2_fast;
774                 else
775                         return limit->p2.p2_slow;
776         } else {
777                 if (target < limit->p2.dot_limit)
778                         return limit->p2.p2_slow;
779                 else
780                         return limit->p2.p2_fast;
781         }
782 }
783
784 static bool
785 i9xx_find_best_dpll(const intel_limit_t *limit,
786                     struct intel_crtc_state *crtc_state,
787                     int target, int refclk, intel_clock_t *match_clock,
788                     intel_clock_t *best_clock)
789 {
790         struct drm_device *dev = crtc_state->base.crtc->dev;
791         intel_clock_t clock;
792         int err = target;
793
794         memset(best_clock, 0, sizeof(*best_clock));
795
796         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
797
798         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
799              clock.m1++) {
800                 for (clock.m2 = limit->m2.min;
801                      clock.m2 <= limit->m2.max; clock.m2++) {
802                         if (clock.m2 >= clock.m1)
803                                 break;
804                         for (clock.n = limit->n.min;
805                              clock.n <= limit->n.max; clock.n++) {
806                                 for (clock.p1 = limit->p1.min;
807                                         clock.p1 <= limit->p1.max; clock.p1++) {
808                                         int this_err;
809
810                                         i9xx_calc_dpll_params(refclk, &clock);
811                                         if (!intel_PLL_is_valid(dev, limit,
812                                                                 &clock))
813                                                 continue;
814                                         if (match_clock &&
815                                             clock.p != match_clock->p)
816                                                 continue;
817
818                                         this_err = abs(clock.dot - target);
819                                         if (this_err < err) {
820                                                 *best_clock = clock;
821                                                 err = this_err;
822                                         }
823                                 }
824                         }
825                 }
826         }
827
828         return (err != target);
829 }
830
831 static bool
832 pnv_find_best_dpll(const intel_limit_t *limit,
833                    struct intel_crtc_state *crtc_state,
834                    int target, int refclk, intel_clock_t *match_clock,
835                    intel_clock_t *best_clock)
836 {
837         struct drm_device *dev = crtc_state->base.crtc->dev;
838         intel_clock_t clock;
839         int err = target;
840
841         memset(best_clock, 0, sizeof(*best_clock));
842
843         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
844
845         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
846              clock.m1++) {
847                 for (clock.m2 = limit->m2.min;
848                      clock.m2 <= limit->m2.max; clock.m2++) {
849                         for (clock.n = limit->n.min;
850                              clock.n <= limit->n.max; clock.n++) {
851                                 for (clock.p1 = limit->p1.min;
852                                         clock.p1 <= limit->p1.max; clock.p1++) {
853                                         int this_err;
854
855                                         pnv_calc_dpll_params(refclk, &clock);
856                                         if (!intel_PLL_is_valid(dev, limit,
857                                                                 &clock))
858                                                 continue;
859                                         if (match_clock &&
860                                             clock.p != match_clock->p)
861                                                 continue;
862
863                                         this_err = abs(clock.dot - target);
864                                         if (this_err < err) {
865                                                 *best_clock = clock;
866                                                 err = this_err;
867                                         }
868                                 }
869                         }
870                 }
871         }
872
873         return (err != target);
874 }
875
876 static bool
877 g4x_find_best_dpll(const intel_limit_t *limit,
878                    struct intel_crtc_state *crtc_state,
879                    int target, int refclk, intel_clock_t *match_clock,
880                    intel_clock_t *best_clock)
881 {
882         struct drm_device *dev = crtc_state->base.crtc->dev;
883         intel_clock_t clock;
884         int max_n;
885         bool found = false;
886         /* approximately equals target * 0.00585 */
887         int err_most = (target >> 8) + (target >> 9);
888
889         memset(best_clock, 0, sizeof(*best_clock));
890
891         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
892
893         max_n = limit->n.max;
894         /* based on hardware requirement, prefer smaller n to precision */
895         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
896                 /* based on hardware requirement, prefere larger m1,m2 */
897                 for (clock.m1 = limit->m1.max;
898                      clock.m1 >= limit->m1.min; clock.m1--) {
899                         for (clock.m2 = limit->m2.max;
900                              clock.m2 >= limit->m2.min; clock.m2--) {
901                                 for (clock.p1 = limit->p1.max;
902                                      clock.p1 >= limit->p1.min; clock.p1--) {
903                                         int this_err;
904
905                                         i9xx_calc_dpll_params(refclk, &clock);
906                                         if (!intel_PLL_is_valid(dev, limit,
907                                                                 &clock))
908                                                 continue;
909
910                                         this_err = abs(clock.dot - target);
911                                         if (this_err < err_most) {
912                                                 *best_clock = clock;
913                                                 err_most = this_err;
914                                                 max_n = clock.n;
915                                                 found = true;
916                                         }
917                                 }
918                         }
919                 }
920         }
921         return found;
922 }
923
924 /*
925  * Check if the calculated PLL configuration is more optimal compared to the
926  * best configuration and error found so far. Return the calculated error.
927  */
928 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
929                                const intel_clock_t *calculated_clock,
930                                const intel_clock_t *best_clock,
931                                unsigned int best_error_ppm,
932                                unsigned int *error_ppm)
933 {
934         /*
935          * For CHV ignore the error and consider only the P value.
936          * Prefer a bigger P value based on HW requirements.
937          */
938         if (IS_CHERRYVIEW(dev)) {
939                 *error_ppm = 0;
940
941                 return calculated_clock->p > best_clock->p;
942         }
943
944         if (WARN_ON_ONCE(!target_freq))
945                 return false;
946
947         *error_ppm = div_u64(1000000ULL *
948                                 abs(target_freq - calculated_clock->dot),
949                              target_freq);
950         /*
951          * Prefer a better P value over a better (smaller) error if the error
952          * is small. Ensure this preference for future configurations too by
953          * setting the error to 0.
954          */
955         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
956                 *error_ppm = 0;
957
958                 return true;
959         }
960
961         return *error_ppm + 10 < best_error_ppm;
962 }
963
964 static bool
965 vlv_find_best_dpll(const intel_limit_t *limit,
966                    struct intel_crtc_state *crtc_state,
967                    int target, int refclk, intel_clock_t *match_clock,
968                    intel_clock_t *best_clock)
969 {
970         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
971         struct drm_device *dev = crtc->base.dev;
972         intel_clock_t clock;
973         unsigned int bestppm = 1000000;
974         /* min update 19.2 MHz */
975         int max_n = min(limit->n.max, refclk / 19200);
976         bool found = false;
977
978         target *= 5; /* fast clock */
979
980         memset(best_clock, 0, sizeof(*best_clock));
981
982         /* based on hardware requirement, prefer smaller n to precision */
983         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
984                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
985                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
986                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
987                                 clock.p = clock.p1 * clock.p2;
988                                 /* based on hardware requirement, prefer bigger m1,m2 values */
989                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
990                                         unsigned int ppm;
991
992                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
993                                                                      refclk * clock.m1);
994
995                                         vlv_calc_dpll_params(refclk, &clock);
996
997                                         if (!intel_PLL_is_valid(dev, limit,
998                                                                 &clock))
999                                                 continue;
1000
1001                                         if (!vlv_PLL_is_optimal(dev, target,
1002                                                                 &clock,
1003                                                                 best_clock,
1004                                                                 bestppm, &ppm))
1005                                                 continue;
1006
1007                                         *best_clock = clock;
1008                                         bestppm = ppm;
1009                                         found = true;
1010                                 }
1011                         }
1012                 }
1013         }
1014
1015         return found;
1016 }
1017
1018 static bool
1019 chv_find_best_dpll(const intel_limit_t *limit,
1020                    struct intel_crtc_state *crtc_state,
1021                    int target, int refclk, intel_clock_t *match_clock,
1022                    intel_clock_t *best_clock)
1023 {
1024         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1025         struct drm_device *dev = crtc->base.dev;
1026         unsigned int best_error_ppm;
1027         intel_clock_t clock;
1028         uint64_t m2;
1029         int found = false;
1030
1031         memset(best_clock, 0, sizeof(*best_clock));
1032         best_error_ppm = 1000000;
1033
1034         /*
1035          * Based on hardware doc, the n always set to 1, and m1 always
1036          * set to 2.  If requires to support 200Mhz refclk, we need to
1037          * revisit this because n may not 1 anymore.
1038          */
1039         clock.n = 1, clock.m1 = 2;
1040         target *= 5;    /* fast clock */
1041
1042         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
1043                 for (clock.p2 = limit->p2.p2_fast;
1044                                 clock.p2 >= limit->p2.p2_slow;
1045                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1046                         unsigned int error_ppm;
1047
1048                         clock.p = clock.p1 * clock.p2;
1049
1050                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1051                                         clock.n) << 22, refclk * clock.m1);
1052
1053                         if (m2 > INT_MAX/clock.m1)
1054                                 continue;
1055
1056                         clock.m2 = m2;
1057
1058                         chv_calc_dpll_params(refclk, &clock);
1059
1060                         if (!intel_PLL_is_valid(dev, limit, &clock))
1061                                 continue;
1062
1063                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1064                                                 best_error_ppm, &error_ppm))
1065                                 continue;
1066
1067                         *best_clock = clock;
1068                         best_error_ppm = error_ppm;
1069                         found = true;
1070                 }
1071         }
1072
1073         return found;
1074 }
1075
1076 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1077                         intel_clock_t *best_clock)
1078 {
1079         int refclk = i9xx_get_refclk(crtc_state, 0);
1080
1081         return chv_find_best_dpll(intel_limit(crtc_state, refclk), crtc_state,
1082                                   target_clock, refclk, NULL, best_clock);
1083 }
1084
1085 bool intel_crtc_active(struct drm_crtc *crtc)
1086 {
1087         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1088
1089         /* Be paranoid as we can arrive here with only partial
1090          * state retrieved from the hardware during setup.
1091          *
1092          * We can ditch the adjusted_mode.crtc_clock check as soon
1093          * as Haswell has gained clock readout/fastboot support.
1094          *
1095          * We can ditch the crtc->primary->fb check as soon as we can
1096          * properly reconstruct framebuffers.
1097          *
1098          * FIXME: The intel_crtc->active here should be switched to
1099          * crtc->state->active once we have proper CRTC states wired up
1100          * for atomic.
1101          */
1102         return intel_crtc->active && crtc->primary->state->fb &&
1103                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1104 }
1105
1106 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1107                                              enum pipe pipe)
1108 {
1109         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1110         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1111
1112         return intel_crtc->config->cpu_transcoder;
1113 }
1114
1115 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1116 {
1117         struct drm_i915_private *dev_priv = dev->dev_private;
1118         i915_reg_t reg = PIPEDSL(pipe);
1119         u32 line1, line2;
1120         u32 line_mask;
1121
1122         if (IS_GEN2(dev))
1123                 line_mask = DSL_LINEMASK_GEN2;
1124         else
1125                 line_mask = DSL_LINEMASK_GEN3;
1126
1127         line1 = I915_READ(reg) & line_mask;
1128         msleep(5);
1129         line2 = I915_READ(reg) & line_mask;
1130
1131         return line1 == line2;
1132 }
1133
1134 /*
1135  * intel_wait_for_pipe_off - wait for pipe to turn off
1136  * @crtc: crtc whose pipe to wait for
1137  *
1138  * After disabling a pipe, we can't wait for vblank in the usual way,
1139  * spinning on the vblank interrupt status bit, since we won't actually
1140  * see an interrupt when the pipe is disabled.
1141  *
1142  * On Gen4 and above:
1143  *   wait for the pipe register state bit to turn off
1144  *
1145  * Otherwise:
1146  *   wait for the display line value to settle (it usually
1147  *   ends up stopping at the start of the next frame).
1148  *
1149  */
1150 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1151 {
1152         struct drm_device *dev = crtc->base.dev;
1153         struct drm_i915_private *dev_priv = dev->dev_private;
1154         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1155         enum pipe pipe = crtc->pipe;
1156
1157         if (INTEL_INFO(dev)->gen >= 4) {
1158                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1159
1160                 /* Wait for the Pipe State to go off */
1161                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1162                              100))
1163                         WARN(1, "pipe_off wait timed out\n");
1164         } else {
1165                 /* Wait for the display line to settle */
1166                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1167                         WARN(1, "pipe_off wait timed out\n");
1168         }
1169 }
1170
1171 /* Only for pre-ILK configs */
1172 void assert_pll(struct drm_i915_private *dev_priv,
1173                 enum pipe pipe, bool state)
1174 {
1175         u32 val;
1176         bool cur_state;
1177
1178         val = I915_READ(DPLL(pipe));
1179         cur_state = !!(val & DPLL_VCO_ENABLE);
1180         I915_STATE_WARN(cur_state != state,
1181              "PLL state assertion failure (expected %s, current %s)\n",
1182                         onoff(state), onoff(cur_state));
1183 }
1184
1185 /* XXX: the dsi pll is shared between MIPI DSI ports */
1186 static void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1187 {
1188         u32 val;
1189         bool cur_state;
1190
1191         mutex_lock(&dev_priv->sb_lock);
1192         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1193         mutex_unlock(&dev_priv->sb_lock);
1194
1195         cur_state = val & DSI_PLL_VCO_EN;
1196         I915_STATE_WARN(cur_state != state,
1197              "DSI PLL state assertion failure (expected %s, current %s)\n",
1198                         onoff(state), onoff(cur_state));
1199 }
1200 #define assert_dsi_pll_enabled(d) assert_dsi_pll(d, true)
1201 #define assert_dsi_pll_disabled(d) assert_dsi_pll(d, false)
1202
1203 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1204                           enum pipe pipe, bool state)
1205 {
1206         bool cur_state;
1207         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1208                                                                       pipe);
1209
1210         if (HAS_DDI(dev_priv->dev)) {
1211                 /* DDI does not have a specific FDI_TX register */
1212                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1213                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1214         } else {
1215                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1216                 cur_state = !!(val & FDI_TX_ENABLE);
1217         }
1218         I915_STATE_WARN(cur_state != state,
1219              "FDI TX state assertion failure (expected %s, current %s)\n",
1220                         onoff(state), onoff(cur_state));
1221 }
1222 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1223 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1224
1225 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1226                           enum pipe pipe, bool state)
1227 {
1228         u32 val;
1229         bool cur_state;
1230
1231         val = I915_READ(FDI_RX_CTL(pipe));
1232         cur_state = !!(val & FDI_RX_ENABLE);
1233         I915_STATE_WARN(cur_state != state,
1234              "FDI RX state assertion failure (expected %s, current %s)\n",
1235                         onoff(state), onoff(cur_state));
1236 }
1237 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1238 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1239
1240 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1241                                       enum pipe pipe)
1242 {
1243         u32 val;
1244
1245         /* ILK FDI PLL is always enabled */
1246         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1247                 return;
1248
1249         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1250         if (HAS_DDI(dev_priv->dev))
1251                 return;
1252
1253         val = I915_READ(FDI_TX_CTL(pipe));
1254         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1255 }
1256
1257 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1258                        enum pipe pipe, bool state)
1259 {
1260         u32 val;
1261         bool cur_state;
1262
1263         val = I915_READ(FDI_RX_CTL(pipe));
1264         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1265         I915_STATE_WARN(cur_state != state,
1266              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1267                         onoff(state), onoff(cur_state));
1268 }
1269
1270 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1271                            enum pipe pipe)
1272 {
1273         struct drm_device *dev = dev_priv->dev;
1274         i915_reg_t pp_reg;
1275         u32 val;
1276         enum pipe panel_pipe = PIPE_A;
1277         bool locked = true;
1278
1279         if (WARN_ON(HAS_DDI(dev)))
1280                 return;
1281
1282         if (HAS_PCH_SPLIT(dev)) {
1283                 u32 port_sel;
1284
1285                 pp_reg = PCH_PP_CONTROL;
1286                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1287
1288                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1289                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1290                         panel_pipe = PIPE_B;
1291                 /* XXX: else fix for eDP */
1292         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1293                 /* presumably write lock depends on pipe, not port select */
1294                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1295                 panel_pipe = pipe;
1296         } else {
1297                 pp_reg = PP_CONTROL;
1298                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1299                         panel_pipe = PIPE_B;
1300         }
1301
1302         val = I915_READ(pp_reg);
1303         if (!(val & PANEL_POWER_ON) ||
1304             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1305                 locked = false;
1306
1307         I915_STATE_WARN(panel_pipe == pipe && locked,
1308              "panel assertion failure, pipe %c regs locked\n",
1309              pipe_name(pipe));
1310 }
1311
1312 static void assert_cursor(struct drm_i915_private *dev_priv,
1313                           enum pipe pipe, bool state)
1314 {
1315         struct drm_device *dev = dev_priv->dev;
1316         bool cur_state;
1317
1318         if (IS_845G(dev) || IS_I865G(dev))
1319                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1320         else
1321                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1322
1323         I915_STATE_WARN(cur_state != state,
1324              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1325                         pipe_name(pipe), onoff(state), onoff(cur_state));
1326 }
1327 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1328 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1329
1330 void assert_pipe(struct drm_i915_private *dev_priv,
1331                  enum pipe pipe, bool state)
1332 {
1333         bool cur_state;
1334         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1335                                                                       pipe);
1336         enum intel_display_power_domain power_domain;
1337
1338         /* if we need the pipe quirk it must be always on */
1339         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1340             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1341                 state = true;
1342
1343         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1344         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1345                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1346                 cur_state = !!(val & PIPECONF_ENABLE);
1347
1348                 intel_display_power_put(dev_priv, power_domain);
1349         } else {
1350                 cur_state = false;
1351         }
1352
1353         I915_STATE_WARN(cur_state != state,
1354              "pipe %c assertion failure (expected %s, current %s)\n",
1355                         pipe_name(pipe), onoff(state), onoff(cur_state));
1356 }
1357
1358 static void assert_plane(struct drm_i915_private *dev_priv,
1359                          enum plane plane, bool state)
1360 {
1361         u32 val;
1362         bool cur_state;
1363
1364         val = I915_READ(DSPCNTR(plane));
1365         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1366         I915_STATE_WARN(cur_state != state,
1367              "plane %c assertion failure (expected %s, current %s)\n",
1368                         plane_name(plane), onoff(state), onoff(cur_state));
1369 }
1370
1371 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1372 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1373
1374 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1375                                    enum pipe pipe)
1376 {
1377         struct drm_device *dev = dev_priv->dev;
1378         int i;
1379
1380         /* Primary planes are fixed to pipes on gen4+ */
1381         if (INTEL_INFO(dev)->gen >= 4) {
1382                 u32 val = I915_READ(DSPCNTR(pipe));
1383                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1384                      "plane %c assertion failure, should be disabled but not\n",
1385                      plane_name(pipe));
1386                 return;
1387         }
1388
1389         /* Need to check both planes against the pipe */
1390         for_each_pipe(dev_priv, i) {
1391                 u32 val = I915_READ(DSPCNTR(i));
1392                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1393                         DISPPLANE_SEL_PIPE_SHIFT;
1394                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1395                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1396                      plane_name(i), pipe_name(pipe));
1397         }
1398 }
1399
1400 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1401                                     enum pipe pipe)
1402 {
1403         struct drm_device *dev = dev_priv->dev;
1404         int sprite;
1405
1406         if (INTEL_INFO(dev)->gen >= 9) {
1407                 for_each_sprite(dev_priv, pipe, sprite) {
1408                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1409                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1410                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1411                              sprite, pipe_name(pipe));
1412                 }
1413         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1414                 for_each_sprite(dev_priv, pipe, sprite) {
1415                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1416                         I915_STATE_WARN(val & SP_ENABLE,
1417                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1418                              sprite_name(pipe, sprite), pipe_name(pipe));
1419                 }
1420         } else if (INTEL_INFO(dev)->gen >= 7) {
1421                 u32 val = I915_READ(SPRCTL(pipe));
1422                 I915_STATE_WARN(val & SPRITE_ENABLE,
1423                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1424                      plane_name(pipe), pipe_name(pipe));
1425         } else if (INTEL_INFO(dev)->gen >= 5) {
1426                 u32 val = I915_READ(DVSCNTR(pipe));
1427                 I915_STATE_WARN(val & DVS_ENABLE,
1428                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1429                      plane_name(pipe), pipe_name(pipe));
1430         }
1431 }
1432
1433 static void assert_vblank_disabled(struct drm_crtc *crtc)
1434 {
1435         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1436                 drm_crtc_vblank_put(crtc);
1437 }
1438
1439 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1440                                     enum pipe pipe)
1441 {
1442         u32 val;
1443         bool enabled;
1444
1445         val = I915_READ(PCH_TRANSCONF(pipe));
1446         enabled = !!(val & TRANS_ENABLE);
1447         I915_STATE_WARN(enabled,
1448              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1449              pipe_name(pipe));
1450 }
1451
1452 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1453                             enum pipe pipe, u32 port_sel, u32 val)
1454 {
1455         if ((val & DP_PORT_EN) == 0)
1456                 return false;
1457
1458         if (HAS_PCH_CPT(dev_priv->dev)) {
1459                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1460                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1461                         return false;
1462         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1463                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1464                         return false;
1465         } else {
1466                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1467                         return false;
1468         }
1469         return true;
1470 }
1471
1472 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1473                               enum pipe pipe, u32 val)
1474 {
1475         if ((val & SDVO_ENABLE) == 0)
1476                 return false;
1477
1478         if (HAS_PCH_CPT(dev_priv->dev)) {
1479                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1480                         return false;
1481         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1482                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1483                         return false;
1484         } else {
1485                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1486                         return false;
1487         }
1488         return true;
1489 }
1490
1491 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1492                               enum pipe pipe, u32 val)
1493 {
1494         if ((val & LVDS_PORT_EN) == 0)
1495                 return false;
1496
1497         if (HAS_PCH_CPT(dev_priv->dev)) {
1498                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1499                         return false;
1500         } else {
1501                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1502                         return false;
1503         }
1504         return true;
1505 }
1506
1507 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1508                               enum pipe pipe, u32 val)
1509 {
1510         if ((val & ADPA_DAC_ENABLE) == 0)
1511                 return false;
1512         if (HAS_PCH_CPT(dev_priv->dev)) {
1513                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1514                         return false;
1515         } else {
1516                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1517                         return false;
1518         }
1519         return true;
1520 }
1521
1522 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1523                                    enum pipe pipe, i915_reg_t reg,
1524                                    u32 port_sel)
1525 {
1526         u32 val = I915_READ(reg);
1527         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1528              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1529              i915_mmio_reg_offset(reg), pipe_name(pipe));
1530
1531         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1532              && (val & DP_PIPEB_SELECT),
1533              "IBX PCH dp port still using transcoder B\n");
1534 }
1535
1536 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1537                                      enum pipe pipe, i915_reg_t reg)
1538 {
1539         u32 val = I915_READ(reg);
1540         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1541              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1542              i915_mmio_reg_offset(reg), pipe_name(pipe));
1543
1544         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1545              && (val & SDVO_PIPE_B_SELECT),
1546              "IBX PCH hdmi port still using transcoder B\n");
1547 }
1548
1549 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1550                                       enum pipe pipe)
1551 {
1552         u32 val;
1553
1554         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1555         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1556         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1557
1558         val = I915_READ(PCH_ADPA);
1559         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1560              "PCH VGA enabled on transcoder %c, should be disabled\n",
1561              pipe_name(pipe));
1562
1563         val = I915_READ(PCH_LVDS);
1564         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1565              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1566              pipe_name(pipe));
1567
1568         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1569         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1570         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1571 }
1572
1573 static void vlv_enable_pll(struct intel_crtc *crtc,
1574                            const struct intel_crtc_state *pipe_config)
1575 {
1576         struct drm_device *dev = crtc->base.dev;
1577         struct drm_i915_private *dev_priv = dev->dev_private;
1578         i915_reg_t reg = DPLL(crtc->pipe);
1579         u32 dpll = pipe_config->dpll_hw_state.dpll;
1580
1581         assert_pipe_disabled(dev_priv, crtc->pipe);
1582
1583         /* PLL is protected by panel, make sure we can write it */
1584         if (IS_MOBILE(dev_priv->dev))
1585                 assert_panel_unlocked(dev_priv, crtc->pipe);
1586
1587         I915_WRITE(reg, dpll);
1588         POSTING_READ(reg);
1589         udelay(150);
1590
1591         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1592                 DRM_ERROR("DPLL %d failed to lock\n", crtc->pipe);
1593
1594         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1595         POSTING_READ(DPLL_MD(crtc->pipe));
1596
1597         /* We do this three times for luck */
1598         I915_WRITE(reg, dpll);
1599         POSTING_READ(reg);
1600         udelay(150); /* wait for warmup */
1601         I915_WRITE(reg, dpll);
1602         POSTING_READ(reg);
1603         udelay(150); /* wait for warmup */
1604         I915_WRITE(reg, dpll);
1605         POSTING_READ(reg);
1606         udelay(150); /* wait for warmup */
1607 }
1608
1609 static void chv_enable_pll(struct intel_crtc *crtc,
1610                            const struct intel_crtc_state *pipe_config)
1611 {
1612         struct drm_device *dev = crtc->base.dev;
1613         struct drm_i915_private *dev_priv = dev->dev_private;
1614         int pipe = crtc->pipe;
1615         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1616         u32 tmp;
1617
1618         assert_pipe_disabled(dev_priv, crtc->pipe);
1619
1620         mutex_lock(&dev_priv->sb_lock);
1621
1622         /* Enable back the 10bit clock to display controller */
1623         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1624         tmp |= DPIO_DCLKP_EN;
1625         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1626
1627         mutex_unlock(&dev_priv->sb_lock);
1628
1629         /*
1630          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1631          */
1632         udelay(1);
1633
1634         /* Enable PLL */
1635         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1636
1637         /* Check PLL is locked */
1638         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1639                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1640
1641         /* not sure when this should be written */
1642         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1643         POSTING_READ(DPLL_MD(pipe));
1644 }
1645
1646 static int intel_num_dvo_pipes(struct drm_device *dev)
1647 {
1648         struct intel_crtc *crtc;
1649         int count = 0;
1650
1651         for_each_intel_crtc(dev, crtc)
1652                 count += crtc->base.state->active &&
1653                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1654
1655         return count;
1656 }
1657
1658 static void i9xx_enable_pll(struct intel_crtc *crtc)
1659 {
1660         struct drm_device *dev = crtc->base.dev;
1661         struct drm_i915_private *dev_priv = dev->dev_private;
1662         i915_reg_t reg = DPLL(crtc->pipe);
1663         u32 dpll = crtc->config->dpll_hw_state.dpll;
1664
1665         assert_pipe_disabled(dev_priv, crtc->pipe);
1666
1667         /* No really, not for ILK+ */
1668         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1669
1670         /* PLL is protected by panel, make sure we can write it */
1671         if (IS_MOBILE(dev) && !IS_I830(dev))
1672                 assert_panel_unlocked(dev_priv, crtc->pipe);
1673
1674         /* Enable DVO 2x clock on both PLLs if necessary */
1675         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1676                 /*
1677                  * It appears to be important that we don't enable this
1678                  * for the current pipe before otherwise configuring the
1679                  * PLL. No idea how this should be handled if multiple
1680                  * DVO outputs are enabled simultaneosly.
1681                  */
1682                 dpll |= DPLL_DVO_2X_MODE;
1683                 I915_WRITE(DPLL(!crtc->pipe),
1684                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1685         }
1686
1687         /*
1688          * Apparently we need to have VGA mode enabled prior to changing
1689          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1690          * dividers, even though the register value does change.
1691          */
1692         I915_WRITE(reg, 0);
1693
1694         I915_WRITE(reg, dpll);
1695
1696         /* Wait for the clocks to stabilize. */
1697         POSTING_READ(reg);
1698         udelay(150);
1699
1700         if (INTEL_INFO(dev)->gen >= 4) {
1701                 I915_WRITE(DPLL_MD(crtc->pipe),
1702                            crtc->config->dpll_hw_state.dpll_md);
1703         } else {
1704                 /* The pixel multiplier can only be updated once the
1705                  * DPLL is enabled and the clocks are stable.
1706                  *
1707                  * So write it again.
1708                  */
1709                 I915_WRITE(reg, dpll);
1710         }
1711
1712         /* We do this three times for luck */
1713         I915_WRITE(reg, dpll);
1714         POSTING_READ(reg);
1715         udelay(150); /* wait for warmup */
1716         I915_WRITE(reg, dpll);
1717         POSTING_READ(reg);
1718         udelay(150); /* wait for warmup */
1719         I915_WRITE(reg, dpll);
1720         POSTING_READ(reg);
1721         udelay(150); /* wait for warmup */
1722 }
1723
1724 /**
1725  * i9xx_disable_pll - disable a PLL
1726  * @dev_priv: i915 private structure
1727  * @pipe: pipe PLL to disable
1728  *
1729  * Disable the PLL for @pipe, making sure the pipe is off first.
1730  *
1731  * Note!  This is for pre-ILK only.
1732  */
1733 static void i9xx_disable_pll(struct intel_crtc *crtc)
1734 {
1735         struct drm_device *dev = crtc->base.dev;
1736         struct drm_i915_private *dev_priv = dev->dev_private;
1737         enum pipe pipe = crtc->pipe;
1738
1739         /* Disable DVO 2x clock on both PLLs if necessary */
1740         if (IS_I830(dev) &&
1741             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1742             !intel_num_dvo_pipes(dev)) {
1743                 I915_WRITE(DPLL(PIPE_B),
1744                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1745                 I915_WRITE(DPLL(PIPE_A),
1746                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1747         }
1748
1749         /* Don't disable pipe or pipe PLLs if needed */
1750         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1751             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1752                 return;
1753
1754         /* Make sure the pipe isn't still relying on us */
1755         assert_pipe_disabled(dev_priv, pipe);
1756
1757         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1758         POSTING_READ(DPLL(pipe));
1759 }
1760
1761 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1762 {
1763         u32 val;
1764
1765         /* Make sure the pipe isn't still relying on us */
1766         assert_pipe_disabled(dev_priv, pipe);
1767
1768         /*
1769          * Leave integrated clock source and reference clock enabled for pipe B.
1770          * The latter is needed for VGA hotplug / manual detection.
1771          */
1772         val = DPLL_VGA_MODE_DIS;
1773         if (pipe == PIPE_B)
1774                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1775         I915_WRITE(DPLL(pipe), val);
1776         POSTING_READ(DPLL(pipe));
1777
1778 }
1779
1780 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1781 {
1782         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1783         u32 val;
1784
1785         /* Make sure the pipe isn't still relying on us */
1786         assert_pipe_disabled(dev_priv, pipe);
1787
1788         /* Set PLL en = 0 */
1789         val = DPLL_SSC_REF_CLK_CHV |
1790                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1791         if (pipe != PIPE_A)
1792                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1793         I915_WRITE(DPLL(pipe), val);
1794         POSTING_READ(DPLL(pipe));
1795
1796         mutex_lock(&dev_priv->sb_lock);
1797
1798         /* Disable 10bit clock to display controller */
1799         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1800         val &= ~DPIO_DCLKP_EN;
1801         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1802
1803         mutex_unlock(&dev_priv->sb_lock);
1804 }
1805
1806 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1807                          struct intel_digital_port *dport,
1808                          unsigned int expected_mask)
1809 {
1810         u32 port_mask;
1811         i915_reg_t dpll_reg;
1812
1813         switch (dport->port) {
1814         case PORT_B:
1815                 port_mask = DPLL_PORTB_READY_MASK;
1816                 dpll_reg = DPLL(0);
1817                 break;
1818         case PORT_C:
1819                 port_mask = DPLL_PORTC_READY_MASK;
1820                 dpll_reg = DPLL(0);
1821                 expected_mask <<= 4;
1822                 break;
1823         case PORT_D:
1824                 port_mask = DPLL_PORTD_READY_MASK;
1825                 dpll_reg = DPIO_PHY_STATUS;
1826                 break;
1827         default:
1828                 BUG();
1829         }
1830
1831         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1832                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1833                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1834 }
1835
1836 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1837                                            enum pipe pipe)
1838 {
1839         struct drm_device *dev = dev_priv->dev;
1840         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1841         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1842         i915_reg_t reg;
1843         uint32_t val, pipeconf_val;
1844
1845         /* PCH only available on ILK+ */
1846         BUG_ON(!HAS_PCH_SPLIT(dev));
1847
1848         /* Make sure PCH DPLL is enabled */
1849         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1850
1851         /* FDI must be feeding us bits for PCH ports */
1852         assert_fdi_tx_enabled(dev_priv, pipe);
1853         assert_fdi_rx_enabled(dev_priv, pipe);
1854
1855         if (HAS_PCH_CPT(dev)) {
1856                 /* Workaround: Set the timing override bit before enabling the
1857                  * pch transcoder. */
1858                 reg = TRANS_CHICKEN2(pipe);
1859                 val = I915_READ(reg);
1860                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1861                 I915_WRITE(reg, val);
1862         }
1863
1864         reg = PCH_TRANSCONF(pipe);
1865         val = I915_READ(reg);
1866         pipeconf_val = I915_READ(PIPECONF(pipe));
1867
1868         if (HAS_PCH_IBX(dev_priv->dev)) {
1869                 /*
1870                  * Make the BPC in transcoder be consistent with
1871                  * that in pipeconf reg. For HDMI we must use 8bpc
1872                  * here for both 8bpc and 12bpc.
1873                  */
1874                 val &= ~PIPECONF_BPC_MASK;
1875                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1876                         val |= PIPECONF_8BPC;
1877                 else
1878                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1879         }
1880
1881         val &= ~TRANS_INTERLACE_MASK;
1882         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1883                 if (HAS_PCH_IBX(dev_priv->dev) &&
1884                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1885                         val |= TRANS_LEGACY_INTERLACED_ILK;
1886                 else
1887                         val |= TRANS_INTERLACED;
1888         else
1889                 val |= TRANS_PROGRESSIVE;
1890
1891         I915_WRITE(reg, val | TRANS_ENABLE);
1892         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1893                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1894 }
1895
1896 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1897                                       enum transcoder cpu_transcoder)
1898 {
1899         u32 val, pipeconf_val;
1900
1901         /* PCH only available on ILK+ */
1902         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
1903
1904         /* FDI must be feeding us bits for PCH ports */
1905         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1906         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1907
1908         /* Workaround: set timing override bit. */
1909         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1910         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1911         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1912
1913         val = TRANS_ENABLE;
1914         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1915
1916         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1917             PIPECONF_INTERLACED_ILK)
1918                 val |= TRANS_INTERLACED;
1919         else
1920                 val |= TRANS_PROGRESSIVE;
1921
1922         I915_WRITE(LPT_TRANSCONF, val);
1923         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1924                 DRM_ERROR("Failed to enable PCH transcoder\n");
1925 }
1926
1927 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1928                                             enum pipe pipe)
1929 {
1930         struct drm_device *dev = dev_priv->dev;
1931         i915_reg_t reg;
1932         uint32_t val;
1933
1934         /* FDI relies on the transcoder */
1935         assert_fdi_tx_disabled(dev_priv, pipe);
1936         assert_fdi_rx_disabled(dev_priv, pipe);
1937
1938         /* Ports must be off as well */
1939         assert_pch_ports_disabled(dev_priv, pipe);
1940
1941         reg = PCH_TRANSCONF(pipe);
1942         val = I915_READ(reg);
1943         val &= ~TRANS_ENABLE;
1944         I915_WRITE(reg, val);
1945         /* wait for PCH transcoder off, transcoder state */
1946         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1947                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1948
1949         if (HAS_PCH_CPT(dev)) {
1950                 /* Workaround: Clear the timing override chicken bit again. */
1951                 reg = TRANS_CHICKEN2(pipe);
1952                 val = I915_READ(reg);
1953                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1954                 I915_WRITE(reg, val);
1955         }
1956 }
1957
1958 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1959 {
1960         u32 val;
1961
1962         val = I915_READ(LPT_TRANSCONF);
1963         val &= ~TRANS_ENABLE;
1964         I915_WRITE(LPT_TRANSCONF, val);
1965         /* wait for PCH transcoder off, transcoder state */
1966         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1967                 DRM_ERROR("Failed to disable PCH transcoder\n");
1968
1969         /* Workaround: clear timing override bit. */
1970         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1971         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1972         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1973 }
1974
1975 /**
1976  * intel_enable_pipe - enable a pipe, asserting requirements
1977  * @crtc: crtc responsible for the pipe
1978  *
1979  * Enable @crtc's pipe, making sure that various hardware specific requirements
1980  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1981  */
1982 static void intel_enable_pipe(struct intel_crtc *crtc)
1983 {
1984         struct drm_device *dev = crtc->base.dev;
1985         struct drm_i915_private *dev_priv = dev->dev_private;
1986         enum pipe pipe = crtc->pipe;
1987         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1988         enum pipe pch_transcoder;
1989         i915_reg_t reg;
1990         u32 val;
1991
1992         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1993
1994         assert_planes_disabled(dev_priv, pipe);
1995         assert_cursor_disabled(dev_priv, pipe);
1996         assert_sprites_disabled(dev_priv, pipe);
1997
1998         if (HAS_PCH_LPT(dev_priv->dev))
1999                 pch_transcoder = TRANSCODER_A;
2000         else
2001                 pch_transcoder = pipe;
2002
2003         /*
2004          * A pipe without a PLL won't actually be able to drive bits from
2005          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
2006          * need the check.
2007          */
2008         if (HAS_GMCH_DISPLAY(dev_priv->dev))
2009                 if (crtc->config->has_dsi_encoder)
2010                         assert_dsi_pll_enabled(dev_priv);
2011                 else
2012                         assert_pll_enabled(dev_priv, pipe);
2013         else {
2014                 if (crtc->config->has_pch_encoder) {
2015                         /* if driving the PCH, we need FDI enabled */
2016                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
2017                         assert_fdi_tx_pll_enabled(dev_priv,
2018                                                   (enum pipe) cpu_transcoder);
2019                 }
2020                 /* FIXME: assert CPU port conditions for SNB+ */
2021         }
2022
2023         reg = PIPECONF(cpu_transcoder);
2024         val = I915_READ(reg);
2025         if (val & PIPECONF_ENABLE) {
2026                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
2027                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
2028                 return;
2029         }
2030
2031         I915_WRITE(reg, val | PIPECONF_ENABLE);
2032         POSTING_READ(reg);
2033
2034         /*
2035          * Until the pipe starts DSL will read as 0, which would cause
2036          * an apparent vblank timestamp jump, which messes up also the
2037          * frame count when it's derived from the timestamps. So let's
2038          * wait for the pipe to start properly before we call
2039          * drm_crtc_vblank_on()
2040          */
2041         if (dev->max_vblank_count == 0 &&
2042             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2043                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2044 }
2045
2046 /**
2047  * intel_disable_pipe - disable a pipe, asserting requirements
2048  * @crtc: crtc whose pipes is to be disabled
2049  *
2050  * Disable the pipe of @crtc, making sure that various hardware
2051  * specific requirements are met, if applicable, e.g. plane
2052  * disabled, panel fitter off, etc.
2053  *
2054  * Will wait until the pipe has shut down before returning.
2055  */
2056 static void intel_disable_pipe(struct intel_crtc *crtc)
2057 {
2058         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2059         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2060         enum pipe pipe = crtc->pipe;
2061         i915_reg_t reg;
2062         u32 val;
2063
2064         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2065
2066         /*
2067          * Make sure planes won't keep trying to pump pixels to us,
2068          * or we might hang the display.
2069          */
2070         assert_planes_disabled(dev_priv, pipe);
2071         assert_cursor_disabled(dev_priv, pipe);
2072         assert_sprites_disabled(dev_priv, pipe);
2073
2074         reg = PIPECONF(cpu_transcoder);
2075         val = I915_READ(reg);
2076         if ((val & PIPECONF_ENABLE) == 0)
2077                 return;
2078
2079         /*
2080          * Double wide has implications for planes
2081          * so best keep it disabled when not needed.
2082          */
2083         if (crtc->config->double_wide)
2084                 val &= ~PIPECONF_DOUBLE_WIDE;
2085
2086         /* Don't disable pipe or pipe PLLs if needed */
2087         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2088             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2089                 val &= ~PIPECONF_ENABLE;
2090
2091         I915_WRITE(reg, val);
2092         if ((val & PIPECONF_ENABLE) == 0)
2093                 intel_wait_for_pipe_off(crtc);
2094 }
2095
2096 static bool need_vtd_wa(struct drm_device *dev)
2097 {
2098 #ifdef CONFIG_INTEL_IOMMU
2099         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2100                 return true;
2101 #endif
2102         return false;
2103 }
2104
2105 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2106 {
2107         return IS_GEN2(dev_priv) ? 2048 : 4096;
2108 }
2109
2110 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2111                                            uint64_t fb_modifier, unsigned int cpp)
2112 {
2113         switch (fb_modifier) {
2114         case DRM_FORMAT_MOD_NONE:
2115                 return cpp;
2116         case I915_FORMAT_MOD_X_TILED:
2117                 if (IS_GEN2(dev_priv))
2118                         return 128;
2119                 else
2120                         return 512;
2121         case I915_FORMAT_MOD_Y_TILED:
2122                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2123                         return 128;
2124                 else
2125                         return 512;
2126         case I915_FORMAT_MOD_Yf_TILED:
2127                 switch (cpp) {
2128                 case 1:
2129                         return 64;
2130                 case 2:
2131                 case 4:
2132                         return 128;
2133                 case 8:
2134                 case 16:
2135                         return 256;
2136                 default:
2137                         MISSING_CASE(cpp);
2138                         return cpp;
2139                 }
2140                 break;
2141         default:
2142                 MISSING_CASE(fb_modifier);
2143                 return cpp;
2144         }
2145 }
2146
2147 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2148                                uint64_t fb_modifier, unsigned int cpp)
2149 {
2150         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2151                 return 1;
2152         else
2153                 return intel_tile_size(dev_priv) /
2154                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2155 }
2156
2157 /* Return the tile dimensions in pixel units */
2158 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2159                             unsigned int *tile_width,
2160                             unsigned int *tile_height,
2161                             uint64_t fb_modifier,
2162                             unsigned int cpp)
2163 {
2164         unsigned int tile_width_bytes =
2165                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2166
2167         *tile_width = tile_width_bytes / cpp;
2168         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2169 }
2170
2171 unsigned int
2172 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2173                       uint32_t pixel_format, uint64_t fb_modifier)
2174 {
2175         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2176         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2177
2178         return ALIGN(height, tile_height);
2179 }
2180
2181 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2182 {
2183         unsigned int size = 0;
2184         int i;
2185
2186         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2187                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2188
2189         return size;
2190 }
2191
2192 static void
2193 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2194                         const struct drm_framebuffer *fb,
2195                         unsigned int rotation)
2196 {
2197         if (intel_rotation_90_or_270(rotation)) {
2198                 *view = i915_ggtt_view_rotated;
2199                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2200         } else {
2201                 *view = i915_ggtt_view_normal;
2202         }
2203 }
2204
2205 static void
2206 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2207                    struct drm_framebuffer *fb)
2208 {
2209         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2210         unsigned int tile_size, tile_width, tile_height, cpp;
2211
2212         tile_size = intel_tile_size(dev_priv);
2213
2214         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2215         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2216                         fb->modifier[0], cpp);
2217
2218         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2219         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2220
2221         if (info->pixel_format == DRM_FORMAT_NV12) {
2222                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2223                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2224                                 fb->modifier[1], cpp);
2225
2226                 info->uv_offset = fb->offsets[1];
2227                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2228                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2229         }
2230 }
2231
2232 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2233 {
2234         if (INTEL_INFO(dev_priv)->gen >= 9)
2235                 return 256 * 1024;
2236         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2237                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2238                 return 128 * 1024;
2239         else if (INTEL_INFO(dev_priv)->gen >= 4)
2240                 return 4 * 1024;
2241         else
2242                 return 0;
2243 }
2244
2245 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2246                                          uint64_t fb_modifier)
2247 {
2248         switch (fb_modifier) {
2249         case DRM_FORMAT_MOD_NONE:
2250                 return intel_linear_alignment(dev_priv);
2251         case I915_FORMAT_MOD_X_TILED:
2252                 if (INTEL_INFO(dev_priv)->gen >= 9)
2253                         return 256 * 1024;
2254                 return 0;
2255         case I915_FORMAT_MOD_Y_TILED:
2256         case I915_FORMAT_MOD_Yf_TILED:
2257                 return 1 * 1024 * 1024;
2258         default:
2259                 MISSING_CASE(fb_modifier);
2260                 return 0;
2261         }
2262 }
2263
2264 int
2265 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2266                            unsigned int rotation)
2267 {
2268         struct drm_device *dev = fb->dev;
2269         struct drm_i915_private *dev_priv = dev->dev_private;
2270         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2271         struct i915_ggtt_view view;
2272         u32 alignment;
2273         int ret;
2274
2275         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2276
2277         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2278
2279         intel_fill_fb_ggtt_view(&view, fb, rotation);
2280
2281         /* Note that the w/a also requires 64 PTE of padding following the
2282          * bo. We currently fill all unused PTE with the shadow page and so
2283          * we should always have valid PTE following the scanout preventing
2284          * the VT-d warning.
2285          */
2286         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2287                 alignment = 256 * 1024;
2288
2289         /*
2290          * Global gtt pte registers are special registers which actually forward
2291          * writes to a chunk of system memory. Which means that there is no risk
2292          * that the register values disappear as soon as we call
2293          * intel_runtime_pm_put(), so it is correct to wrap only the
2294          * pin/unpin/fence and not more.
2295          */
2296         intel_runtime_pm_get(dev_priv);
2297
2298         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2299                                                    &view);
2300         if (ret)
2301                 goto err_pm;
2302
2303         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2304          * fence, whereas 965+ only requires a fence if using
2305          * framebuffer compression.  For simplicity, we always install
2306          * a fence as the cost is not that onerous.
2307          */
2308         if (view.type == I915_GGTT_VIEW_NORMAL) {
2309                 ret = i915_gem_object_get_fence(obj);
2310                 if (ret == -EDEADLK) {
2311                         /*
2312                          * -EDEADLK means there are no free fences
2313                          * no pending flips.
2314                          *
2315                          * This is propagated to atomic, but it uses
2316                          * -EDEADLK to force a locking recovery, so
2317                          * change the returned error to -EBUSY.
2318                          */
2319                         ret = -EBUSY;
2320                         goto err_unpin;
2321                 } else if (ret)
2322                         goto err_unpin;
2323
2324                 i915_gem_object_pin_fence(obj);
2325         }
2326
2327         intel_runtime_pm_put(dev_priv);
2328         return 0;
2329
2330 err_unpin:
2331         i915_gem_object_unpin_from_display_plane(obj, &view);
2332 err_pm:
2333         intel_runtime_pm_put(dev_priv);
2334         return ret;
2335 }
2336
2337 static void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2338 {
2339         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2340         struct i915_ggtt_view view;
2341
2342         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2343
2344         intel_fill_fb_ggtt_view(&view, fb, rotation);
2345
2346         if (view.type == I915_GGTT_VIEW_NORMAL)
2347                 i915_gem_object_unpin_fence(obj);
2348
2349         i915_gem_object_unpin_from_display_plane(obj, &view);
2350 }
2351
2352 /*
2353  * Adjust the tile offset by moving the difference into
2354  * the x/y offsets.
2355  *
2356  * Input tile dimensions and pitch must already be
2357  * rotated to match x and y, and in pixel units.
2358  */
2359 static u32 intel_adjust_tile_offset(int *x, int *y,
2360                                     unsigned int tile_width,
2361                                     unsigned int tile_height,
2362                                     unsigned int tile_size,
2363                                     unsigned int pitch_tiles,
2364                                     u32 old_offset,
2365                                     u32 new_offset)
2366 {
2367         unsigned int tiles;
2368
2369         WARN_ON(old_offset & (tile_size - 1));
2370         WARN_ON(new_offset & (tile_size - 1));
2371         WARN_ON(new_offset > old_offset);
2372
2373         tiles = (old_offset - new_offset) / tile_size;
2374
2375         *y += tiles / pitch_tiles * tile_height;
2376         *x += tiles % pitch_tiles * tile_width;
2377
2378         return new_offset;
2379 }
2380
2381 /*
2382  * Computes the linear offset to the base tile and adjusts
2383  * x, y. bytes per pixel is assumed to be a power-of-two.
2384  *
2385  * In the 90/270 rotated case, x and y are assumed
2386  * to be already rotated to match the rotated GTT view, and
2387  * pitch is the tile_height aligned framebuffer height.
2388  */
2389 u32 intel_compute_tile_offset(int *x, int *y,
2390                               const struct drm_framebuffer *fb, int plane,
2391                               unsigned int pitch,
2392                               unsigned int rotation)
2393 {
2394         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2395         uint64_t fb_modifier = fb->modifier[plane];
2396         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2397         u32 offset, offset_aligned, alignment;
2398
2399         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2400         if (alignment)
2401                 alignment--;
2402
2403         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2404                 unsigned int tile_size, tile_width, tile_height;
2405                 unsigned int tile_rows, tiles, pitch_tiles;
2406
2407                 tile_size = intel_tile_size(dev_priv);
2408                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2409                                 fb_modifier, cpp);
2410
2411                 if (intel_rotation_90_or_270(rotation)) {
2412                         pitch_tiles = pitch / tile_height;
2413                         swap(tile_width, tile_height);
2414                 } else {
2415                         pitch_tiles = pitch / (tile_width * cpp);
2416                 }
2417
2418                 tile_rows = *y / tile_height;
2419                 *y %= tile_height;
2420
2421                 tiles = *x / tile_width;
2422                 *x %= tile_width;
2423
2424                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2425                 offset_aligned = offset & ~alignment;
2426
2427                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2428                                          tile_size, pitch_tiles,
2429                                          offset, offset_aligned);
2430         } else {
2431                 offset = *y * pitch + *x * cpp;
2432                 offset_aligned = offset & ~alignment;
2433
2434                 *y = (offset & alignment) / pitch;
2435                 *x = ((offset & alignment) - *y * pitch) / cpp;
2436         }
2437
2438         return offset_aligned;
2439 }
2440
2441 static int i9xx_format_to_fourcc(int format)
2442 {
2443         switch (format) {
2444         case DISPPLANE_8BPP:
2445                 return DRM_FORMAT_C8;
2446         case DISPPLANE_BGRX555:
2447                 return DRM_FORMAT_XRGB1555;
2448         case DISPPLANE_BGRX565:
2449                 return DRM_FORMAT_RGB565;
2450         default:
2451         case DISPPLANE_BGRX888:
2452                 return DRM_FORMAT_XRGB8888;
2453         case DISPPLANE_RGBX888:
2454                 return DRM_FORMAT_XBGR8888;
2455         case DISPPLANE_BGRX101010:
2456                 return DRM_FORMAT_XRGB2101010;
2457         case DISPPLANE_RGBX101010:
2458                 return DRM_FORMAT_XBGR2101010;
2459         }
2460 }
2461
2462 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2463 {
2464         switch (format) {
2465         case PLANE_CTL_FORMAT_RGB_565:
2466                 return DRM_FORMAT_RGB565;
2467         default:
2468         case PLANE_CTL_FORMAT_XRGB_8888:
2469                 if (rgb_order) {
2470                         if (alpha)
2471                                 return DRM_FORMAT_ABGR8888;
2472                         else
2473                                 return DRM_FORMAT_XBGR8888;
2474                 } else {
2475                         if (alpha)
2476                                 return DRM_FORMAT_ARGB8888;
2477                         else
2478                                 return DRM_FORMAT_XRGB8888;
2479                 }
2480         case PLANE_CTL_FORMAT_XRGB_2101010:
2481                 if (rgb_order)
2482                         return DRM_FORMAT_XBGR2101010;
2483                 else
2484                         return DRM_FORMAT_XRGB2101010;
2485         }
2486 }
2487
2488 static bool
2489 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2490                               struct intel_initial_plane_config *plane_config)
2491 {
2492         struct drm_device *dev = crtc->base.dev;
2493         struct drm_i915_private *dev_priv = to_i915(dev);
2494         struct drm_i915_gem_object *obj = NULL;
2495         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2496         struct drm_framebuffer *fb = &plane_config->fb->base;
2497         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2498         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2499                                     PAGE_SIZE);
2500
2501         size_aligned -= base_aligned;
2502
2503         if (plane_config->size == 0)
2504                 return false;
2505
2506         /* If the FB is too big, just don't use it since fbdev is not very
2507          * important and we should probably use that space with FBC or other
2508          * features. */
2509         if (size_aligned * 2 > dev_priv->ggtt.stolen_usable_size)
2510                 return false;
2511
2512         mutex_lock(&dev->struct_mutex);
2513
2514         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2515                                                              base_aligned,
2516                                                              base_aligned,
2517                                                              size_aligned);
2518         if (!obj) {
2519                 mutex_unlock(&dev->struct_mutex);
2520                 return false;
2521         }
2522
2523         obj->tiling_mode = plane_config->tiling;
2524         if (obj->tiling_mode == I915_TILING_X)
2525                 obj->stride = fb->pitches[0];
2526
2527         mode_cmd.pixel_format = fb->pixel_format;
2528         mode_cmd.width = fb->width;
2529         mode_cmd.height = fb->height;
2530         mode_cmd.pitches[0] = fb->pitches[0];
2531         mode_cmd.modifier[0] = fb->modifier[0];
2532         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2533
2534         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2535                                    &mode_cmd, obj)) {
2536                 DRM_DEBUG_KMS("intel fb init failed\n");
2537                 goto out_unref_obj;
2538         }
2539
2540         mutex_unlock(&dev->struct_mutex);
2541
2542         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2543         return true;
2544
2545 out_unref_obj:
2546         drm_gem_object_unreference(&obj->base);
2547         mutex_unlock(&dev->struct_mutex);
2548         return false;
2549 }
2550
2551 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2552 static void
2553 update_state_fb(struct drm_plane *plane)
2554 {
2555         if (plane->fb == plane->state->fb)
2556                 return;
2557
2558         if (plane->state->fb)
2559                 drm_framebuffer_unreference(plane->state->fb);
2560         plane->state->fb = plane->fb;
2561         if (plane->state->fb)
2562                 drm_framebuffer_reference(plane->state->fb);
2563 }
2564
2565 static void
2566 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2567                              struct intel_initial_plane_config *plane_config)
2568 {
2569         struct drm_device *dev = intel_crtc->base.dev;
2570         struct drm_i915_private *dev_priv = dev->dev_private;
2571         struct drm_crtc *c;
2572         struct intel_crtc *i;
2573         struct drm_i915_gem_object *obj;
2574         struct drm_plane *primary = intel_crtc->base.primary;
2575         struct drm_plane_state *plane_state = primary->state;
2576         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2577         struct intel_plane *intel_plane = to_intel_plane(primary);
2578         struct intel_plane_state *intel_state =
2579                 to_intel_plane_state(plane_state);
2580         struct drm_framebuffer *fb;
2581
2582         if (!plane_config->fb)
2583                 return;
2584
2585         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2586                 fb = &plane_config->fb->base;
2587                 goto valid_fb;
2588         }
2589
2590         kfree(plane_config->fb);
2591
2592         /*
2593          * Failed to alloc the obj, check to see if we should share
2594          * an fb with another CRTC instead
2595          */
2596         for_each_crtc(dev, c) {
2597                 i = to_intel_crtc(c);
2598
2599                 if (c == &intel_crtc->base)
2600                         continue;
2601
2602                 if (!i->active)
2603                         continue;
2604
2605                 fb = c->primary->fb;
2606                 if (!fb)
2607                         continue;
2608
2609                 obj = intel_fb_obj(fb);
2610                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2611                         drm_framebuffer_reference(fb);
2612                         goto valid_fb;
2613                 }
2614         }
2615
2616         /*
2617          * We've failed to reconstruct the BIOS FB.  Current display state
2618          * indicates that the primary plane is visible, but has a NULL FB,
2619          * which will lead to problems later if we don't fix it up.  The
2620          * simplest solution is to just disable the primary plane now and
2621          * pretend the BIOS never had it enabled.
2622          */
2623         to_intel_plane_state(plane_state)->visible = false;
2624         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2625         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2626         intel_plane->disable_plane(primary, &intel_crtc->base);
2627
2628         return;
2629
2630 valid_fb:
2631         plane_state->src_x = 0;
2632         plane_state->src_y = 0;
2633         plane_state->src_w = fb->width << 16;
2634         plane_state->src_h = fb->height << 16;
2635
2636         plane_state->crtc_x = 0;
2637         plane_state->crtc_y = 0;
2638         plane_state->crtc_w = fb->width;
2639         plane_state->crtc_h = fb->height;
2640
2641         intel_state->src.x1 = plane_state->src_x;
2642         intel_state->src.y1 = plane_state->src_y;
2643         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2644         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2645         intel_state->dst.x1 = plane_state->crtc_x;
2646         intel_state->dst.y1 = plane_state->crtc_y;
2647         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2648         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2649
2650         obj = intel_fb_obj(fb);
2651         if (obj->tiling_mode != I915_TILING_NONE)
2652                 dev_priv->preserve_bios_swizzle = true;
2653
2654         drm_framebuffer_reference(fb);
2655         primary->fb = primary->state->fb = fb;
2656         primary->crtc = primary->state->crtc = &intel_crtc->base;
2657         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2658         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2659 }
2660
2661 static void i9xx_update_primary_plane(struct drm_plane *primary,
2662                                       const struct intel_crtc_state *crtc_state,
2663                                       const struct intel_plane_state *plane_state)
2664 {
2665         struct drm_device *dev = primary->dev;
2666         struct drm_i915_private *dev_priv = dev->dev_private;
2667         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2668         struct drm_framebuffer *fb = plane_state->base.fb;
2669         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2670         int plane = intel_crtc->plane;
2671         u32 linear_offset;
2672         u32 dspcntr;
2673         i915_reg_t reg = DSPCNTR(plane);
2674         unsigned int rotation = plane_state->base.rotation;
2675         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2676         int x = plane_state->src.x1 >> 16;
2677         int y = plane_state->src.y1 >> 16;
2678
2679         dspcntr = DISPPLANE_GAMMA_ENABLE;
2680
2681         dspcntr |= DISPLAY_PLANE_ENABLE;
2682
2683         if (INTEL_INFO(dev)->gen < 4) {
2684                 if (intel_crtc->pipe == PIPE_B)
2685                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2686
2687                 /* pipesrc and dspsize control the size that is scaled from,
2688                  * which should always be the user's requested size.
2689                  */
2690                 I915_WRITE(DSPSIZE(plane),
2691                            ((crtc_state->pipe_src_h - 1) << 16) |
2692                            (crtc_state->pipe_src_w - 1));
2693                 I915_WRITE(DSPPOS(plane), 0);
2694         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2695                 I915_WRITE(PRIMSIZE(plane),
2696                            ((crtc_state->pipe_src_h - 1) << 16) |
2697                            (crtc_state->pipe_src_w - 1));
2698                 I915_WRITE(PRIMPOS(plane), 0);
2699                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2700         }
2701
2702         switch (fb->pixel_format) {
2703         case DRM_FORMAT_C8:
2704                 dspcntr |= DISPPLANE_8BPP;
2705                 break;
2706         case DRM_FORMAT_XRGB1555:
2707                 dspcntr |= DISPPLANE_BGRX555;
2708                 break;
2709         case DRM_FORMAT_RGB565:
2710                 dspcntr |= DISPPLANE_BGRX565;
2711                 break;
2712         case DRM_FORMAT_XRGB8888:
2713                 dspcntr |= DISPPLANE_BGRX888;
2714                 break;
2715         case DRM_FORMAT_XBGR8888:
2716                 dspcntr |= DISPPLANE_RGBX888;
2717                 break;
2718         case DRM_FORMAT_XRGB2101010:
2719                 dspcntr |= DISPPLANE_BGRX101010;
2720                 break;
2721         case DRM_FORMAT_XBGR2101010:
2722                 dspcntr |= DISPPLANE_RGBX101010;
2723                 break;
2724         default:
2725                 BUG();
2726         }
2727
2728         if (INTEL_INFO(dev)->gen >= 4 &&
2729             obj->tiling_mode != I915_TILING_NONE)
2730                 dspcntr |= DISPPLANE_TILED;
2731
2732         if (IS_G4X(dev))
2733                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2734
2735         linear_offset = y * fb->pitches[0] + x * cpp;
2736
2737         if (INTEL_INFO(dev)->gen >= 4) {
2738                 intel_crtc->dspaddr_offset =
2739                         intel_compute_tile_offset(&x, &y, fb, 0,
2740                                                   fb->pitches[0], rotation);
2741                 linear_offset -= intel_crtc->dspaddr_offset;
2742         } else {
2743                 intel_crtc->dspaddr_offset = linear_offset;
2744         }
2745
2746         if (rotation == BIT(DRM_ROTATE_180)) {
2747                 dspcntr |= DISPPLANE_ROTATE_180;
2748
2749                 x += (crtc_state->pipe_src_w - 1);
2750                 y += (crtc_state->pipe_src_h - 1);
2751
2752                 /* Finding the last pixel of the last line of the display
2753                 data and adding to linear_offset*/
2754                 linear_offset +=
2755                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2756                         (crtc_state->pipe_src_w - 1) * cpp;
2757         }
2758
2759         intel_crtc->adjusted_x = x;
2760         intel_crtc->adjusted_y = y;
2761
2762         I915_WRITE(reg, dspcntr);
2763
2764         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2765         if (INTEL_INFO(dev)->gen >= 4) {
2766                 I915_WRITE(DSPSURF(plane),
2767                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2768                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2769                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2770         } else
2771                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2772         POSTING_READ(reg);
2773 }
2774
2775 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2776                                        struct drm_crtc *crtc)
2777 {
2778         struct drm_device *dev = crtc->dev;
2779         struct drm_i915_private *dev_priv = dev->dev_private;
2780         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2781         int plane = intel_crtc->plane;
2782
2783         I915_WRITE(DSPCNTR(plane), 0);
2784         if (INTEL_INFO(dev_priv)->gen >= 4)
2785                 I915_WRITE(DSPSURF(plane), 0);
2786         else
2787                 I915_WRITE(DSPADDR(plane), 0);
2788         POSTING_READ(DSPCNTR(plane));
2789 }
2790
2791 static void ironlake_update_primary_plane(struct drm_plane *primary,
2792                                           const struct intel_crtc_state *crtc_state,
2793                                           const struct intel_plane_state *plane_state)
2794 {
2795         struct drm_device *dev = primary->dev;
2796         struct drm_i915_private *dev_priv = dev->dev_private;
2797         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2798         struct drm_framebuffer *fb = plane_state->base.fb;
2799         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2800         int plane = intel_crtc->plane;
2801         u32 linear_offset;
2802         u32 dspcntr;
2803         i915_reg_t reg = DSPCNTR(plane);
2804         unsigned int rotation = plane_state->base.rotation;
2805         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2806         int x = plane_state->src.x1 >> 16;
2807         int y = plane_state->src.y1 >> 16;
2808
2809         dspcntr = DISPPLANE_GAMMA_ENABLE;
2810         dspcntr |= DISPLAY_PLANE_ENABLE;
2811
2812         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2813                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2814
2815         switch (fb->pixel_format) {
2816         case DRM_FORMAT_C8:
2817                 dspcntr |= DISPPLANE_8BPP;
2818                 break;
2819         case DRM_FORMAT_RGB565:
2820                 dspcntr |= DISPPLANE_BGRX565;
2821                 break;
2822         case DRM_FORMAT_XRGB8888:
2823                 dspcntr |= DISPPLANE_BGRX888;
2824                 break;
2825         case DRM_FORMAT_XBGR8888:
2826                 dspcntr |= DISPPLANE_RGBX888;
2827                 break;
2828         case DRM_FORMAT_XRGB2101010:
2829                 dspcntr |= DISPPLANE_BGRX101010;
2830                 break;
2831         case DRM_FORMAT_XBGR2101010:
2832                 dspcntr |= DISPPLANE_RGBX101010;
2833                 break;
2834         default:
2835                 BUG();
2836         }
2837
2838         if (obj->tiling_mode != I915_TILING_NONE)
2839                 dspcntr |= DISPPLANE_TILED;
2840
2841         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2842                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2843
2844         linear_offset = y * fb->pitches[0] + x * cpp;
2845         intel_crtc->dspaddr_offset =
2846                 intel_compute_tile_offset(&x, &y, fb, 0,
2847                                           fb->pitches[0], rotation);
2848         linear_offset -= intel_crtc->dspaddr_offset;
2849         if (rotation == BIT(DRM_ROTATE_180)) {
2850                 dspcntr |= DISPPLANE_ROTATE_180;
2851
2852                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2853                         x += (crtc_state->pipe_src_w - 1);
2854                         y += (crtc_state->pipe_src_h - 1);
2855
2856                         /* Finding the last pixel of the last line of the display
2857                         data and adding to linear_offset*/
2858                         linear_offset +=
2859                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2860                                 (crtc_state->pipe_src_w - 1) * cpp;
2861                 }
2862         }
2863
2864         intel_crtc->adjusted_x = x;
2865         intel_crtc->adjusted_y = y;
2866
2867         I915_WRITE(reg, dspcntr);
2868
2869         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2870         I915_WRITE(DSPSURF(plane),
2871                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2872         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2873                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2874         } else {
2875                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2876                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2877         }
2878         POSTING_READ(reg);
2879 }
2880
2881 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2882                               uint64_t fb_modifier, uint32_t pixel_format)
2883 {
2884         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2885                 return 64;
2886         } else {
2887                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2888
2889                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2890         }
2891 }
2892
2893 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2894                            struct drm_i915_gem_object *obj,
2895                            unsigned int plane)
2896 {
2897         struct i915_ggtt_view view;
2898         struct i915_vma *vma;
2899         u64 offset;
2900
2901         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2902                                 intel_plane->base.state->rotation);
2903
2904         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2905         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2906                 view.type))
2907                 return -1;
2908
2909         offset = vma->node.start;
2910
2911         if (plane == 1) {
2912                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2913                           PAGE_SIZE;
2914         }
2915
2916         WARN_ON(upper_32_bits(offset));
2917
2918         return lower_32_bits(offset);
2919 }
2920
2921 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2922 {
2923         struct drm_device *dev = intel_crtc->base.dev;
2924         struct drm_i915_private *dev_priv = dev->dev_private;
2925
2926         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2927         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2928         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2929 }
2930
2931 /*
2932  * This function detaches (aka. unbinds) unused scalers in hardware
2933  */
2934 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2935 {
2936         struct intel_crtc_scaler_state *scaler_state;
2937         int i;
2938
2939         scaler_state = &intel_crtc->config->scaler_state;
2940
2941         /* loop through and disable scalers that aren't in use */
2942         for (i = 0; i < intel_crtc->num_scalers; i++) {
2943                 if (!scaler_state->scalers[i].in_use)
2944                         skl_detach_scaler(intel_crtc, i);
2945         }
2946 }
2947
2948 u32 skl_plane_ctl_format(uint32_t pixel_format)
2949 {
2950         switch (pixel_format) {
2951         case DRM_FORMAT_C8:
2952                 return PLANE_CTL_FORMAT_INDEXED;
2953         case DRM_FORMAT_RGB565:
2954                 return PLANE_CTL_FORMAT_RGB_565;
2955         case DRM_FORMAT_XBGR8888:
2956                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2957         case DRM_FORMAT_XRGB8888:
2958                 return PLANE_CTL_FORMAT_XRGB_8888;
2959         /*
2960          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2961          * to be already pre-multiplied. We need to add a knob (or a different
2962          * DRM_FORMAT) for user-space to configure that.
2963          */
2964         case DRM_FORMAT_ABGR8888:
2965                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2966                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2967         case DRM_FORMAT_ARGB8888:
2968                 return PLANE_CTL_FORMAT_XRGB_8888 |
2969                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2970         case DRM_FORMAT_XRGB2101010:
2971                 return PLANE_CTL_FORMAT_XRGB_2101010;
2972         case DRM_FORMAT_XBGR2101010:
2973                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2974         case DRM_FORMAT_YUYV:
2975                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2976         case DRM_FORMAT_YVYU:
2977                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2978         case DRM_FORMAT_UYVY:
2979                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2980         case DRM_FORMAT_VYUY:
2981                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2982         default:
2983                 MISSING_CASE(pixel_format);
2984         }
2985
2986         return 0;
2987 }
2988
2989 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2990 {
2991         switch (fb_modifier) {
2992         case DRM_FORMAT_MOD_NONE:
2993                 break;
2994         case I915_FORMAT_MOD_X_TILED:
2995                 return PLANE_CTL_TILED_X;
2996         case I915_FORMAT_MOD_Y_TILED:
2997                 return PLANE_CTL_TILED_Y;
2998         case I915_FORMAT_MOD_Yf_TILED:
2999                 return PLANE_CTL_TILED_YF;
3000         default:
3001                 MISSING_CASE(fb_modifier);
3002         }
3003
3004         return 0;
3005 }
3006
3007 u32 skl_plane_ctl_rotation(unsigned int rotation)
3008 {
3009         switch (rotation) {
3010         case BIT(DRM_ROTATE_0):
3011                 break;
3012         /*
3013          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
3014          * while i915 HW rotation is clockwise, thats why this swapping.
3015          */
3016         case BIT(DRM_ROTATE_90):
3017                 return PLANE_CTL_ROTATE_270;
3018         case BIT(DRM_ROTATE_180):
3019                 return PLANE_CTL_ROTATE_180;
3020         case BIT(DRM_ROTATE_270):
3021                 return PLANE_CTL_ROTATE_90;
3022         default:
3023                 MISSING_CASE(rotation);
3024         }
3025
3026         return 0;
3027 }
3028
3029 static void skylake_update_primary_plane(struct drm_plane *plane,
3030                                          const struct intel_crtc_state *crtc_state,
3031                                          const struct intel_plane_state *plane_state)
3032 {
3033         struct drm_device *dev = plane->dev;
3034         struct drm_i915_private *dev_priv = dev->dev_private;
3035         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3036         struct drm_framebuffer *fb = plane_state->base.fb;
3037         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3038         int pipe = intel_crtc->pipe;
3039         u32 plane_ctl, stride_div, stride;
3040         u32 tile_height, plane_offset, plane_size;
3041         unsigned int rotation = plane_state->base.rotation;
3042         int x_offset, y_offset;
3043         u32 surf_addr;
3044         int scaler_id = plane_state->scaler_id;
3045         int src_x = plane_state->src.x1 >> 16;
3046         int src_y = plane_state->src.y1 >> 16;
3047         int src_w = drm_rect_width(&plane_state->src) >> 16;
3048         int src_h = drm_rect_height(&plane_state->src) >> 16;
3049         int dst_x = plane_state->dst.x1;
3050         int dst_y = plane_state->dst.y1;
3051         int dst_w = drm_rect_width(&plane_state->dst);
3052         int dst_h = drm_rect_height(&plane_state->dst);
3053
3054         plane_ctl = PLANE_CTL_ENABLE |
3055                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3056                     PLANE_CTL_PIPE_CSC_ENABLE;
3057
3058         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3059         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3060         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3061         plane_ctl |= skl_plane_ctl_rotation(rotation);
3062
3063         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3064                                                fb->pixel_format);
3065         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3066
3067         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3068
3069         if (intel_rotation_90_or_270(rotation)) {
3070                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3071
3072                 /* stride = Surface height in tiles */
3073                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3074                 stride = DIV_ROUND_UP(fb->height, tile_height);
3075                 x_offset = stride * tile_height - src_y - src_h;
3076                 y_offset = src_x;
3077                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3078         } else {
3079                 stride = fb->pitches[0] / stride_div;
3080                 x_offset = src_x;
3081                 y_offset = src_y;
3082                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3083         }
3084         plane_offset = y_offset << 16 | x_offset;
3085
3086         intel_crtc->adjusted_x = x_offset;
3087         intel_crtc->adjusted_y = y_offset;
3088
3089         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3090         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3091         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3092         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3093
3094         if (scaler_id >= 0) {
3095                 uint32_t ps_ctrl = 0;
3096
3097                 WARN_ON(!dst_w || !dst_h);
3098                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3099                         crtc_state->scaler_state.scalers[scaler_id].mode;
3100                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3101                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3102                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3103                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3104                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3105         } else {
3106                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3107         }
3108
3109         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3110
3111         POSTING_READ(PLANE_SURF(pipe, 0));
3112 }
3113
3114 static void skylake_disable_primary_plane(struct drm_plane *primary,
3115                                           struct drm_crtc *crtc)
3116 {
3117         struct drm_device *dev = crtc->dev;
3118         struct drm_i915_private *dev_priv = dev->dev_private;
3119         int pipe = to_intel_crtc(crtc)->pipe;
3120
3121         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3122         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3123         POSTING_READ(PLANE_SURF(pipe, 0));
3124 }
3125
3126 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3127 static int
3128 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3129                            int x, int y, enum mode_set_atomic state)
3130 {
3131         /* Support for kgdboc is disabled, this needs a major rework. */
3132         DRM_ERROR("legacy panic handler not supported any more.\n");
3133
3134         return -ENODEV;
3135 }
3136
3137 static void intel_complete_page_flips(struct drm_device *dev)
3138 {
3139         struct drm_crtc *crtc;
3140
3141         for_each_crtc(dev, crtc) {
3142                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3143                 enum plane plane = intel_crtc->plane;
3144
3145                 intel_prepare_page_flip(dev, plane);
3146                 intel_finish_page_flip_plane(dev, plane);
3147         }
3148 }
3149
3150 static void intel_update_primary_planes(struct drm_device *dev)
3151 {
3152         struct drm_crtc *crtc;
3153
3154         for_each_crtc(dev, crtc) {
3155                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3156                 struct intel_plane_state *plane_state;
3157
3158                 drm_modeset_lock_crtc(crtc, &plane->base);
3159                 plane_state = to_intel_plane_state(plane->base.state);
3160
3161                 if (plane_state->visible)
3162                         plane->update_plane(&plane->base,
3163                                             to_intel_crtc_state(crtc->state),
3164                                             plane_state);
3165
3166                 drm_modeset_unlock_crtc(crtc);
3167         }
3168 }
3169
3170 void intel_prepare_reset(struct drm_device *dev)
3171 {
3172         /* no reset support for gen2 */
3173         if (IS_GEN2(dev))
3174                 return;
3175
3176         /* reset doesn't touch the display */
3177         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3178                 return;
3179
3180         drm_modeset_lock_all(dev);
3181         /*
3182          * Disabling the crtcs gracefully seems nicer. Also the
3183          * g33 docs say we should at least disable all the planes.
3184          */
3185         intel_display_suspend(dev);
3186 }
3187
3188 void intel_finish_reset(struct drm_device *dev)
3189 {
3190         struct drm_i915_private *dev_priv = to_i915(dev);
3191
3192         /*
3193          * Flips in the rings will be nuked by the reset,
3194          * so complete all pending flips so that user space
3195          * will get its events and not get stuck.
3196          */
3197         intel_complete_page_flips(dev);
3198
3199         /* no reset support for gen2 */
3200         if (IS_GEN2(dev))
3201                 return;
3202
3203         /* reset doesn't touch the display */
3204         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3205                 /*
3206                  * Flips in the rings have been nuked by the reset,
3207                  * so update the base address of all primary
3208                  * planes to the the last fb to make sure we're
3209                  * showing the correct fb after a reset.
3210                  *
3211                  * FIXME: Atomic will make this obsolete since we won't schedule
3212                  * CS-based flips (which might get lost in gpu resets) any more.
3213                  */
3214                 intel_update_primary_planes(dev);
3215                 return;
3216         }
3217
3218         /*
3219          * The display has been reset as well,
3220          * so need a full re-initialization.
3221          */
3222         intel_runtime_pm_disable_interrupts(dev_priv);
3223         intel_runtime_pm_enable_interrupts(dev_priv);
3224
3225         intel_modeset_init_hw(dev);
3226
3227         spin_lock_irq(&dev_priv->irq_lock);
3228         if (dev_priv->display.hpd_irq_setup)
3229                 dev_priv->display.hpd_irq_setup(dev);
3230         spin_unlock_irq(&dev_priv->irq_lock);
3231
3232         intel_display_resume(dev);
3233
3234         intel_hpd_init(dev_priv);
3235
3236         drm_modeset_unlock_all(dev);
3237 }
3238
3239 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3240 {
3241         struct drm_device *dev = crtc->dev;
3242         struct drm_i915_private *dev_priv = dev->dev_private;
3243         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3244         bool pending;
3245
3246         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3247             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3248                 return false;
3249
3250         spin_lock_irq(&dev->event_lock);
3251         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3252         spin_unlock_irq(&dev->event_lock);
3253
3254         return pending;
3255 }
3256
3257 static void intel_update_pipe_config(struct intel_crtc *crtc,
3258                                      struct intel_crtc_state *old_crtc_state)
3259 {
3260         struct drm_device *dev = crtc->base.dev;
3261         struct drm_i915_private *dev_priv = dev->dev_private;
3262         struct intel_crtc_state *pipe_config =
3263                 to_intel_crtc_state(crtc->base.state);
3264
3265         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3266         crtc->base.mode = crtc->base.state->mode;
3267
3268         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3269                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3270                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3271
3272         if (HAS_DDI(dev))
3273                 intel_set_pipe_csc(&crtc->base);
3274
3275         /*
3276          * Update pipe size and adjust fitter if needed: the reason for this is
3277          * that in compute_mode_changes we check the native mode (not the pfit
3278          * mode) to see if we can flip rather than do a full mode set. In the
3279          * fastboot case, we'll flip, but if we don't update the pipesrc and
3280          * pfit state, we'll end up with a big fb scanned out into the wrong
3281          * sized surface.
3282          */
3283
3284         I915_WRITE(PIPESRC(crtc->pipe),
3285                    ((pipe_config->pipe_src_w - 1) << 16) |
3286                    (pipe_config->pipe_src_h - 1));
3287
3288         /* on skylake this is done by detaching scalers */
3289         if (INTEL_INFO(dev)->gen >= 9) {
3290                 skl_detach_scalers(crtc);
3291
3292                 if (pipe_config->pch_pfit.enabled)
3293                         skylake_pfit_enable(crtc);
3294         } else if (HAS_PCH_SPLIT(dev)) {
3295                 if (pipe_config->pch_pfit.enabled)
3296                         ironlake_pfit_enable(crtc);
3297                 else if (old_crtc_state->pch_pfit.enabled)
3298                         ironlake_pfit_disable(crtc, true);
3299         }
3300 }
3301
3302 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3303 {
3304         struct drm_device *dev = crtc->dev;
3305         struct drm_i915_private *dev_priv = dev->dev_private;
3306         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3307         int pipe = intel_crtc->pipe;
3308         i915_reg_t reg;
3309         u32 temp;
3310
3311         /* enable normal train */
3312         reg = FDI_TX_CTL(pipe);
3313         temp = I915_READ(reg);
3314         if (IS_IVYBRIDGE(dev)) {
3315                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3316                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3317         } else {
3318                 temp &= ~FDI_LINK_TRAIN_NONE;
3319                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3320         }
3321         I915_WRITE(reg, temp);
3322
3323         reg = FDI_RX_CTL(pipe);
3324         temp = I915_READ(reg);
3325         if (HAS_PCH_CPT(dev)) {
3326                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3327                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3328         } else {
3329                 temp &= ~FDI_LINK_TRAIN_NONE;
3330                 temp |= FDI_LINK_TRAIN_NONE;
3331         }
3332         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3333
3334         /* wait one idle pattern time */
3335         POSTING_READ(reg);
3336         udelay(1000);
3337
3338         /* IVB wants error correction enabled */
3339         if (IS_IVYBRIDGE(dev))
3340                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3341                            FDI_FE_ERRC_ENABLE);
3342 }
3343
3344 /* The FDI link training functions for ILK/Ibexpeak. */
3345 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3346 {
3347         struct drm_device *dev = crtc->dev;
3348         struct drm_i915_private *dev_priv = dev->dev_private;
3349         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3350         int pipe = intel_crtc->pipe;
3351         i915_reg_t reg;
3352         u32 temp, tries;
3353
3354         /* FDI needs bits from pipe first */
3355         assert_pipe_enabled(dev_priv, pipe);
3356
3357         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3358            for train result */
3359         reg = FDI_RX_IMR(pipe);
3360         temp = I915_READ(reg);
3361         temp &= ~FDI_RX_SYMBOL_LOCK;
3362         temp &= ~FDI_RX_BIT_LOCK;
3363         I915_WRITE(reg, temp);
3364         I915_READ(reg);
3365         udelay(150);
3366
3367         /* enable CPU FDI TX and PCH FDI RX */
3368         reg = FDI_TX_CTL(pipe);
3369         temp = I915_READ(reg);
3370         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3371         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3372         temp &= ~FDI_LINK_TRAIN_NONE;
3373         temp |= FDI_LINK_TRAIN_PATTERN_1;
3374         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3375
3376         reg = FDI_RX_CTL(pipe);
3377         temp = I915_READ(reg);
3378         temp &= ~FDI_LINK_TRAIN_NONE;
3379         temp |= FDI_LINK_TRAIN_PATTERN_1;
3380         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3381
3382         POSTING_READ(reg);
3383         udelay(150);
3384
3385         /* Ironlake workaround, enable clock pointer after FDI enable*/
3386         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3387         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3388                    FDI_RX_PHASE_SYNC_POINTER_EN);
3389
3390         reg = FDI_RX_IIR(pipe);
3391         for (tries = 0; tries < 5; tries++) {
3392                 temp = I915_READ(reg);
3393                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3394
3395                 if ((temp & FDI_RX_BIT_LOCK)) {
3396                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3397                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3398                         break;
3399                 }
3400         }
3401         if (tries == 5)
3402                 DRM_ERROR("FDI train 1 fail!\n");
3403
3404         /* Train 2 */
3405         reg = FDI_TX_CTL(pipe);
3406         temp = I915_READ(reg);
3407         temp &= ~FDI_LINK_TRAIN_NONE;
3408         temp |= FDI_LINK_TRAIN_PATTERN_2;
3409         I915_WRITE(reg, temp);
3410
3411         reg = FDI_RX_CTL(pipe);
3412         temp = I915_READ(reg);
3413         temp &= ~FDI_LINK_TRAIN_NONE;
3414         temp |= FDI_LINK_TRAIN_PATTERN_2;
3415         I915_WRITE(reg, temp);
3416
3417         POSTING_READ(reg);
3418         udelay(150);
3419
3420         reg = FDI_RX_IIR(pipe);
3421         for (tries = 0; tries < 5; tries++) {
3422                 temp = I915_READ(reg);
3423                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3424
3425                 if (temp & FDI_RX_SYMBOL_LOCK) {
3426                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3427                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3428                         break;
3429                 }
3430         }
3431         if (tries == 5)
3432                 DRM_ERROR("FDI train 2 fail!\n");
3433
3434         DRM_DEBUG_KMS("FDI train done\n");
3435
3436 }
3437
3438 static const int snb_b_fdi_train_param[] = {
3439         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3440         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3441         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3442         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3443 };
3444
3445 /* The FDI link training functions for SNB/Cougarpoint. */
3446 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3447 {
3448         struct drm_device *dev = crtc->dev;
3449         struct drm_i915_private *dev_priv = dev->dev_private;
3450         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3451         int pipe = intel_crtc->pipe;
3452         i915_reg_t reg;
3453         u32 temp, i, retry;
3454
3455         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3456            for train result */
3457         reg = FDI_RX_IMR(pipe);
3458         temp = I915_READ(reg);
3459         temp &= ~FDI_RX_SYMBOL_LOCK;
3460         temp &= ~FDI_RX_BIT_LOCK;
3461         I915_WRITE(reg, temp);
3462
3463         POSTING_READ(reg);
3464         udelay(150);
3465
3466         /* enable CPU FDI TX and PCH FDI RX */
3467         reg = FDI_TX_CTL(pipe);
3468         temp = I915_READ(reg);
3469         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3470         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3471         temp &= ~FDI_LINK_TRAIN_NONE;
3472         temp |= FDI_LINK_TRAIN_PATTERN_1;
3473         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3474         /* SNB-B */
3475         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3476         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3477
3478         I915_WRITE(FDI_RX_MISC(pipe),
3479                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3480
3481         reg = FDI_RX_CTL(pipe);
3482         temp = I915_READ(reg);
3483         if (HAS_PCH_CPT(dev)) {
3484                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3485                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3486         } else {
3487                 temp &= ~FDI_LINK_TRAIN_NONE;
3488                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3489         }
3490         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3491
3492         POSTING_READ(reg);
3493         udelay(150);
3494
3495         for (i = 0; i < 4; i++) {
3496                 reg = FDI_TX_CTL(pipe);
3497                 temp = I915_READ(reg);
3498                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3499                 temp |= snb_b_fdi_train_param[i];
3500                 I915_WRITE(reg, temp);
3501
3502                 POSTING_READ(reg);
3503                 udelay(500);
3504
3505                 for (retry = 0; retry < 5; retry++) {
3506                         reg = FDI_RX_IIR(pipe);
3507                         temp = I915_READ(reg);
3508                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3509                         if (temp & FDI_RX_BIT_LOCK) {
3510                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3511                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3512                                 break;
3513                         }
3514                         udelay(50);
3515                 }
3516                 if (retry < 5)
3517                         break;
3518         }
3519         if (i == 4)
3520                 DRM_ERROR("FDI train 1 fail!\n");
3521
3522         /* Train 2 */
3523         reg = FDI_TX_CTL(pipe);
3524         temp = I915_READ(reg);
3525         temp &= ~FDI_LINK_TRAIN_NONE;
3526         temp |= FDI_LINK_TRAIN_PATTERN_2;
3527         if (IS_GEN6(dev)) {
3528                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3529                 /* SNB-B */
3530                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3531         }
3532         I915_WRITE(reg, temp);
3533
3534         reg = FDI_RX_CTL(pipe);
3535         temp = I915_READ(reg);
3536         if (HAS_PCH_CPT(dev)) {
3537                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3538                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3539         } else {
3540                 temp &= ~FDI_LINK_TRAIN_NONE;
3541                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3542         }
3543         I915_WRITE(reg, temp);
3544
3545         POSTING_READ(reg);
3546         udelay(150);
3547
3548         for (i = 0; i < 4; i++) {
3549                 reg = FDI_TX_CTL(pipe);
3550                 temp = I915_READ(reg);
3551                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3552                 temp |= snb_b_fdi_train_param[i];
3553                 I915_WRITE(reg, temp);
3554
3555                 POSTING_READ(reg);
3556                 udelay(500);
3557
3558                 for (retry = 0; retry < 5; retry++) {
3559                         reg = FDI_RX_IIR(pipe);
3560                         temp = I915_READ(reg);
3561                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3562                         if (temp & FDI_RX_SYMBOL_LOCK) {
3563                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3564                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3565                                 break;
3566                         }
3567                         udelay(50);
3568                 }
3569                 if (retry < 5)
3570                         break;
3571         }
3572         if (i == 4)
3573                 DRM_ERROR("FDI train 2 fail!\n");
3574
3575         DRM_DEBUG_KMS("FDI train done.\n");
3576 }
3577
3578 /* Manual link training for Ivy Bridge A0 parts */
3579 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3580 {
3581         struct drm_device *dev = crtc->dev;
3582         struct drm_i915_private *dev_priv = dev->dev_private;
3583         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3584         int pipe = intel_crtc->pipe;
3585         i915_reg_t reg;
3586         u32 temp, i, j;
3587
3588         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3589            for train result */
3590         reg = FDI_RX_IMR(pipe);
3591         temp = I915_READ(reg);
3592         temp &= ~FDI_RX_SYMBOL_LOCK;
3593         temp &= ~FDI_RX_BIT_LOCK;
3594         I915_WRITE(reg, temp);
3595
3596         POSTING_READ(reg);
3597         udelay(150);
3598
3599         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3600                       I915_READ(FDI_RX_IIR(pipe)));
3601
3602         /* Try each vswing and preemphasis setting twice before moving on */
3603         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3604                 /* disable first in case we need to retry */
3605                 reg = FDI_TX_CTL(pipe);
3606                 temp = I915_READ(reg);
3607                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3608                 temp &= ~FDI_TX_ENABLE;
3609                 I915_WRITE(reg, temp);
3610
3611                 reg = FDI_RX_CTL(pipe);
3612                 temp = I915_READ(reg);
3613                 temp &= ~FDI_LINK_TRAIN_AUTO;
3614                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3615                 temp &= ~FDI_RX_ENABLE;
3616                 I915_WRITE(reg, temp);
3617
3618                 /* enable CPU FDI TX and PCH FDI RX */
3619                 reg = FDI_TX_CTL(pipe);
3620                 temp = I915_READ(reg);
3621                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3622                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3623                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3624                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3625                 temp |= snb_b_fdi_train_param[j/2];
3626                 temp |= FDI_COMPOSITE_SYNC;
3627                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3628
3629                 I915_WRITE(FDI_RX_MISC(pipe),
3630                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3631
3632                 reg = FDI_RX_CTL(pipe);
3633                 temp = I915_READ(reg);
3634                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3635                 temp |= FDI_COMPOSITE_SYNC;
3636                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3637
3638                 POSTING_READ(reg);
3639                 udelay(1); /* should be 0.5us */
3640
3641                 for (i = 0; i < 4; i++) {
3642                         reg = FDI_RX_IIR(pipe);
3643                         temp = I915_READ(reg);
3644                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3645
3646                         if (temp & FDI_RX_BIT_LOCK ||
3647                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3648                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3649                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3650                                               i);
3651                                 break;
3652                         }
3653                         udelay(1); /* should be 0.5us */
3654                 }
3655                 if (i == 4) {
3656                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3657                         continue;
3658                 }
3659
3660                 /* Train 2 */
3661                 reg = FDI_TX_CTL(pipe);
3662                 temp = I915_READ(reg);
3663                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3664                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3665                 I915_WRITE(reg, temp);
3666
3667                 reg = FDI_RX_CTL(pipe);
3668                 temp = I915_READ(reg);
3669                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3670                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3671                 I915_WRITE(reg, temp);
3672
3673                 POSTING_READ(reg);
3674                 udelay(2); /* should be 1.5us */
3675
3676                 for (i = 0; i < 4; i++) {
3677                         reg = FDI_RX_IIR(pipe);
3678                         temp = I915_READ(reg);
3679                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3680
3681                         if (temp & FDI_RX_SYMBOL_LOCK ||
3682                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3683                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3684                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3685                                               i);
3686                                 goto train_done;
3687                         }
3688                         udelay(2); /* should be 1.5us */
3689                 }
3690                 if (i == 4)
3691                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3692         }
3693
3694 train_done:
3695         DRM_DEBUG_KMS("FDI train done.\n");
3696 }
3697
3698 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3699 {
3700         struct drm_device *dev = intel_crtc->base.dev;
3701         struct drm_i915_private *dev_priv = dev->dev_private;
3702         int pipe = intel_crtc->pipe;
3703         i915_reg_t reg;
3704         u32 temp;
3705
3706         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3707         reg = FDI_RX_CTL(pipe);
3708         temp = I915_READ(reg);
3709         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3710         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3711         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3712         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3713
3714         POSTING_READ(reg);
3715         udelay(200);
3716
3717         /* Switch from Rawclk to PCDclk */
3718         temp = I915_READ(reg);
3719         I915_WRITE(reg, temp | FDI_PCDCLK);
3720
3721         POSTING_READ(reg);
3722         udelay(200);
3723
3724         /* Enable CPU FDI TX PLL, always on for Ironlake */
3725         reg = FDI_TX_CTL(pipe);
3726         temp = I915_READ(reg);
3727         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3728                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3729
3730                 POSTING_READ(reg);
3731                 udelay(100);
3732         }
3733 }
3734
3735 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3736 {
3737         struct drm_device *dev = intel_crtc->base.dev;
3738         struct drm_i915_private *dev_priv = dev->dev_private;
3739         int pipe = intel_crtc->pipe;
3740         i915_reg_t reg;
3741         u32 temp;
3742
3743         /* Switch from PCDclk to Rawclk */
3744         reg = FDI_RX_CTL(pipe);
3745         temp = I915_READ(reg);
3746         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3747
3748         /* Disable CPU FDI TX PLL */
3749         reg = FDI_TX_CTL(pipe);
3750         temp = I915_READ(reg);
3751         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3752
3753         POSTING_READ(reg);
3754         udelay(100);
3755
3756         reg = FDI_RX_CTL(pipe);
3757         temp = I915_READ(reg);
3758         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3759
3760         /* Wait for the clocks to turn off. */
3761         POSTING_READ(reg);
3762         udelay(100);
3763 }
3764
3765 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3766 {
3767         struct drm_device *dev = crtc->dev;
3768         struct drm_i915_private *dev_priv = dev->dev_private;
3769         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3770         int pipe = intel_crtc->pipe;
3771         i915_reg_t reg;
3772         u32 temp;
3773
3774         /* disable CPU FDI tx and PCH FDI rx */
3775         reg = FDI_TX_CTL(pipe);
3776         temp = I915_READ(reg);
3777         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3778         POSTING_READ(reg);
3779
3780         reg = FDI_RX_CTL(pipe);
3781         temp = I915_READ(reg);
3782         temp &= ~(0x7 << 16);
3783         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3784         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3785
3786         POSTING_READ(reg);
3787         udelay(100);
3788
3789         /* Ironlake workaround, disable clock pointer after downing FDI */
3790         if (HAS_PCH_IBX(dev))
3791                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3792
3793         /* still set train pattern 1 */
3794         reg = FDI_TX_CTL(pipe);
3795         temp = I915_READ(reg);
3796         temp &= ~FDI_LINK_TRAIN_NONE;
3797         temp |= FDI_LINK_TRAIN_PATTERN_1;
3798         I915_WRITE(reg, temp);
3799
3800         reg = FDI_RX_CTL(pipe);
3801         temp = I915_READ(reg);
3802         if (HAS_PCH_CPT(dev)) {
3803                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3804                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3805         } else {
3806                 temp &= ~FDI_LINK_TRAIN_NONE;
3807                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3808         }
3809         /* BPC in FDI rx is consistent with that in PIPECONF */
3810         temp &= ~(0x07 << 16);
3811         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3812         I915_WRITE(reg, temp);
3813
3814         POSTING_READ(reg);
3815         udelay(100);
3816 }
3817
3818 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3819 {
3820         struct intel_crtc *crtc;
3821
3822         /* Note that we don't need to be called with mode_config.lock here
3823          * as our list of CRTC objects is static for the lifetime of the
3824          * device and so cannot disappear as we iterate. Similarly, we can
3825          * happily treat the predicates as racy, atomic checks as userspace
3826          * cannot claim and pin a new fb without at least acquring the
3827          * struct_mutex and so serialising with us.
3828          */
3829         for_each_intel_crtc(dev, crtc) {
3830                 if (atomic_read(&crtc->unpin_work_count) == 0)
3831                         continue;
3832
3833                 if (crtc->unpin_work)
3834                         intel_wait_for_vblank(dev, crtc->pipe);
3835
3836                 return true;
3837         }
3838
3839         return false;
3840 }
3841
3842 static void page_flip_completed(struct intel_crtc *intel_crtc)
3843 {
3844         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3845         struct intel_unpin_work *work = intel_crtc->unpin_work;
3846
3847         /* ensure that the unpin work is consistent wrt ->pending. */
3848         smp_rmb();
3849         intel_crtc->unpin_work = NULL;
3850
3851         if (work->event)
3852                 drm_send_vblank_event(intel_crtc->base.dev,
3853                                       intel_crtc->pipe,
3854                                       work->event);
3855
3856         drm_crtc_vblank_put(&intel_crtc->base);
3857
3858         wake_up_all(&dev_priv->pending_flip_queue);
3859         queue_work(dev_priv->wq, &work->work);
3860
3861         trace_i915_flip_complete(intel_crtc->plane,
3862                                  work->pending_flip_obj);
3863 }
3864
3865 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3866 {
3867         struct drm_device *dev = crtc->dev;
3868         struct drm_i915_private *dev_priv = dev->dev_private;
3869         long ret;
3870
3871         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3872
3873         ret = wait_event_interruptible_timeout(
3874                                         dev_priv->pending_flip_queue,
3875                                         !intel_crtc_has_pending_flip(crtc),
3876                                         60*HZ);
3877
3878         if (ret < 0)
3879                 return ret;
3880
3881         if (ret == 0) {
3882                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3883
3884                 spin_lock_irq(&dev->event_lock);
3885                 if (intel_crtc->unpin_work) {
3886                         WARN_ONCE(1, "Removing stuck page flip\n");
3887                         page_flip_completed(intel_crtc);
3888                 }
3889                 spin_unlock_irq(&dev->event_lock);
3890         }
3891
3892         return 0;
3893 }
3894
3895 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3896 {
3897         u32 temp;
3898
3899         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3900
3901         mutex_lock(&dev_priv->sb_lock);
3902
3903         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3904         temp |= SBI_SSCCTL_DISABLE;
3905         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3906
3907         mutex_unlock(&dev_priv->sb_lock);
3908 }
3909
3910 /* Program iCLKIP clock to the desired frequency */
3911 static void lpt_program_iclkip(struct drm_crtc *crtc)
3912 {
3913         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3914         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3915         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3916         u32 temp;
3917
3918         lpt_disable_iclkip(dev_priv);
3919
3920         /* The iCLK virtual clock root frequency is in MHz,
3921          * but the adjusted_mode->crtc_clock in in KHz. To get the
3922          * divisors, it is necessary to divide one by another, so we
3923          * convert the virtual clock precision to KHz here for higher
3924          * precision.
3925          */
3926         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3927                 u32 iclk_virtual_root_freq = 172800 * 1000;
3928                 u32 iclk_pi_range = 64;
3929                 u32 desired_divisor;
3930
3931                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3932                                                     clock << auxdiv);
3933                 divsel = (desired_divisor / iclk_pi_range) - 2;
3934                 phaseinc = desired_divisor % iclk_pi_range;
3935
3936                 /*
3937                  * Near 20MHz is a corner case which is
3938                  * out of range for the 7-bit divisor
3939                  */
3940                 if (divsel <= 0x7f)
3941                         break;
3942         }
3943
3944         /* This should not happen with any sane values */
3945         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3946                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3947         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3948                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3949
3950         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3951                         clock,
3952                         auxdiv,
3953                         divsel,
3954                         phasedir,
3955                         phaseinc);
3956
3957         mutex_lock(&dev_priv->sb_lock);
3958
3959         /* Program SSCDIVINTPHASE6 */
3960         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3961         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3962         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3963         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3964         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3965         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3966         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3967         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3968
3969         /* Program SSCAUXDIV */
3970         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3971         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3972         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3973         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3974
3975         /* Enable modulator and associated divider */
3976         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3977         temp &= ~SBI_SSCCTL_DISABLE;
3978         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3979
3980         mutex_unlock(&dev_priv->sb_lock);
3981
3982         /* Wait for initialization time */
3983         udelay(24);
3984
3985         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3986 }
3987
3988 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3989 {
3990         u32 divsel, phaseinc, auxdiv;
3991         u32 iclk_virtual_root_freq = 172800 * 1000;
3992         u32 iclk_pi_range = 64;
3993         u32 desired_divisor;
3994         u32 temp;
3995
3996         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3997                 return 0;
3998
3999         mutex_lock(&dev_priv->sb_lock);
4000
4001         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4002         if (temp & SBI_SSCCTL_DISABLE) {
4003                 mutex_unlock(&dev_priv->sb_lock);
4004                 return 0;
4005         }
4006
4007         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4008         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4009                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4010         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4011                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4012
4013         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4014         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4015                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4016
4017         mutex_unlock(&dev_priv->sb_lock);
4018
4019         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4020
4021         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4022                                  desired_divisor << auxdiv);
4023 }
4024
4025 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4026                                                 enum pipe pch_transcoder)
4027 {
4028         struct drm_device *dev = crtc->base.dev;
4029         struct drm_i915_private *dev_priv = dev->dev_private;
4030         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4031
4032         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4033                    I915_READ(HTOTAL(cpu_transcoder)));
4034         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4035                    I915_READ(HBLANK(cpu_transcoder)));
4036         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4037                    I915_READ(HSYNC(cpu_transcoder)));
4038
4039         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4040                    I915_READ(VTOTAL(cpu_transcoder)));
4041         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4042                    I915_READ(VBLANK(cpu_transcoder)));
4043         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4044                    I915_READ(VSYNC(cpu_transcoder)));
4045         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4046                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4047 }
4048
4049 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4050 {
4051         struct drm_i915_private *dev_priv = dev->dev_private;
4052         uint32_t temp;
4053
4054         temp = I915_READ(SOUTH_CHICKEN1);
4055         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4056                 return;
4057
4058         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4059         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4060
4061         temp &= ~FDI_BC_BIFURCATION_SELECT;
4062         if (enable)
4063                 temp |= FDI_BC_BIFURCATION_SELECT;
4064
4065         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4066         I915_WRITE(SOUTH_CHICKEN1, temp);
4067         POSTING_READ(SOUTH_CHICKEN1);
4068 }
4069
4070 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4071 {
4072         struct drm_device *dev = intel_crtc->base.dev;
4073
4074         switch (intel_crtc->pipe) {
4075         case PIPE_A:
4076                 break;
4077         case PIPE_B:
4078                 if (intel_crtc->config->fdi_lanes > 2)
4079                         cpt_set_fdi_bc_bifurcation(dev, false);
4080                 else
4081                         cpt_set_fdi_bc_bifurcation(dev, true);
4082
4083                 break;
4084         case PIPE_C:
4085                 cpt_set_fdi_bc_bifurcation(dev, true);
4086
4087                 break;
4088         default:
4089                 BUG();
4090         }
4091 }
4092
4093 /* Return which DP Port should be selected for Transcoder DP control */
4094 static enum port
4095 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4096 {
4097         struct drm_device *dev = crtc->dev;
4098         struct intel_encoder *encoder;
4099
4100         for_each_encoder_on_crtc(dev, crtc, encoder) {
4101                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4102                     encoder->type == INTEL_OUTPUT_EDP)
4103                         return enc_to_dig_port(&encoder->base)->port;
4104         }
4105
4106         return -1;
4107 }
4108
4109 /*
4110  * Enable PCH resources required for PCH ports:
4111  *   - PCH PLLs
4112  *   - FDI training & RX/TX
4113  *   - update transcoder timings
4114  *   - DP transcoding bits
4115  *   - transcoder
4116  */
4117 static void ironlake_pch_enable(struct drm_crtc *crtc)
4118 {
4119         struct drm_device *dev = crtc->dev;
4120         struct drm_i915_private *dev_priv = dev->dev_private;
4121         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4122         int pipe = intel_crtc->pipe;
4123         u32 temp;
4124
4125         assert_pch_transcoder_disabled(dev_priv, pipe);
4126
4127         if (IS_IVYBRIDGE(dev))
4128                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4129
4130         /* Write the TU size bits before fdi link training, so that error
4131          * detection works. */
4132         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4133                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4134
4135         /*
4136          * Sometimes spurious CPU pipe underruns happen during FDI
4137          * training, at least with VGA+HDMI cloning. Suppress them.
4138          */
4139         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4140
4141         /* For PCH output, training FDI link */
4142         dev_priv->display.fdi_link_train(crtc);
4143
4144         /* We need to program the right clock selection before writing the pixel
4145          * mutliplier into the DPLL. */
4146         if (HAS_PCH_CPT(dev)) {
4147                 u32 sel;
4148
4149                 temp = I915_READ(PCH_DPLL_SEL);
4150                 temp |= TRANS_DPLL_ENABLE(pipe);
4151                 sel = TRANS_DPLLB_SEL(pipe);
4152                 if (intel_crtc->config->shared_dpll ==
4153                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4154                         temp |= sel;
4155                 else
4156                         temp &= ~sel;
4157                 I915_WRITE(PCH_DPLL_SEL, temp);
4158         }
4159
4160         /* XXX: pch pll's can be enabled any time before we enable the PCH
4161          * transcoder, and we actually should do this to not upset any PCH
4162          * transcoder that already use the clock when we share it.
4163          *
4164          * Note that enable_shared_dpll tries to do the right thing, but
4165          * get_shared_dpll unconditionally resets the pll - we need that to have
4166          * the right LVDS enable sequence. */
4167         intel_enable_shared_dpll(intel_crtc);
4168
4169         /* set transcoder timing, panel must allow it */
4170         assert_panel_unlocked(dev_priv, pipe);
4171         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4172
4173         intel_fdi_normal_train(crtc);
4174
4175         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4176
4177         /* For PCH DP, enable TRANS_DP_CTL */
4178         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4179                 const struct drm_display_mode *adjusted_mode =
4180                         &intel_crtc->config->base.adjusted_mode;
4181                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4182                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4183                 temp = I915_READ(reg);
4184                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4185                           TRANS_DP_SYNC_MASK |
4186                           TRANS_DP_BPC_MASK);
4187                 temp |= TRANS_DP_OUTPUT_ENABLE;
4188                 temp |= bpc << 9; /* same format but at 11:9 */
4189
4190                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4191                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4192                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4193                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4194
4195                 switch (intel_trans_dp_port_sel(crtc)) {
4196                 case PORT_B:
4197                         temp |= TRANS_DP_PORT_SEL_B;
4198                         break;
4199                 case PORT_C:
4200                         temp |= TRANS_DP_PORT_SEL_C;
4201                         break;
4202                 case PORT_D:
4203                         temp |= TRANS_DP_PORT_SEL_D;
4204                         break;
4205                 default:
4206                         BUG();
4207                 }
4208
4209                 I915_WRITE(reg, temp);
4210         }
4211
4212         ironlake_enable_pch_transcoder(dev_priv, pipe);
4213 }
4214
4215 static void lpt_pch_enable(struct drm_crtc *crtc)
4216 {
4217         struct drm_device *dev = crtc->dev;
4218         struct drm_i915_private *dev_priv = dev->dev_private;
4219         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4220         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4221
4222         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4223
4224         lpt_program_iclkip(crtc);
4225
4226         /* Set transcoder timing. */
4227         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4228
4229         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4230 }
4231
4232 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4233 {
4234         struct drm_i915_private *dev_priv = dev->dev_private;
4235         i915_reg_t dslreg = PIPEDSL(pipe);
4236         u32 temp;
4237
4238         temp = I915_READ(dslreg);
4239         udelay(500);
4240         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4241                 if (wait_for(I915_READ(dslreg) != temp, 5))
4242                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4243         }
4244 }
4245
4246 static int
4247 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4248                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4249                   int src_w, int src_h, int dst_w, int dst_h)
4250 {
4251         struct intel_crtc_scaler_state *scaler_state =
4252                 &crtc_state->scaler_state;
4253         struct intel_crtc *intel_crtc =
4254                 to_intel_crtc(crtc_state->base.crtc);
4255         int need_scaling;
4256
4257         need_scaling = intel_rotation_90_or_270(rotation) ?
4258                 (src_h != dst_w || src_w != dst_h):
4259                 (src_w != dst_w || src_h != dst_h);
4260
4261         /*
4262          * if plane is being disabled or scaler is no more required or force detach
4263          *  - free scaler binded to this plane/crtc
4264          *  - in order to do this, update crtc->scaler_usage
4265          *
4266          * Here scaler state in crtc_state is set free so that
4267          * scaler can be assigned to other user. Actual register
4268          * update to free the scaler is done in plane/panel-fit programming.
4269          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4270          */
4271         if (force_detach || !need_scaling) {
4272                 if (*scaler_id >= 0) {
4273                         scaler_state->scaler_users &= ~(1 << scaler_user);
4274                         scaler_state->scalers[*scaler_id].in_use = 0;
4275
4276                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4277                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4278                                 intel_crtc->pipe, scaler_user, *scaler_id,
4279                                 scaler_state->scaler_users);
4280                         *scaler_id = -1;
4281                 }
4282                 return 0;
4283         }
4284
4285         /* range checks */
4286         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4287                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4288
4289                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4290                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4291                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4292                         "size is out of scaler range\n",
4293                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4294                 return -EINVAL;
4295         }
4296
4297         /* mark this plane as a scaler user in crtc_state */
4298         scaler_state->scaler_users |= (1 << scaler_user);
4299         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4300                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4301                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4302                 scaler_state->scaler_users);
4303
4304         return 0;
4305 }
4306
4307 /**
4308  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4309  *
4310  * @state: crtc's scaler state
4311  *
4312  * Return
4313  *     0 - scaler_usage updated successfully
4314  *    error - requested scaling cannot be supported or other error condition
4315  */
4316 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4317 {
4318         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4319         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4320
4321         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4322                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4323
4324         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4325                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4326                 state->pipe_src_w, state->pipe_src_h,
4327                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4328 }
4329
4330 /**
4331  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4332  *
4333  * @state: crtc's scaler state
4334  * @plane_state: atomic plane state to update
4335  *
4336  * Return
4337  *     0 - scaler_usage updated successfully
4338  *    error - requested scaling cannot be supported or other error condition
4339  */
4340 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4341                                    struct intel_plane_state *plane_state)
4342 {
4343
4344         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4345         struct intel_plane *intel_plane =
4346                 to_intel_plane(plane_state->base.plane);
4347         struct drm_framebuffer *fb = plane_state->base.fb;
4348         int ret;
4349
4350         bool force_detach = !fb || !plane_state->visible;
4351
4352         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4353                       intel_plane->base.base.id, intel_crtc->pipe,
4354                       drm_plane_index(&intel_plane->base));
4355
4356         ret = skl_update_scaler(crtc_state, force_detach,
4357                                 drm_plane_index(&intel_plane->base),
4358                                 &plane_state->scaler_id,
4359                                 plane_state->base.rotation,
4360                                 drm_rect_width(&plane_state->src) >> 16,
4361                                 drm_rect_height(&plane_state->src) >> 16,
4362                                 drm_rect_width(&plane_state->dst),
4363                                 drm_rect_height(&plane_state->dst));
4364
4365         if (ret || plane_state->scaler_id < 0)
4366                 return ret;
4367
4368         /* check colorkey */
4369         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4370                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4371                               intel_plane->base.base.id);
4372                 return -EINVAL;
4373         }
4374
4375         /* Check src format */
4376         switch (fb->pixel_format) {
4377         case DRM_FORMAT_RGB565:
4378         case DRM_FORMAT_XBGR8888:
4379         case DRM_FORMAT_XRGB8888:
4380         case DRM_FORMAT_ABGR8888:
4381         case DRM_FORMAT_ARGB8888:
4382         case DRM_FORMAT_XRGB2101010:
4383         case DRM_FORMAT_XBGR2101010:
4384         case DRM_FORMAT_YUYV:
4385         case DRM_FORMAT_YVYU:
4386         case DRM_FORMAT_UYVY:
4387         case DRM_FORMAT_VYUY:
4388                 break;
4389         default:
4390                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4391                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4392                 return -EINVAL;
4393         }
4394
4395         return 0;
4396 }
4397
4398 static void skylake_scaler_disable(struct intel_crtc *crtc)
4399 {
4400         int i;
4401
4402         for (i = 0; i < crtc->num_scalers; i++)
4403                 skl_detach_scaler(crtc, i);
4404 }
4405
4406 static void skylake_pfit_enable(struct intel_crtc *crtc)
4407 {
4408         struct drm_device *dev = crtc->base.dev;
4409         struct drm_i915_private *dev_priv = dev->dev_private;
4410         int pipe = crtc->pipe;
4411         struct intel_crtc_scaler_state *scaler_state =
4412                 &crtc->config->scaler_state;
4413
4414         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4415
4416         if (crtc->config->pch_pfit.enabled) {
4417                 int id;
4418
4419                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4420                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4421                         return;
4422                 }
4423
4424                 id = scaler_state->scaler_id;
4425                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4426                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4427                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4428                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4429
4430                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4431         }
4432 }
4433
4434 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4435 {
4436         struct drm_device *dev = crtc->base.dev;
4437         struct drm_i915_private *dev_priv = dev->dev_private;
4438         int pipe = crtc->pipe;
4439
4440         if (crtc->config->pch_pfit.enabled) {
4441                 /* Force use of hard-coded filter coefficients
4442                  * as some pre-programmed values are broken,
4443                  * e.g. x201.
4444                  */
4445                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4446                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4447                                                  PF_PIPE_SEL_IVB(pipe));
4448                 else
4449                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4450                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4451                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4452         }
4453 }
4454
4455 void hsw_enable_ips(struct intel_crtc *crtc)
4456 {
4457         struct drm_device *dev = crtc->base.dev;
4458         struct drm_i915_private *dev_priv = dev->dev_private;
4459
4460         if (!crtc->config->ips_enabled)
4461                 return;
4462
4463         /* We can only enable IPS after we enable a plane and wait for a vblank */
4464         intel_wait_for_vblank(dev, crtc->pipe);
4465
4466         assert_plane_enabled(dev_priv, crtc->plane);
4467         if (IS_BROADWELL(dev)) {
4468                 mutex_lock(&dev_priv->rps.hw_lock);
4469                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4470                 mutex_unlock(&dev_priv->rps.hw_lock);
4471                 /* Quoting Art Runyan: "its not safe to expect any particular
4472                  * value in IPS_CTL bit 31 after enabling IPS through the
4473                  * mailbox." Moreover, the mailbox may return a bogus state,
4474                  * so we need to just enable it and continue on.
4475                  */
4476         } else {
4477                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4478                 /* The bit only becomes 1 in the next vblank, so this wait here
4479                  * is essentially intel_wait_for_vblank. If we don't have this
4480                  * and don't wait for vblanks until the end of crtc_enable, then
4481                  * the HW state readout code will complain that the expected
4482                  * IPS_CTL value is not the one we read. */
4483                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4484                         DRM_ERROR("Timed out waiting for IPS enable\n");
4485         }
4486 }
4487
4488 void hsw_disable_ips(struct intel_crtc *crtc)
4489 {
4490         struct drm_device *dev = crtc->base.dev;
4491         struct drm_i915_private *dev_priv = dev->dev_private;
4492
4493         if (!crtc->config->ips_enabled)
4494                 return;
4495
4496         assert_plane_enabled(dev_priv, crtc->plane);
4497         if (IS_BROADWELL(dev)) {
4498                 mutex_lock(&dev_priv->rps.hw_lock);
4499                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4500                 mutex_unlock(&dev_priv->rps.hw_lock);
4501                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4502                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4503                         DRM_ERROR("Timed out waiting for IPS disable\n");
4504         } else {
4505                 I915_WRITE(IPS_CTL, 0);
4506                 POSTING_READ(IPS_CTL);
4507         }
4508
4509         /* We need to wait for a vblank before we can disable the plane. */
4510         intel_wait_for_vblank(dev, crtc->pipe);
4511 }
4512
4513 /** Loads the palette/gamma unit for the CRTC with the prepared values */
4514 static void intel_crtc_load_lut(struct drm_crtc *crtc)
4515 {
4516         struct drm_device *dev = crtc->dev;
4517         struct drm_i915_private *dev_priv = dev->dev_private;
4518         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4519         enum pipe pipe = intel_crtc->pipe;
4520         int i;
4521         bool reenable_ips = false;
4522
4523         /* The clocks have to be on to load the palette. */
4524         if (!crtc->state->active)
4525                 return;
4526
4527         if (HAS_GMCH_DISPLAY(dev_priv->dev)) {
4528                 if (intel_crtc->config->has_dsi_encoder)
4529                         assert_dsi_pll_enabled(dev_priv);
4530                 else
4531                         assert_pll_enabled(dev_priv, pipe);
4532         }
4533
4534         /* Workaround : Do not read or write the pipe palette/gamma data while
4535          * GAMMA_MODE is configured for split gamma and IPS_CTL has IPS enabled.
4536          */
4537         if (IS_HASWELL(dev) && intel_crtc->config->ips_enabled &&
4538             ((I915_READ(GAMMA_MODE(pipe)) & GAMMA_MODE_MODE_MASK) ==
4539              GAMMA_MODE_MODE_SPLIT)) {
4540                 hsw_disable_ips(intel_crtc);
4541                 reenable_ips = true;
4542         }
4543
4544         for (i = 0; i < 256; i++) {
4545                 i915_reg_t palreg;
4546
4547                 if (HAS_GMCH_DISPLAY(dev))
4548                         palreg = PALETTE(pipe, i);
4549                 else
4550                         palreg = LGC_PALETTE(pipe, i);
4551
4552                 I915_WRITE(palreg,
4553                            (intel_crtc->lut_r[i] << 16) |
4554                            (intel_crtc->lut_g[i] << 8) |
4555                            intel_crtc->lut_b[i]);
4556         }
4557
4558         if (reenable_ips)
4559                 hsw_enable_ips(intel_crtc);
4560 }
4561
4562 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4563 {
4564         if (intel_crtc->overlay) {
4565                 struct drm_device *dev = intel_crtc->base.dev;
4566                 struct drm_i915_private *dev_priv = dev->dev_private;
4567
4568                 mutex_lock(&dev->struct_mutex);
4569                 dev_priv->mm.interruptible = false;
4570                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4571                 dev_priv->mm.interruptible = true;
4572                 mutex_unlock(&dev->struct_mutex);
4573         }
4574
4575         /* Let userspace switch the overlay on again. In most cases userspace
4576          * has to recompute where to put it anyway.
4577          */
4578 }
4579
4580 /**
4581  * intel_post_enable_primary - Perform operations after enabling primary plane
4582  * @crtc: the CRTC whose primary plane was just enabled
4583  *
4584  * Performs potentially sleeping operations that must be done after the primary
4585  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4586  * called due to an explicit primary plane update, or due to an implicit
4587  * re-enable that is caused when a sprite plane is updated to no longer
4588  * completely hide the primary plane.
4589  */
4590 static void
4591 intel_post_enable_primary(struct drm_crtc *crtc)
4592 {
4593         struct drm_device *dev = crtc->dev;
4594         struct drm_i915_private *dev_priv = dev->dev_private;
4595         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4596         int pipe = intel_crtc->pipe;
4597
4598         /*
4599          * FIXME IPS should be fine as long as one plane is
4600          * enabled, but in practice it seems to have problems
4601          * when going from primary only to sprite only and vice
4602          * versa.
4603          */
4604         hsw_enable_ips(intel_crtc);
4605
4606         /*
4607          * Gen2 reports pipe underruns whenever all planes are disabled.
4608          * So don't enable underrun reporting before at least some planes
4609          * are enabled.
4610          * FIXME: Need to fix the logic to work when we turn off all planes
4611          * but leave the pipe running.
4612          */
4613         if (IS_GEN2(dev))
4614                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4615
4616         /* Underruns don't always raise interrupts, so check manually. */
4617         intel_check_cpu_fifo_underruns(dev_priv);
4618         intel_check_pch_fifo_underruns(dev_priv);
4619 }
4620
4621 /* FIXME move all this to pre_plane_update() with proper state tracking */
4622 static void
4623 intel_pre_disable_primary(struct drm_crtc *crtc)
4624 {
4625         struct drm_device *dev = crtc->dev;
4626         struct drm_i915_private *dev_priv = dev->dev_private;
4627         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4628         int pipe = intel_crtc->pipe;
4629
4630         /*
4631          * Gen2 reports pipe underruns whenever all planes are disabled.
4632          * So diasble underrun reporting before all the planes get disabled.
4633          * FIXME: Need to fix the logic to work when we turn off all planes
4634          * but leave the pipe running.
4635          */
4636         if (IS_GEN2(dev))
4637                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4638
4639         /*
4640          * FIXME IPS should be fine as long as one plane is
4641          * enabled, but in practice it seems to have problems
4642          * when going from primary only to sprite only and vice
4643          * versa.
4644          */
4645         hsw_disable_ips(intel_crtc);
4646 }
4647
4648 /* FIXME get rid of this and use pre_plane_update */
4649 static void
4650 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4651 {
4652         struct drm_device *dev = crtc->dev;
4653         struct drm_i915_private *dev_priv = dev->dev_private;
4654         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4655         int pipe = intel_crtc->pipe;
4656
4657         intel_pre_disable_primary(crtc);
4658
4659         /*
4660          * Vblank time updates from the shadow to live plane control register
4661          * are blocked if the memory self-refresh mode is active at that
4662          * moment. So to make sure the plane gets truly disabled, disable
4663          * first the self-refresh mode. The self-refresh enable bit in turn
4664          * will be checked/applied by the HW only at the next frame start
4665          * event which is after the vblank start event, so we need to have a
4666          * wait-for-vblank between disabling the plane and the pipe.
4667          */
4668         if (HAS_GMCH_DISPLAY(dev)) {
4669                 intel_set_memory_cxsr(dev_priv, false);
4670                 dev_priv->wm.vlv.cxsr = false;
4671                 intel_wait_for_vblank(dev, pipe);
4672         }
4673 }
4674
4675 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4676 {
4677         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4678         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4679         struct intel_crtc_state *pipe_config =
4680                 to_intel_crtc_state(crtc->base.state);
4681         struct drm_device *dev = crtc->base.dev;
4682         struct drm_plane *primary = crtc->base.primary;
4683         struct drm_plane_state *old_pri_state =
4684                 drm_atomic_get_existing_plane_state(old_state, primary);
4685
4686         intel_frontbuffer_flip(dev, pipe_config->fb_bits);
4687
4688         crtc->wm.cxsr_allowed = true;
4689
4690         if (pipe_config->update_wm_post && pipe_config->base.active)
4691                 intel_update_watermarks(&crtc->base);
4692
4693         if (old_pri_state) {
4694                 struct intel_plane_state *primary_state =
4695                         to_intel_plane_state(primary->state);
4696                 struct intel_plane_state *old_primary_state =
4697                         to_intel_plane_state(old_pri_state);
4698
4699                 intel_fbc_post_update(crtc);
4700
4701                 if (primary_state->visible &&
4702                     (needs_modeset(&pipe_config->base) ||
4703                      !old_primary_state->visible))
4704                         intel_post_enable_primary(&crtc->base);
4705         }
4706 }
4707
4708 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4709 {
4710         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4711         struct drm_device *dev = crtc->base.dev;
4712         struct drm_i915_private *dev_priv = dev->dev_private;
4713         struct intel_crtc_state *pipe_config =
4714                 to_intel_crtc_state(crtc->base.state);
4715         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4716         struct drm_plane *primary = crtc->base.primary;
4717         struct drm_plane_state *old_pri_state =
4718                 drm_atomic_get_existing_plane_state(old_state, primary);
4719         bool modeset = needs_modeset(&pipe_config->base);
4720
4721         if (old_pri_state) {
4722                 struct intel_plane_state *primary_state =
4723                         to_intel_plane_state(primary->state);
4724                 struct intel_plane_state *old_primary_state =
4725                         to_intel_plane_state(old_pri_state);
4726
4727                 intel_fbc_pre_update(crtc);
4728
4729                 if (old_primary_state->visible &&
4730                     (modeset || !primary_state->visible))
4731                         intel_pre_disable_primary(&crtc->base);
4732         }
4733
4734         if (pipe_config->disable_cxsr) {
4735                 crtc->wm.cxsr_allowed = false;
4736
4737                 /*
4738                  * Vblank time updates from the shadow to live plane control register
4739                  * are blocked if the memory self-refresh mode is active at that
4740                  * moment. So to make sure the plane gets truly disabled, disable
4741                  * first the self-refresh mode. The self-refresh enable bit in turn
4742                  * will be checked/applied by the HW only at the next frame start
4743                  * event which is after the vblank start event, so we need to have a
4744                  * wait-for-vblank between disabling the plane and the pipe.
4745                  */
4746                 if (old_crtc_state->base.active) {
4747                         intel_set_memory_cxsr(dev_priv, false);
4748                         dev_priv->wm.vlv.cxsr = false;
4749                         intel_wait_for_vblank(dev, crtc->pipe);
4750                 }
4751         }
4752
4753         /*
4754          * IVB workaround: must disable low power watermarks for at least
4755          * one frame before enabling scaling.  LP watermarks can be re-enabled
4756          * when scaling is disabled.
4757          *
4758          * WaCxSRDisabledForSpriteScaling:ivb
4759          */
4760         if (pipe_config->disable_lp_wm) {
4761                 ilk_disable_lp_wm(dev);
4762                 intel_wait_for_vblank(dev, crtc->pipe);
4763         }
4764
4765         /*
4766          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4767          * watermark programming here.
4768          */
4769         if (needs_modeset(&pipe_config->base))
4770                 return;
4771
4772         /*
4773          * For platforms that support atomic watermarks, program the
4774          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4775          * will be the intermediate values that are safe for both pre- and
4776          * post- vblank; when vblank happens, the 'active' values will be set
4777          * to the final 'target' values and we'll do this again to get the
4778          * optimal watermarks.  For gen9+ platforms, the values we program here
4779          * will be the final target values which will get automatically latched
4780          * at vblank time; no further programming will be necessary.
4781          *
4782          * If a platform hasn't been transitioned to atomic watermarks yet,
4783          * we'll continue to update watermarks the old way, if flags tell
4784          * us to.
4785          */
4786         if (dev_priv->display.initial_watermarks != NULL)
4787                 dev_priv->display.initial_watermarks(pipe_config);
4788         else if (pipe_config->update_wm_pre)
4789                 intel_update_watermarks(&crtc->base);
4790 }
4791
4792 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4793 {
4794         struct drm_device *dev = crtc->dev;
4795         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4796         struct drm_plane *p;
4797         int pipe = intel_crtc->pipe;
4798
4799         intel_crtc_dpms_overlay_disable(intel_crtc);
4800
4801         drm_for_each_plane_mask(p, dev, plane_mask)
4802                 to_intel_plane(p)->disable_plane(p, crtc);
4803
4804         /*
4805          * FIXME: Once we grow proper nuclear flip support out of this we need
4806          * to compute the mask of flip planes precisely. For the time being
4807          * consider this a flip to a NULL plane.
4808          */
4809         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4810 }
4811
4812 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4813 {
4814         struct drm_device *dev = crtc->dev;
4815         struct drm_i915_private *dev_priv = dev->dev_private;
4816         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4817         struct intel_encoder *encoder;
4818         int pipe = intel_crtc->pipe;
4819
4820         if (WARN_ON(intel_crtc->active))
4821                 return;
4822
4823         if (intel_crtc->config->has_pch_encoder)
4824                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4825
4826         if (intel_crtc->config->has_pch_encoder)
4827                 intel_prepare_shared_dpll(intel_crtc);
4828
4829         if (intel_crtc->config->has_dp_encoder)
4830                 intel_dp_set_m_n(intel_crtc, M1_N1);
4831
4832         intel_set_pipe_timings(intel_crtc);
4833         intel_set_pipe_src_size(intel_crtc);
4834
4835         if (intel_crtc->config->has_pch_encoder) {
4836                 intel_cpu_transcoder_set_m_n(intel_crtc,
4837                                      &intel_crtc->config->fdi_m_n, NULL);
4838         }
4839
4840         ironlake_set_pipeconf(crtc);
4841
4842         intel_crtc->active = true;
4843
4844         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4845
4846         for_each_encoder_on_crtc(dev, crtc, encoder)
4847                 if (encoder->pre_enable)
4848                         encoder->pre_enable(encoder);
4849
4850         if (intel_crtc->config->has_pch_encoder) {
4851                 /* Note: FDI PLL enabling _must_ be done before we enable the
4852                  * cpu pipes, hence this is separate from all the other fdi/pch
4853                  * enabling. */
4854                 ironlake_fdi_pll_enable(intel_crtc);
4855         } else {
4856                 assert_fdi_tx_disabled(dev_priv, pipe);
4857                 assert_fdi_rx_disabled(dev_priv, pipe);
4858         }
4859
4860         ironlake_pfit_enable(intel_crtc);
4861
4862         /*
4863          * On ILK+ LUT must be loaded before the pipe is running but with
4864          * clocks enabled
4865          */
4866         intel_crtc_load_lut(crtc);
4867
4868         if (dev_priv->display.initial_watermarks != NULL)
4869                 dev_priv->display.initial_watermarks(intel_crtc->config);
4870         intel_enable_pipe(intel_crtc);
4871
4872         if (intel_crtc->config->has_pch_encoder)
4873                 ironlake_pch_enable(crtc);
4874
4875         assert_vblank_disabled(crtc);
4876         drm_crtc_vblank_on(crtc);
4877
4878         for_each_encoder_on_crtc(dev, crtc, encoder)
4879                 encoder->enable(encoder);
4880
4881         if (HAS_PCH_CPT(dev))
4882                 cpt_verify_modeset(dev, intel_crtc->pipe);
4883
4884         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4885         if (intel_crtc->config->has_pch_encoder)
4886                 intel_wait_for_vblank(dev, pipe);
4887         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4888 }
4889
4890 /* IPS only exists on ULT machines and is tied to pipe A. */
4891 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4892 {
4893         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4894 }
4895
4896 static void haswell_crtc_enable(struct drm_crtc *crtc)
4897 {
4898         struct drm_device *dev = crtc->dev;
4899         struct drm_i915_private *dev_priv = dev->dev_private;
4900         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4901         struct intel_encoder *encoder;
4902         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4903         struct intel_crtc_state *pipe_config =
4904                 to_intel_crtc_state(crtc->state);
4905
4906         if (WARN_ON(intel_crtc->active))
4907                 return;
4908
4909         if (intel_crtc->config->has_pch_encoder)
4910                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4911                                                       false);
4912
4913         if (intel_crtc->config->shared_dpll)
4914                 intel_enable_shared_dpll(intel_crtc);
4915
4916         if (intel_crtc->config->has_dp_encoder)
4917                 intel_dp_set_m_n(intel_crtc, M1_N1);
4918
4919         intel_set_pipe_timings(intel_crtc);
4920         intel_set_pipe_src_size(intel_crtc);
4921
4922         if (intel_crtc->config->cpu_transcoder != TRANSCODER_EDP) {
4923                 I915_WRITE(PIPE_MULT(intel_crtc->config->cpu_transcoder),
4924                            intel_crtc->config->pixel_multiplier - 1);
4925         }
4926
4927         if (intel_crtc->config->has_pch_encoder) {
4928                 intel_cpu_transcoder_set_m_n(intel_crtc,
4929                                      &intel_crtc->config->fdi_m_n, NULL);
4930         }
4931
4932         haswell_set_pipeconf(crtc);
4933         haswell_set_pipe_gamma(crtc);
4934         haswell_set_pipemisc(crtc);
4935
4936         intel_set_pipe_csc(crtc);
4937
4938         intel_crtc->active = true;
4939
4940         if (intel_crtc->config->has_pch_encoder)
4941                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4942         else
4943                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4944
4945         for_each_encoder_on_crtc(dev, crtc, encoder) {
4946                 if (encoder->pre_enable)
4947                         encoder->pre_enable(encoder);
4948         }
4949
4950         if (intel_crtc->config->has_pch_encoder)
4951                 dev_priv->display.fdi_link_train(crtc);
4952
4953         if (!intel_crtc->config->has_dsi_encoder)
4954                 intel_ddi_enable_pipe_clock(intel_crtc);
4955
4956         if (INTEL_INFO(dev)->gen >= 9)
4957                 skylake_pfit_enable(intel_crtc);
4958         else
4959                 ironlake_pfit_enable(intel_crtc);
4960
4961         /*
4962          * On ILK+ LUT must be loaded before the pipe is running but with
4963          * clocks enabled
4964          */
4965         intel_crtc_load_lut(crtc);
4966
4967         intel_ddi_set_pipe_settings(crtc);
4968         if (!intel_crtc->config->has_dsi_encoder)
4969                 intel_ddi_enable_transcoder_func(crtc);
4970
4971         if (dev_priv->display.initial_watermarks != NULL)
4972                 dev_priv->display.initial_watermarks(pipe_config);
4973         else
4974                 intel_update_watermarks(crtc);
4975         intel_enable_pipe(intel_crtc);
4976
4977         if (intel_crtc->config->has_pch_encoder)
4978                 lpt_pch_enable(crtc);
4979
4980         if (intel_crtc->config->dp_encoder_is_mst)
4981                 intel_ddi_set_vc_payload_alloc(crtc, true);
4982
4983         assert_vblank_disabled(crtc);
4984         drm_crtc_vblank_on(crtc);
4985
4986         for_each_encoder_on_crtc(dev, crtc, encoder) {
4987                 encoder->enable(encoder);
4988                 intel_opregion_notify_encoder(encoder, true);
4989         }
4990
4991         if (intel_crtc->config->has_pch_encoder) {
4992                 intel_wait_for_vblank(dev, pipe);
4993                 intel_wait_for_vblank(dev, pipe);
4994                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4995                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4996                                                       true);
4997         }
4998
4999         /* If we change the relative order between pipe/planes enabling, we need
5000          * to change the workaround. */
5001         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5002         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
5003                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5004                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
5005         }
5006 }
5007
5008 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5009 {
5010         struct drm_device *dev = crtc->base.dev;
5011         struct drm_i915_private *dev_priv = dev->dev_private;
5012         int pipe = crtc->pipe;
5013
5014         /* To avoid upsetting the power well on haswell only disable the pfit if
5015          * it's in use. The hw state code will make sure we get this right. */
5016         if (force || crtc->config->pch_pfit.enabled) {
5017                 I915_WRITE(PF_CTL(pipe), 0);
5018                 I915_WRITE(PF_WIN_POS(pipe), 0);
5019                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5020         }
5021 }
5022
5023 static void ironlake_crtc_disable(struct drm_crtc *crtc)
5024 {
5025         struct drm_device *dev = crtc->dev;
5026         struct drm_i915_private *dev_priv = dev->dev_private;
5027         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5028         struct intel_encoder *encoder;
5029         int pipe = intel_crtc->pipe;
5030
5031         if (intel_crtc->config->has_pch_encoder)
5032                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5033
5034         for_each_encoder_on_crtc(dev, crtc, encoder)
5035                 encoder->disable(encoder);
5036
5037         drm_crtc_vblank_off(crtc);
5038         assert_vblank_disabled(crtc);
5039
5040         /*
5041          * Sometimes spurious CPU pipe underruns happen when the
5042          * pipe is already disabled, but FDI RX/TX is still enabled.
5043          * Happens at least with VGA+HDMI cloning. Suppress them.
5044          */
5045         if (intel_crtc->config->has_pch_encoder)
5046                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5047
5048         intel_disable_pipe(intel_crtc);
5049
5050         ironlake_pfit_disable(intel_crtc, false);
5051
5052         if (intel_crtc->config->has_pch_encoder) {
5053                 ironlake_fdi_disable(crtc);
5054                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5055         }
5056
5057         for_each_encoder_on_crtc(dev, crtc, encoder)
5058                 if (encoder->post_disable)
5059                         encoder->post_disable(encoder);
5060
5061         if (intel_crtc->config->has_pch_encoder) {
5062                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5063
5064                 if (HAS_PCH_CPT(dev)) {
5065                         i915_reg_t reg;
5066                         u32 temp;
5067
5068                         /* disable TRANS_DP_CTL */
5069                         reg = TRANS_DP_CTL(pipe);
5070                         temp = I915_READ(reg);
5071                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5072                                   TRANS_DP_PORT_SEL_MASK);
5073                         temp |= TRANS_DP_PORT_SEL_NONE;
5074                         I915_WRITE(reg, temp);
5075
5076                         /* disable DPLL_SEL */
5077                         temp = I915_READ(PCH_DPLL_SEL);
5078                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5079                         I915_WRITE(PCH_DPLL_SEL, temp);
5080                 }
5081
5082                 ironlake_fdi_pll_disable(intel_crtc);
5083         }
5084
5085         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5086 }
5087
5088 static void haswell_crtc_disable(struct drm_crtc *crtc)
5089 {
5090         struct drm_device *dev = crtc->dev;
5091         struct drm_i915_private *dev_priv = dev->dev_private;
5092         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5093         struct intel_encoder *encoder;
5094         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5095
5096         if (intel_crtc->config->has_pch_encoder)
5097                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5098                                                       false);
5099
5100         for_each_encoder_on_crtc(dev, crtc, encoder) {
5101                 intel_opregion_notify_encoder(encoder, false);
5102                 encoder->disable(encoder);
5103         }
5104
5105         drm_crtc_vblank_off(crtc);
5106         assert_vblank_disabled(crtc);
5107
5108         intel_disable_pipe(intel_crtc);
5109
5110         if (intel_crtc->config->dp_encoder_is_mst)
5111                 intel_ddi_set_vc_payload_alloc(crtc, false);
5112
5113         if (!intel_crtc->config->has_dsi_encoder)
5114                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5115
5116         if (INTEL_INFO(dev)->gen >= 9)
5117                 skylake_scaler_disable(intel_crtc);
5118         else
5119                 ironlake_pfit_disable(intel_crtc, false);
5120
5121         if (!intel_crtc->config->has_dsi_encoder)
5122                 intel_ddi_disable_pipe_clock(intel_crtc);
5123
5124         for_each_encoder_on_crtc(dev, crtc, encoder)
5125                 if (encoder->post_disable)
5126                         encoder->post_disable(encoder);
5127
5128         if (intel_crtc->config->has_pch_encoder) {
5129                 lpt_disable_pch_transcoder(dev_priv);
5130                 lpt_disable_iclkip(dev_priv);
5131                 intel_ddi_fdi_disable(crtc);
5132
5133                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5134                                                       true);
5135         }
5136 }
5137
5138 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5139 {
5140         struct drm_device *dev = crtc->base.dev;
5141         struct drm_i915_private *dev_priv = dev->dev_private;
5142         struct intel_crtc_state *pipe_config = crtc->config;
5143
5144         if (!pipe_config->gmch_pfit.control)
5145                 return;
5146
5147         /*
5148          * The panel fitter should only be adjusted whilst the pipe is disabled,
5149          * according to register description and PRM.
5150          */
5151         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5152         assert_pipe_disabled(dev_priv, crtc->pipe);
5153
5154         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5155         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5156
5157         /* Border color in case we don't scale up to the full screen. Black by
5158          * default, change to something else for debugging. */
5159         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5160 }
5161
5162 static enum intel_display_power_domain port_to_power_domain(enum port port)
5163 {
5164         switch (port) {
5165         case PORT_A:
5166                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5167         case PORT_B:
5168                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5169         case PORT_C:
5170                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5171         case PORT_D:
5172                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5173         case PORT_E:
5174                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5175         default:
5176                 MISSING_CASE(port);
5177                 return POWER_DOMAIN_PORT_OTHER;
5178         }
5179 }
5180
5181 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5182 {
5183         switch (port) {
5184         case PORT_A:
5185                 return POWER_DOMAIN_AUX_A;
5186         case PORT_B:
5187                 return POWER_DOMAIN_AUX_B;
5188         case PORT_C:
5189                 return POWER_DOMAIN_AUX_C;
5190         case PORT_D:
5191                 return POWER_DOMAIN_AUX_D;
5192         case PORT_E:
5193                 /* FIXME: Check VBT for actual wiring of PORT E */
5194                 return POWER_DOMAIN_AUX_D;
5195         default:
5196                 MISSING_CASE(port);
5197                 return POWER_DOMAIN_AUX_A;
5198         }
5199 }
5200
5201 enum intel_display_power_domain
5202 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5203 {
5204         struct drm_device *dev = intel_encoder->base.dev;
5205         struct intel_digital_port *intel_dig_port;
5206
5207         switch (intel_encoder->type) {
5208         case INTEL_OUTPUT_UNKNOWN:
5209                 /* Only DDI platforms should ever use this output type */
5210                 WARN_ON_ONCE(!HAS_DDI(dev));
5211         case INTEL_OUTPUT_DISPLAYPORT:
5212         case INTEL_OUTPUT_HDMI:
5213         case INTEL_OUTPUT_EDP:
5214                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5215                 return port_to_power_domain(intel_dig_port->port);
5216         case INTEL_OUTPUT_DP_MST:
5217                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5218                 return port_to_power_domain(intel_dig_port->port);
5219         case INTEL_OUTPUT_ANALOG:
5220                 return POWER_DOMAIN_PORT_CRT;
5221         case INTEL_OUTPUT_DSI:
5222                 return POWER_DOMAIN_PORT_DSI;
5223         default:
5224                 return POWER_DOMAIN_PORT_OTHER;
5225         }
5226 }
5227
5228 enum intel_display_power_domain
5229 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5230 {
5231         struct drm_device *dev = intel_encoder->base.dev;
5232         struct intel_digital_port *intel_dig_port;
5233
5234         switch (intel_encoder->type) {
5235         case INTEL_OUTPUT_UNKNOWN:
5236         case INTEL_OUTPUT_HDMI:
5237                 /*
5238                  * Only DDI platforms should ever use these output types.
5239                  * We can get here after the HDMI detect code has already set
5240                  * the type of the shared encoder. Since we can't be sure
5241                  * what's the status of the given connectors, play safe and
5242                  * run the DP detection too.
5243                  */
5244                 WARN_ON_ONCE(!HAS_DDI(dev));
5245         case INTEL_OUTPUT_DISPLAYPORT:
5246         case INTEL_OUTPUT_EDP:
5247                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5248                 return port_to_aux_power_domain(intel_dig_port->port);
5249         case INTEL_OUTPUT_DP_MST:
5250                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5251                 return port_to_aux_power_domain(intel_dig_port->port);
5252         default:
5253                 MISSING_CASE(intel_encoder->type);
5254                 return POWER_DOMAIN_AUX_A;
5255         }
5256 }
5257
5258 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5259                                             struct intel_crtc_state *crtc_state)
5260 {
5261         struct drm_device *dev = crtc->dev;
5262         struct drm_encoder *encoder;
5263         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5264         enum pipe pipe = intel_crtc->pipe;
5265         unsigned long mask;
5266         enum transcoder transcoder = crtc_state->cpu_transcoder;
5267
5268         if (!crtc_state->base.active)
5269                 return 0;
5270
5271         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5272         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5273         if (crtc_state->pch_pfit.enabled ||
5274             crtc_state->pch_pfit.force_thru)
5275                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5276
5277         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5278                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5279
5280                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5281         }
5282
5283         if (crtc_state->shared_dpll)
5284                 mask |= BIT(POWER_DOMAIN_PLLS);
5285
5286         return mask;
5287 }
5288
5289 static unsigned long
5290 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5291                                struct intel_crtc_state *crtc_state)
5292 {
5293         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5294         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5295         enum intel_display_power_domain domain;
5296         unsigned long domains, new_domains, old_domains;
5297
5298         old_domains = intel_crtc->enabled_power_domains;
5299         intel_crtc->enabled_power_domains = new_domains =
5300                 get_crtc_power_domains(crtc, crtc_state);
5301
5302         domains = new_domains & ~old_domains;
5303
5304         for_each_power_domain(domain, domains)
5305                 intel_display_power_get(dev_priv, domain);
5306
5307         return old_domains & ~new_domains;
5308 }
5309
5310 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5311                                       unsigned long domains)
5312 {
5313         enum intel_display_power_domain domain;
5314
5315         for_each_power_domain(domain, domains)
5316                 intel_display_power_put(dev_priv, domain);
5317 }
5318
5319 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5320 {
5321         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5322
5323         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5324             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5325                 return max_cdclk_freq;
5326         else if (IS_CHERRYVIEW(dev_priv))
5327                 return max_cdclk_freq*95/100;
5328         else if (INTEL_INFO(dev_priv)->gen < 4)
5329                 return 2*max_cdclk_freq*90/100;
5330         else
5331                 return max_cdclk_freq*90/100;
5332 }
5333
5334 static void intel_update_max_cdclk(struct drm_device *dev)
5335 {
5336         struct drm_i915_private *dev_priv = dev->dev_private;
5337
5338         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5339                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5340
5341                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5342                         dev_priv->max_cdclk_freq = 675000;
5343                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5344                         dev_priv->max_cdclk_freq = 540000;
5345                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5346                         dev_priv->max_cdclk_freq = 450000;
5347                 else
5348                         dev_priv->max_cdclk_freq = 337500;
5349         } else if (IS_BROADWELL(dev))  {
5350                 /*
5351                  * FIXME with extra cooling we can allow
5352                  * 540 MHz for ULX and 675 Mhz for ULT.
5353                  * How can we know if extra cooling is
5354                  * available? PCI ID, VTB, something else?
5355                  */
5356                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5357                         dev_priv->max_cdclk_freq = 450000;
5358                 else if (IS_BDW_ULX(dev))
5359                         dev_priv->max_cdclk_freq = 450000;
5360                 else if (IS_BDW_ULT(dev))
5361                         dev_priv->max_cdclk_freq = 540000;
5362                 else
5363                         dev_priv->max_cdclk_freq = 675000;
5364         } else if (IS_CHERRYVIEW(dev)) {
5365                 dev_priv->max_cdclk_freq = 320000;
5366         } else if (IS_VALLEYVIEW(dev)) {
5367                 dev_priv->max_cdclk_freq = 400000;
5368         } else {
5369                 /* otherwise assume cdclk is fixed */
5370                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5371         }
5372
5373         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5374
5375         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5376                          dev_priv->max_cdclk_freq);
5377
5378         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5379                          dev_priv->max_dotclk_freq);
5380 }
5381
5382 static void intel_update_cdclk(struct drm_device *dev)
5383 {
5384         struct drm_i915_private *dev_priv = dev->dev_private;
5385
5386         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5387         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5388                          dev_priv->cdclk_freq);
5389
5390         /*
5391          * Program the gmbus_freq based on the cdclk frequency.
5392          * BSpec erroneously claims we should aim for 4MHz, but
5393          * in fact 1MHz is the correct frequency.
5394          */
5395         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
5396                 /*
5397                  * Program the gmbus_freq based on the cdclk frequency.
5398                  * BSpec erroneously claims we should aim for 4MHz, but
5399                  * in fact 1MHz is the correct frequency.
5400                  */
5401                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5402         }
5403
5404         if (dev_priv->max_cdclk_freq == 0)
5405                 intel_update_max_cdclk(dev);
5406 }
5407
5408 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5409 {
5410         struct drm_i915_private *dev_priv = dev->dev_private;
5411         uint32_t divider;
5412         uint32_t ratio;
5413         uint32_t current_freq;
5414         int ret;
5415
5416         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5417         switch (frequency) {
5418         case 144000:
5419                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5420                 ratio = BXT_DE_PLL_RATIO(60);
5421                 break;
5422         case 288000:
5423                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5424                 ratio = BXT_DE_PLL_RATIO(60);
5425                 break;
5426         case 384000:
5427                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5428                 ratio = BXT_DE_PLL_RATIO(60);
5429                 break;
5430         case 576000:
5431                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5432                 ratio = BXT_DE_PLL_RATIO(60);
5433                 break;
5434         case 624000:
5435                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5436                 ratio = BXT_DE_PLL_RATIO(65);
5437                 break;
5438         case 19200:
5439                 /*
5440                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5441                  * to suppress GCC warning.
5442                  */
5443                 ratio = 0;
5444                 divider = 0;
5445                 break;
5446         default:
5447                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5448
5449                 return;
5450         }
5451
5452         mutex_lock(&dev_priv->rps.hw_lock);
5453         /* Inform power controller of upcoming frequency change */
5454         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5455                                       0x80000000);
5456         mutex_unlock(&dev_priv->rps.hw_lock);
5457
5458         if (ret) {
5459                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5460                           ret, frequency);
5461                 return;
5462         }
5463
5464         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5465         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5466         current_freq = current_freq * 500 + 1000;
5467
5468         /*
5469          * DE PLL has to be disabled when
5470          * - setting to 19.2MHz (bypass, PLL isn't used)
5471          * - before setting to 624MHz (PLL needs toggling)
5472          * - before setting to any frequency from 624MHz (PLL needs toggling)
5473          */
5474         if (frequency == 19200 || frequency == 624000 ||
5475             current_freq == 624000) {
5476                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5477                 /* Timeout 200us */
5478                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5479                              1))
5480                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5481         }
5482
5483         if (frequency != 19200) {
5484                 uint32_t val;
5485
5486                 val = I915_READ(BXT_DE_PLL_CTL);
5487                 val &= ~BXT_DE_PLL_RATIO_MASK;
5488                 val |= ratio;
5489                 I915_WRITE(BXT_DE_PLL_CTL, val);
5490
5491                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5492                 /* Timeout 200us */
5493                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5494                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5495
5496                 val = I915_READ(CDCLK_CTL);
5497                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5498                 val |= divider;
5499                 /*
5500                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5501                  * enable otherwise.
5502                  */
5503                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5504                 if (frequency >= 500000)
5505                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5506
5507                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5508                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5509                 val |= (frequency - 1000) / 500;
5510                 I915_WRITE(CDCLK_CTL, val);
5511         }
5512
5513         mutex_lock(&dev_priv->rps.hw_lock);
5514         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5515                                       DIV_ROUND_UP(frequency, 25000));
5516         mutex_unlock(&dev_priv->rps.hw_lock);
5517
5518         if (ret) {
5519                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5520                           ret, frequency);
5521                 return;
5522         }
5523
5524         intel_update_cdclk(dev);
5525 }
5526
5527 void broxton_init_cdclk(struct drm_device *dev)
5528 {
5529         struct drm_i915_private *dev_priv = dev->dev_private;
5530         uint32_t val;
5531
5532         /*
5533          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5534          * or else the reset will hang because there is no PCH to respond.
5535          * Move the handshake programming to initialization sequence.
5536          * Previously was left up to BIOS.
5537          */
5538         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5539         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5540         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5541
5542         /* Enable PG1 for cdclk */
5543         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5544
5545         /* check if cd clock is enabled */
5546         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5547                 DRM_DEBUG_KMS("Display already initialized\n");
5548                 return;
5549         }
5550
5551         /*
5552          * FIXME:
5553          * - The initial CDCLK needs to be read from VBT.
5554          *   Need to make this change after VBT has changes for BXT.
5555          * - check if setting the max (or any) cdclk freq is really necessary
5556          *   here, it belongs to modeset time
5557          */
5558         broxton_set_cdclk(dev, 624000);
5559
5560         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5561         POSTING_READ(DBUF_CTL);
5562
5563         udelay(10);
5564
5565         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5566                 DRM_ERROR("DBuf power enable timeout!\n");
5567 }
5568
5569 void broxton_uninit_cdclk(struct drm_device *dev)
5570 {
5571         struct drm_i915_private *dev_priv = dev->dev_private;
5572
5573         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5574         POSTING_READ(DBUF_CTL);
5575
5576         udelay(10);
5577
5578         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5579                 DRM_ERROR("DBuf power disable timeout!\n");
5580
5581         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5582         broxton_set_cdclk(dev, 19200);
5583
5584         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5585 }
5586
5587 static const struct skl_cdclk_entry {
5588         unsigned int freq;
5589         unsigned int vco;
5590 } skl_cdclk_frequencies[] = {
5591         { .freq = 308570, .vco = 8640 },
5592         { .freq = 337500, .vco = 8100 },
5593         { .freq = 432000, .vco = 8640 },
5594         { .freq = 450000, .vco = 8100 },
5595         { .freq = 540000, .vco = 8100 },
5596         { .freq = 617140, .vco = 8640 },
5597         { .freq = 675000, .vco = 8100 },
5598 };
5599
5600 static unsigned int skl_cdclk_decimal(unsigned int freq)
5601 {
5602         return (freq - 1000) / 500;
5603 }
5604
5605 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5606 {
5607         unsigned int i;
5608
5609         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5610                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5611
5612                 if (e->freq == freq)
5613                         return e->vco;
5614         }
5615
5616         return 8100;
5617 }
5618
5619 static void
5620 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5621 {
5622         unsigned int min_freq;
5623         u32 val;
5624
5625         /* select the minimum CDCLK before enabling DPLL 0 */
5626         val = I915_READ(CDCLK_CTL);
5627         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5628         val |= CDCLK_FREQ_337_308;
5629
5630         if (required_vco == 8640)
5631                 min_freq = 308570;
5632         else
5633                 min_freq = 337500;
5634
5635         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5636
5637         I915_WRITE(CDCLK_CTL, val);
5638         POSTING_READ(CDCLK_CTL);
5639
5640         /*
5641          * We always enable DPLL0 with the lowest link rate possible, but still
5642          * taking into account the VCO required to operate the eDP panel at the
5643          * desired frequency. The usual DP link rates operate with a VCO of
5644          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5645          * The modeset code is responsible for the selection of the exact link
5646          * rate later on, with the constraint of choosing a frequency that
5647          * works with required_vco.
5648          */
5649         val = I915_READ(DPLL_CTRL1);
5650
5651         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5652                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5653         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5654         if (required_vco == 8640)
5655                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5656                                             SKL_DPLL0);
5657         else
5658                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5659                                             SKL_DPLL0);
5660
5661         I915_WRITE(DPLL_CTRL1, val);
5662         POSTING_READ(DPLL_CTRL1);
5663
5664         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5665
5666         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5667                 DRM_ERROR("DPLL0 not locked\n");
5668 }
5669
5670 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5671 {
5672         int ret;
5673         u32 val;
5674
5675         /* inform PCU we want to change CDCLK */
5676         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5677         mutex_lock(&dev_priv->rps.hw_lock);
5678         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5679         mutex_unlock(&dev_priv->rps.hw_lock);
5680
5681         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5682 }
5683
5684 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5685 {
5686         unsigned int i;
5687
5688         for (i = 0; i < 15; i++) {
5689                 if (skl_cdclk_pcu_ready(dev_priv))
5690                         return true;
5691                 udelay(10);
5692         }
5693
5694         return false;
5695 }
5696
5697 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5698 {
5699         struct drm_device *dev = dev_priv->dev;
5700         u32 freq_select, pcu_ack;
5701
5702         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5703
5704         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5705                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5706                 return;
5707         }
5708
5709         /* set CDCLK_CTL */
5710         switch(freq) {
5711         case 450000:
5712         case 432000:
5713                 freq_select = CDCLK_FREQ_450_432;
5714                 pcu_ack = 1;
5715                 break;
5716         case 540000:
5717                 freq_select = CDCLK_FREQ_540;
5718                 pcu_ack = 2;
5719                 break;
5720         case 308570:
5721         case 337500:
5722         default:
5723                 freq_select = CDCLK_FREQ_337_308;
5724                 pcu_ack = 0;
5725                 break;
5726         case 617140:
5727         case 675000:
5728                 freq_select = CDCLK_FREQ_675_617;
5729                 pcu_ack = 3;
5730                 break;
5731         }
5732
5733         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5734         POSTING_READ(CDCLK_CTL);
5735
5736         /* inform PCU of the change */
5737         mutex_lock(&dev_priv->rps.hw_lock);
5738         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5739         mutex_unlock(&dev_priv->rps.hw_lock);
5740
5741         intel_update_cdclk(dev);
5742 }
5743
5744 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5745 {
5746         /* disable DBUF power */
5747         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5748         POSTING_READ(DBUF_CTL);
5749
5750         udelay(10);
5751
5752         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5753                 DRM_ERROR("DBuf power disable timeout\n");
5754
5755         /* disable DPLL0 */
5756         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5757         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5758                 DRM_ERROR("Couldn't disable DPLL0\n");
5759 }
5760
5761 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5762 {
5763         unsigned int required_vco;
5764
5765         /* DPLL0 not enabled (happens on early BIOS versions) */
5766         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5767                 /* enable DPLL0 */
5768                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5769                 skl_dpll0_enable(dev_priv, required_vco);
5770         }
5771
5772         /* set CDCLK to the frequency the BIOS chose */
5773         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5774
5775         /* enable DBUF power */
5776         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5777         POSTING_READ(DBUF_CTL);
5778
5779         udelay(10);
5780
5781         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5782                 DRM_ERROR("DBuf power enable timeout\n");
5783 }
5784
5785 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5786 {
5787         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5788         uint32_t cdctl = I915_READ(CDCLK_CTL);
5789         int freq = dev_priv->skl_boot_cdclk;
5790
5791         /*
5792          * check if the pre-os intialized the display
5793          * There is SWF18 scratchpad register defined which is set by the
5794          * pre-os which can be used by the OS drivers to check the status
5795          */
5796         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5797                 goto sanitize;
5798
5799         /* Is PLL enabled and locked ? */
5800         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5801                 goto sanitize;
5802
5803         /* DPLL okay; verify the cdclock
5804          *
5805          * Noticed in some instances that the freq selection is correct but
5806          * decimal part is programmed wrong from BIOS where pre-os does not
5807          * enable display. Verify the same as well.
5808          */
5809         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
5810                 /* All well; nothing to sanitize */
5811                 return false;
5812 sanitize:
5813         /*
5814          * As of now initialize with max cdclk till
5815          * we get dynamic cdclk support
5816          * */
5817         dev_priv->skl_boot_cdclk = dev_priv->max_cdclk_freq;
5818         skl_init_cdclk(dev_priv);
5819
5820         /* we did have to sanitize */
5821         return true;
5822 }
5823
5824 /* Adjust CDclk dividers to allow high res or save power if possible */
5825 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5826 {
5827         struct drm_i915_private *dev_priv = dev->dev_private;
5828         u32 val, cmd;
5829
5830         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5831                                         != dev_priv->cdclk_freq);
5832
5833         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5834                 cmd = 2;
5835         else if (cdclk == 266667)
5836                 cmd = 1;
5837         else
5838                 cmd = 0;
5839
5840         mutex_lock(&dev_priv->rps.hw_lock);
5841         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5842         val &= ~DSPFREQGUAR_MASK;
5843         val |= (cmd << DSPFREQGUAR_SHIFT);
5844         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5845         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5846                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5847                      50)) {
5848                 DRM_ERROR("timed out waiting for CDclk change\n");
5849         }
5850         mutex_unlock(&dev_priv->rps.hw_lock);
5851
5852         mutex_lock(&dev_priv->sb_lock);
5853
5854         if (cdclk == 400000) {
5855                 u32 divider;
5856
5857                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5858
5859                 /* adjust cdclk divider */
5860                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5861                 val &= ~CCK_FREQUENCY_VALUES;
5862                 val |= divider;
5863                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5864
5865                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5866                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5867                              50))
5868                         DRM_ERROR("timed out waiting for CDclk change\n");
5869         }
5870
5871         /* adjust self-refresh exit latency value */
5872         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5873         val &= ~0x7f;
5874
5875         /*
5876          * For high bandwidth configs, we set a higher latency in the bunit
5877          * so that the core display fetch happens in time to avoid underruns.
5878          */
5879         if (cdclk == 400000)
5880                 val |= 4500 / 250; /* 4.5 usec */
5881         else
5882                 val |= 3000 / 250; /* 3.0 usec */
5883         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5884
5885         mutex_unlock(&dev_priv->sb_lock);
5886
5887         intel_update_cdclk(dev);
5888 }
5889
5890 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5891 {
5892         struct drm_i915_private *dev_priv = dev->dev_private;
5893         u32 val, cmd;
5894
5895         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5896                                                 != dev_priv->cdclk_freq);
5897
5898         switch (cdclk) {
5899         case 333333:
5900         case 320000:
5901         case 266667:
5902         case 200000:
5903                 break;
5904         default:
5905                 MISSING_CASE(cdclk);
5906                 return;
5907         }
5908
5909         /*
5910          * Specs are full of misinformation, but testing on actual
5911          * hardware has shown that we just need to write the desired
5912          * CCK divider into the Punit register.
5913          */
5914         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5915
5916         mutex_lock(&dev_priv->rps.hw_lock);
5917         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5918         val &= ~DSPFREQGUAR_MASK_CHV;
5919         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5920         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5921         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5922                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5923                      50)) {
5924                 DRM_ERROR("timed out waiting for CDclk change\n");
5925         }
5926         mutex_unlock(&dev_priv->rps.hw_lock);
5927
5928         intel_update_cdclk(dev);
5929 }
5930
5931 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5932                                  int max_pixclk)
5933 {
5934         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5935         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5936
5937         /*
5938          * Really only a few cases to deal with, as only 4 CDclks are supported:
5939          *   200MHz
5940          *   267MHz
5941          *   320/333MHz (depends on HPLL freq)
5942          *   400MHz (VLV only)
5943          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5944          * of the lower bin and adjust if needed.
5945          *
5946          * We seem to get an unstable or solid color picture at 200MHz.
5947          * Not sure what's wrong. For now use 200MHz only when all pipes
5948          * are off.
5949          */
5950         if (!IS_CHERRYVIEW(dev_priv) &&
5951             max_pixclk > freq_320*limit/100)
5952                 return 400000;
5953         else if (max_pixclk > 266667*limit/100)
5954                 return freq_320;
5955         else if (max_pixclk > 0)
5956                 return 266667;
5957         else
5958                 return 200000;
5959 }
5960
5961 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5962                               int max_pixclk)
5963 {
5964         /*
5965          * FIXME:
5966          * - remove the guardband, it's not needed on BXT
5967          * - set 19.2MHz bypass frequency if there are no active pipes
5968          */
5969         if (max_pixclk > 576000*9/10)
5970                 return 624000;
5971         else if (max_pixclk > 384000*9/10)
5972                 return 576000;
5973         else if (max_pixclk > 288000*9/10)
5974                 return 384000;
5975         else if (max_pixclk > 144000*9/10)
5976                 return 288000;
5977         else
5978                 return 144000;
5979 }
5980
5981 /* Compute the max pixel clock for new configuration. */
5982 static int intel_mode_max_pixclk(struct drm_device *dev,
5983                                  struct drm_atomic_state *state)
5984 {
5985         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
5986         struct drm_i915_private *dev_priv = dev->dev_private;
5987         struct drm_crtc *crtc;
5988         struct drm_crtc_state *crtc_state;
5989         unsigned max_pixclk = 0, i;
5990         enum pipe pipe;
5991
5992         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
5993                sizeof(intel_state->min_pixclk));
5994
5995         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5996                 int pixclk = 0;
5997
5998                 if (crtc_state->enable)
5999                         pixclk = crtc_state->adjusted_mode.crtc_clock;
6000
6001                 intel_state->min_pixclk[i] = pixclk;
6002         }
6003
6004         for_each_pipe(dev_priv, pipe)
6005                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
6006
6007         return max_pixclk;
6008 }
6009
6010 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
6011 {
6012         struct drm_device *dev = state->dev;
6013         struct drm_i915_private *dev_priv = dev->dev_private;
6014         int max_pixclk = intel_mode_max_pixclk(dev, state);
6015         struct intel_atomic_state *intel_state =
6016                 to_intel_atomic_state(state);
6017
6018         if (max_pixclk < 0)
6019                 return max_pixclk;
6020
6021         intel_state->cdclk = intel_state->dev_cdclk =
6022                 valleyview_calc_cdclk(dev_priv, max_pixclk);
6023
6024         if (!intel_state->active_crtcs)
6025                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
6026
6027         return 0;
6028 }
6029
6030 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
6031 {
6032         struct drm_device *dev = state->dev;
6033         struct drm_i915_private *dev_priv = dev->dev_private;
6034         int max_pixclk = intel_mode_max_pixclk(dev, state);
6035         struct intel_atomic_state *intel_state =
6036                 to_intel_atomic_state(state);
6037
6038         if (max_pixclk < 0)
6039                 return max_pixclk;
6040
6041         intel_state->cdclk = intel_state->dev_cdclk =
6042                 broxton_calc_cdclk(dev_priv, max_pixclk);
6043
6044         if (!intel_state->active_crtcs)
6045                 intel_state->dev_cdclk = broxton_calc_cdclk(dev_priv, 0);
6046
6047         return 0;
6048 }
6049
6050 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
6051 {
6052         unsigned int credits, default_credits;
6053
6054         if (IS_CHERRYVIEW(dev_priv))
6055                 default_credits = PFI_CREDIT(12);
6056         else
6057                 default_credits = PFI_CREDIT(8);
6058
6059         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
6060                 /* CHV suggested value is 31 or 63 */
6061                 if (IS_CHERRYVIEW(dev_priv))
6062                         credits = PFI_CREDIT_63;
6063                 else
6064                         credits = PFI_CREDIT(15);
6065         } else {
6066                 credits = default_credits;
6067         }
6068
6069         /*
6070          * WA - write default credits before re-programming
6071          * FIXME: should we also set the resend bit here?
6072          */
6073         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6074                    default_credits);
6075
6076         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6077                    credits | PFI_CREDIT_RESEND);
6078
6079         /*
6080          * FIXME is this guaranteed to clear
6081          * immediately or should we poll for it?
6082          */
6083         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6084 }
6085
6086 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6087 {
6088         struct drm_device *dev = old_state->dev;
6089         struct drm_i915_private *dev_priv = dev->dev_private;
6090         struct intel_atomic_state *old_intel_state =
6091                 to_intel_atomic_state(old_state);
6092         unsigned req_cdclk = old_intel_state->dev_cdclk;
6093
6094         /*
6095          * FIXME: We can end up here with all power domains off, yet
6096          * with a CDCLK frequency other than the minimum. To account
6097          * for this take the PIPE-A power domain, which covers the HW
6098          * blocks needed for the following programming. This can be
6099          * removed once it's guaranteed that we get here either with
6100          * the minimum CDCLK set, or the required power domains
6101          * enabled.
6102          */
6103         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6104
6105         if (IS_CHERRYVIEW(dev))
6106                 cherryview_set_cdclk(dev, req_cdclk);
6107         else
6108                 valleyview_set_cdclk(dev, req_cdclk);
6109
6110         vlv_program_pfi_credits(dev_priv);
6111
6112         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6113 }
6114
6115 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6116 {
6117         struct drm_device *dev = crtc->dev;
6118         struct drm_i915_private *dev_priv = to_i915(dev);
6119         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6120         struct intel_encoder *encoder;
6121         int pipe = intel_crtc->pipe;
6122
6123         if (WARN_ON(intel_crtc->active))
6124                 return;
6125
6126         if (intel_crtc->config->has_dp_encoder)
6127                 intel_dp_set_m_n(intel_crtc, M1_N1);
6128
6129         intel_set_pipe_timings(intel_crtc);
6130         intel_set_pipe_src_size(intel_crtc);
6131
6132         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6133                 struct drm_i915_private *dev_priv = dev->dev_private;
6134
6135                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6136                 I915_WRITE(CHV_CANVAS(pipe), 0);
6137         }
6138
6139         i9xx_set_pipeconf(intel_crtc);
6140
6141         intel_crtc->active = true;
6142
6143         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6144
6145         for_each_encoder_on_crtc(dev, crtc, encoder)
6146                 if (encoder->pre_pll_enable)
6147                         encoder->pre_pll_enable(encoder);
6148
6149         if (!intel_crtc->config->has_dsi_encoder) {
6150                 if (IS_CHERRYVIEW(dev)) {
6151                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6152                         chv_enable_pll(intel_crtc, intel_crtc->config);
6153                 } else {
6154                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6155                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6156                 }
6157         }
6158
6159         for_each_encoder_on_crtc(dev, crtc, encoder)
6160                 if (encoder->pre_enable)
6161                         encoder->pre_enable(encoder);
6162
6163         i9xx_pfit_enable(intel_crtc);
6164
6165         intel_crtc_load_lut(crtc);
6166
6167         intel_update_watermarks(crtc);
6168         intel_enable_pipe(intel_crtc);
6169
6170         assert_vblank_disabled(crtc);
6171         drm_crtc_vblank_on(crtc);
6172
6173         for_each_encoder_on_crtc(dev, crtc, encoder)
6174                 encoder->enable(encoder);
6175 }
6176
6177 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6178 {
6179         struct drm_device *dev = crtc->base.dev;
6180         struct drm_i915_private *dev_priv = dev->dev_private;
6181
6182         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6183         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6184 }
6185
6186 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6187 {
6188         struct drm_device *dev = crtc->dev;
6189         struct drm_i915_private *dev_priv = to_i915(dev);
6190         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6191         struct intel_encoder *encoder;
6192         int pipe = intel_crtc->pipe;
6193
6194         if (WARN_ON(intel_crtc->active))
6195                 return;
6196
6197         i9xx_set_pll_dividers(intel_crtc);
6198
6199         if (intel_crtc->config->has_dp_encoder)
6200                 intel_dp_set_m_n(intel_crtc, M1_N1);
6201
6202         intel_set_pipe_timings(intel_crtc);
6203         intel_set_pipe_src_size(intel_crtc);
6204
6205         i9xx_set_pipeconf(intel_crtc);
6206
6207         intel_crtc->active = true;
6208
6209         if (!IS_GEN2(dev))
6210                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6211
6212         for_each_encoder_on_crtc(dev, crtc, encoder)
6213                 if (encoder->pre_enable)
6214                         encoder->pre_enable(encoder);
6215
6216         i9xx_enable_pll(intel_crtc);
6217
6218         i9xx_pfit_enable(intel_crtc);
6219
6220         intel_crtc_load_lut(crtc);
6221
6222         intel_update_watermarks(crtc);
6223         intel_enable_pipe(intel_crtc);
6224
6225         assert_vblank_disabled(crtc);
6226         drm_crtc_vblank_on(crtc);
6227
6228         for_each_encoder_on_crtc(dev, crtc, encoder)
6229                 encoder->enable(encoder);
6230 }
6231
6232 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6233 {
6234         struct drm_device *dev = crtc->base.dev;
6235         struct drm_i915_private *dev_priv = dev->dev_private;
6236
6237         if (!crtc->config->gmch_pfit.control)
6238                 return;
6239
6240         assert_pipe_disabled(dev_priv, crtc->pipe);
6241
6242         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6243                          I915_READ(PFIT_CONTROL));
6244         I915_WRITE(PFIT_CONTROL, 0);
6245 }
6246
6247 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6248 {
6249         struct drm_device *dev = crtc->dev;
6250         struct drm_i915_private *dev_priv = dev->dev_private;
6251         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6252         struct intel_encoder *encoder;
6253         int pipe = intel_crtc->pipe;
6254
6255         /*
6256          * On gen2 planes are double buffered but the pipe isn't, so we must
6257          * wait for planes to fully turn off before disabling the pipe.
6258          * We also need to wait on all gmch platforms because of the
6259          * self-refresh mode constraint explained above.
6260          */
6261         intel_wait_for_vblank(dev, pipe);
6262
6263         for_each_encoder_on_crtc(dev, crtc, encoder)
6264                 encoder->disable(encoder);
6265
6266         drm_crtc_vblank_off(crtc);
6267         assert_vblank_disabled(crtc);
6268
6269         intel_disable_pipe(intel_crtc);
6270
6271         i9xx_pfit_disable(intel_crtc);
6272
6273         for_each_encoder_on_crtc(dev, crtc, encoder)
6274                 if (encoder->post_disable)
6275                         encoder->post_disable(encoder);
6276
6277         if (!intel_crtc->config->has_dsi_encoder) {
6278                 if (IS_CHERRYVIEW(dev))
6279                         chv_disable_pll(dev_priv, pipe);
6280                 else if (IS_VALLEYVIEW(dev))
6281                         vlv_disable_pll(dev_priv, pipe);
6282                 else
6283                         i9xx_disable_pll(intel_crtc);
6284         }
6285
6286         for_each_encoder_on_crtc(dev, crtc, encoder)
6287                 if (encoder->post_pll_disable)
6288                         encoder->post_pll_disable(encoder);
6289
6290         if (!IS_GEN2(dev))
6291                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6292 }
6293
6294 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6295 {
6296         struct intel_encoder *encoder;
6297         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6298         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6299         enum intel_display_power_domain domain;
6300         unsigned long domains;
6301
6302         if (!intel_crtc->active)
6303                 return;
6304
6305         if (to_intel_plane_state(crtc->primary->state)->visible) {
6306                 WARN_ON(intel_crtc->unpin_work);
6307
6308                 intel_pre_disable_primary_noatomic(crtc);
6309
6310                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6311                 to_intel_plane_state(crtc->primary->state)->visible = false;
6312         }
6313
6314         dev_priv->display.crtc_disable(crtc);
6315
6316         DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was enabled, now disabled\n",
6317                       crtc->base.id);
6318
6319         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6320         crtc->state->active = false;
6321         intel_crtc->active = false;
6322         crtc->enabled = false;
6323         crtc->state->connector_mask = 0;
6324         crtc->state->encoder_mask = 0;
6325
6326         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6327                 encoder->base.crtc = NULL;
6328
6329         intel_fbc_disable(intel_crtc);
6330         intel_update_watermarks(crtc);
6331         intel_disable_shared_dpll(intel_crtc);
6332
6333         domains = intel_crtc->enabled_power_domains;
6334         for_each_power_domain(domain, domains)
6335                 intel_display_power_put(dev_priv, domain);
6336         intel_crtc->enabled_power_domains = 0;
6337
6338         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6339         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6340 }
6341
6342 /*
6343  * turn all crtc's off, but do not adjust state
6344  * This has to be paired with a call to intel_modeset_setup_hw_state.
6345  */
6346 int intel_display_suspend(struct drm_device *dev)
6347 {
6348         struct drm_i915_private *dev_priv = to_i915(dev);
6349         struct drm_atomic_state *state;
6350         int ret;
6351
6352         state = drm_atomic_helper_suspend(dev);
6353         ret = PTR_ERR_OR_ZERO(state);
6354         if (ret)
6355                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6356         else
6357                 dev_priv->modeset_restore_state = state;
6358         return ret;
6359 }
6360
6361 void intel_encoder_destroy(struct drm_encoder *encoder)
6362 {
6363         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6364
6365         drm_encoder_cleanup(encoder);
6366         kfree(intel_encoder);
6367 }
6368
6369 /* Cross check the actual hw state with our own modeset state tracking (and it's
6370  * internal consistency). */
6371 static void intel_connector_check_state(struct intel_connector *connector)
6372 {
6373         struct drm_crtc *crtc = connector->base.state->crtc;
6374
6375         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6376                       connector->base.base.id,
6377                       connector->base.name);
6378
6379         if (connector->get_hw_state(connector)) {
6380                 struct intel_encoder *encoder = connector->encoder;
6381                 struct drm_connector_state *conn_state = connector->base.state;
6382
6383                 I915_STATE_WARN(!crtc,
6384                          "connector enabled without attached crtc\n");
6385
6386                 if (!crtc)
6387                         return;
6388
6389                 I915_STATE_WARN(!crtc->state->active,
6390                       "connector is active, but attached crtc isn't\n");
6391
6392                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6393                         return;
6394
6395                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6396                         "atomic encoder doesn't match attached encoder\n");
6397
6398                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6399                         "attached encoder crtc differs from connector crtc\n");
6400         } else {
6401                 I915_STATE_WARN(crtc && crtc->state->active,
6402                         "attached crtc is active, but connector isn't\n");
6403                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6404                         "best encoder set without crtc!\n");
6405         }
6406 }
6407
6408 int intel_connector_init(struct intel_connector *connector)
6409 {
6410         drm_atomic_helper_connector_reset(&connector->base);
6411
6412         if (!connector->base.state)
6413                 return -ENOMEM;
6414
6415         return 0;
6416 }
6417
6418 struct intel_connector *intel_connector_alloc(void)
6419 {
6420         struct intel_connector *connector;
6421
6422         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6423         if (!connector)
6424                 return NULL;
6425
6426         if (intel_connector_init(connector) < 0) {
6427                 kfree(connector);
6428                 return NULL;
6429         }
6430
6431         return connector;
6432 }
6433
6434 /* Simple connector->get_hw_state implementation for encoders that support only
6435  * one connector and no cloning and hence the encoder state determines the state
6436  * of the connector. */
6437 bool intel_connector_get_hw_state(struct intel_connector *connector)
6438 {
6439         enum pipe pipe = 0;
6440         struct intel_encoder *encoder = connector->encoder;
6441
6442         return encoder->get_hw_state(encoder, &pipe);
6443 }
6444
6445 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6446 {
6447         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6448                 return crtc_state->fdi_lanes;
6449
6450         return 0;
6451 }
6452
6453 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6454                                      struct intel_crtc_state *pipe_config)
6455 {
6456         struct drm_atomic_state *state = pipe_config->base.state;
6457         struct intel_crtc *other_crtc;
6458         struct intel_crtc_state *other_crtc_state;
6459
6460         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6461                       pipe_name(pipe), pipe_config->fdi_lanes);
6462         if (pipe_config->fdi_lanes > 4) {
6463                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6464                               pipe_name(pipe), pipe_config->fdi_lanes);
6465                 return -EINVAL;
6466         }
6467
6468         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6469                 if (pipe_config->fdi_lanes > 2) {
6470                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6471                                       pipe_config->fdi_lanes);
6472                         return -EINVAL;
6473                 } else {
6474                         return 0;
6475                 }
6476         }
6477
6478         if (INTEL_INFO(dev)->num_pipes == 2)
6479                 return 0;
6480
6481         /* Ivybridge 3 pipe is really complicated */
6482         switch (pipe) {
6483         case PIPE_A:
6484                 return 0;
6485         case PIPE_B:
6486                 if (pipe_config->fdi_lanes <= 2)
6487                         return 0;
6488
6489                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6490                 other_crtc_state =
6491                         intel_atomic_get_crtc_state(state, other_crtc);
6492                 if (IS_ERR(other_crtc_state))
6493                         return PTR_ERR(other_crtc_state);
6494
6495                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6496                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6497                                       pipe_name(pipe), pipe_config->fdi_lanes);
6498                         return -EINVAL;
6499                 }
6500                 return 0;
6501         case PIPE_C:
6502                 if (pipe_config->fdi_lanes > 2) {
6503                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6504                                       pipe_name(pipe), pipe_config->fdi_lanes);
6505                         return -EINVAL;
6506                 }
6507
6508                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6509                 other_crtc_state =
6510                         intel_atomic_get_crtc_state(state, other_crtc);
6511                 if (IS_ERR(other_crtc_state))
6512                         return PTR_ERR(other_crtc_state);
6513
6514                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6515                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6516                         return -EINVAL;
6517                 }
6518                 return 0;
6519         default:
6520                 BUG();
6521         }
6522 }
6523
6524 #define RETRY 1
6525 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6526                                        struct intel_crtc_state *pipe_config)
6527 {
6528         struct drm_device *dev = intel_crtc->base.dev;
6529         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6530         int lane, link_bw, fdi_dotclock, ret;
6531         bool needs_recompute = false;
6532
6533 retry:
6534         /* FDI is a binary signal running at ~2.7GHz, encoding
6535          * each output octet as 10 bits. The actual frequency
6536          * is stored as a divider into a 100MHz clock, and the
6537          * mode pixel clock is stored in units of 1KHz.
6538          * Hence the bw of each lane in terms of the mode signal
6539          * is:
6540          */
6541         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6542
6543         fdi_dotclock = adjusted_mode->crtc_clock;
6544
6545         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6546                                            pipe_config->pipe_bpp);
6547
6548         pipe_config->fdi_lanes = lane;
6549
6550         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6551                                link_bw, &pipe_config->fdi_m_n);
6552
6553         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6554         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6555                 pipe_config->pipe_bpp -= 2*3;
6556                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6557                               pipe_config->pipe_bpp);
6558                 needs_recompute = true;
6559                 pipe_config->bw_constrained = true;
6560
6561                 goto retry;
6562         }
6563
6564         if (needs_recompute)
6565                 return RETRY;
6566
6567         return ret;
6568 }
6569
6570 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6571                                      struct intel_crtc_state *pipe_config)
6572 {
6573         if (pipe_config->pipe_bpp > 24)
6574                 return false;
6575
6576         /* HSW can handle pixel rate up to cdclk? */
6577         if (IS_HASWELL(dev_priv->dev))
6578                 return true;
6579
6580         /*
6581          * We compare against max which means we must take
6582          * the increased cdclk requirement into account when
6583          * calculating the new cdclk.
6584          *
6585          * Should measure whether using a lower cdclk w/o IPS
6586          */
6587         return ilk_pipe_pixel_rate(pipe_config) <=
6588                 dev_priv->max_cdclk_freq * 95 / 100;
6589 }
6590
6591 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6592                                    struct intel_crtc_state *pipe_config)
6593 {
6594         struct drm_device *dev = crtc->base.dev;
6595         struct drm_i915_private *dev_priv = dev->dev_private;
6596
6597         pipe_config->ips_enabled = i915.enable_ips &&
6598                 hsw_crtc_supports_ips(crtc) &&
6599                 pipe_config_supports_ips(dev_priv, pipe_config);
6600 }
6601
6602 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6603 {
6604         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6605
6606         /* GDG double wide on either pipe, otherwise pipe A only */
6607         return INTEL_INFO(dev_priv)->gen < 4 &&
6608                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6609 }
6610
6611 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6612                                      struct intel_crtc_state *pipe_config)
6613 {
6614         struct drm_device *dev = crtc->base.dev;
6615         struct drm_i915_private *dev_priv = dev->dev_private;
6616         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6617
6618         /* FIXME should check pixel clock limits on all platforms */
6619         if (INTEL_INFO(dev)->gen < 4) {
6620                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6621
6622                 /*
6623                  * Enable double wide mode when the dot clock
6624                  * is > 90% of the (display) core speed.
6625                  */
6626                 if (intel_crtc_supports_double_wide(crtc) &&
6627                     adjusted_mode->crtc_clock > clock_limit) {
6628                         clock_limit *= 2;
6629                         pipe_config->double_wide = true;
6630                 }
6631
6632                 if (adjusted_mode->crtc_clock > clock_limit) {
6633                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6634                                       adjusted_mode->crtc_clock, clock_limit,
6635                                       yesno(pipe_config->double_wide));
6636                         return -EINVAL;
6637                 }
6638         }
6639
6640         /*
6641          * Pipe horizontal size must be even in:
6642          * - DVO ganged mode
6643          * - LVDS dual channel mode
6644          * - Double wide pipe
6645          */
6646         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6647              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6648                 pipe_config->pipe_src_w &= ~1;
6649
6650         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6651          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6652          */
6653         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6654                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6655                 return -EINVAL;
6656
6657         if (HAS_IPS(dev))
6658                 hsw_compute_ips_config(crtc, pipe_config);
6659
6660         if (pipe_config->has_pch_encoder)
6661                 return ironlake_fdi_compute_config(crtc, pipe_config);
6662
6663         return 0;
6664 }
6665
6666 static int skylake_get_display_clock_speed(struct drm_device *dev)
6667 {
6668         struct drm_i915_private *dev_priv = to_i915(dev);
6669         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6670         uint32_t cdctl = I915_READ(CDCLK_CTL);
6671         uint32_t linkrate;
6672
6673         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6674                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6675
6676         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6677                 return 540000;
6678
6679         linkrate = (I915_READ(DPLL_CTRL1) &
6680                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6681
6682         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6683             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6684                 /* vco 8640 */
6685                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6686                 case CDCLK_FREQ_450_432:
6687                         return 432000;
6688                 case CDCLK_FREQ_337_308:
6689                         return 308570;
6690                 case CDCLK_FREQ_675_617:
6691                         return 617140;
6692                 default:
6693                         WARN(1, "Unknown cd freq selection\n");
6694                 }
6695         } else {
6696                 /* vco 8100 */
6697                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6698                 case CDCLK_FREQ_450_432:
6699                         return 450000;
6700                 case CDCLK_FREQ_337_308:
6701                         return 337500;
6702                 case CDCLK_FREQ_675_617:
6703                         return 675000;
6704                 default:
6705                         WARN(1, "Unknown cd freq selection\n");
6706                 }
6707         }
6708
6709         /* error case, do as if DPLL0 isn't enabled */
6710         return 24000;
6711 }
6712
6713 static int broxton_get_display_clock_speed(struct drm_device *dev)
6714 {
6715         struct drm_i915_private *dev_priv = to_i915(dev);
6716         uint32_t cdctl = I915_READ(CDCLK_CTL);
6717         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6718         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6719         int cdclk;
6720
6721         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6722                 return 19200;
6723
6724         cdclk = 19200 * pll_ratio / 2;
6725
6726         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6727         case BXT_CDCLK_CD2X_DIV_SEL_1:
6728                 return cdclk;  /* 576MHz or 624MHz */
6729         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6730                 return cdclk * 2 / 3; /* 384MHz */
6731         case BXT_CDCLK_CD2X_DIV_SEL_2:
6732                 return cdclk / 2; /* 288MHz */
6733         case BXT_CDCLK_CD2X_DIV_SEL_4:
6734                 return cdclk / 4; /* 144MHz */
6735         }
6736
6737         /* error case, do as if DE PLL isn't enabled */
6738         return 19200;
6739 }
6740
6741 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6742 {
6743         struct drm_i915_private *dev_priv = dev->dev_private;
6744         uint32_t lcpll = I915_READ(LCPLL_CTL);
6745         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6746
6747         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6748                 return 800000;
6749         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6750                 return 450000;
6751         else if (freq == LCPLL_CLK_FREQ_450)
6752                 return 450000;
6753         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6754                 return 540000;
6755         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6756                 return 337500;
6757         else
6758                 return 675000;
6759 }
6760
6761 static int haswell_get_display_clock_speed(struct drm_device *dev)
6762 {
6763         struct drm_i915_private *dev_priv = dev->dev_private;
6764         uint32_t lcpll = I915_READ(LCPLL_CTL);
6765         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6766
6767         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6768                 return 800000;
6769         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6770                 return 450000;
6771         else if (freq == LCPLL_CLK_FREQ_450)
6772                 return 450000;
6773         else if (IS_HSW_ULT(dev))
6774                 return 337500;
6775         else
6776                 return 540000;
6777 }
6778
6779 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6780 {
6781         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6782                                       CCK_DISPLAY_CLOCK_CONTROL);
6783 }
6784
6785 static int ilk_get_display_clock_speed(struct drm_device *dev)
6786 {
6787         return 450000;
6788 }
6789
6790 static int i945_get_display_clock_speed(struct drm_device *dev)
6791 {
6792         return 400000;
6793 }
6794
6795 static int i915_get_display_clock_speed(struct drm_device *dev)
6796 {
6797         return 333333;
6798 }
6799
6800 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6801 {
6802         return 200000;
6803 }
6804
6805 static int pnv_get_display_clock_speed(struct drm_device *dev)
6806 {
6807         u16 gcfgc = 0;
6808
6809         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6810
6811         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6812         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6813                 return 266667;
6814         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6815                 return 333333;
6816         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6817                 return 444444;
6818         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6819                 return 200000;
6820         default:
6821                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6822         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6823                 return 133333;
6824         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6825                 return 166667;
6826         }
6827 }
6828
6829 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6830 {
6831         u16 gcfgc = 0;
6832
6833         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6834
6835         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6836                 return 133333;
6837         else {
6838                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6839                 case GC_DISPLAY_CLOCK_333_MHZ:
6840                         return 333333;
6841                 default:
6842                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6843                         return 190000;
6844                 }
6845         }
6846 }
6847
6848 static int i865_get_display_clock_speed(struct drm_device *dev)
6849 {
6850         return 266667;
6851 }
6852
6853 static int i85x_get_display_clock_speed(struct drm_device *dev)
6854 {
6855         u16 hpllcc = 0;
6856
6857         /*
6858          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6859          * encoding is different :(
6860          * FIXME is this the right way to detect 852GM/852GMV?
6861          */
6862         if (dev->pdev->revision == 0x1)
6863                 return 133333;
6864
6865         pci_bus_read_config_word(dev->pdev->bus,
6866                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6867
6868         /* Assume that the hardware is in the high speed state.  This
6869          * should be the default.
6870          */
6871         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6872         case GC_CLOCK_133_200:
6873         case GC_CLOCK_133_200_2:
6874         case GC_CLOCK_100_200:
6875                 return 200000;
6876         case GC_CLOCK_166_250:
6877                 return 250000;
6878         case GC_CLOCK_100_133:
6879                 return 133333;
6880         case GC_CLOCK_133_266:
6881         case GC_CLOCK_133_266_2:
6882         case GC_CLOCK_166_266:
6883                 return 266667;
6884         }
6885
6886         /* Shouldn't happen */
6887         return 0;
6888 }
6889
6890 static int i830_get_display_clock_speed(struct drm_device *dev)
6891 {
6892         return 133333;
6893 }
6894
6895 static unsigned int intel_hpll_vco(struct drm_device *dev)
6896 {
6897         struct drm_i915_private *dev_priv = dev->dev_private;
6898         static const unsigned int blb_vco[8] = {
6899                 [0] = 3200000,
6900                 [1] = 4000000,
6901                 [2] = 5333333,
6902                 [3] = 4800000,
6903                 [4] = 6400000,
6904         };
6905         static const unsigned int pnv_vco[8] = {
6906                 [0] = 3200000,
6907                 [1] = 4000000,
6908                 [2] = 5333333,
6909                 [3] = 4800000,
6910                 [4] = 2666667,
6911         };
6912         static const unsigned int cl_vco[8] = {
6913                 [0] = 3200000,
6914                 [1] = 4000000,
6915                 [2] = 5333333,
6916                 [3] = 6400000,
6917                 [4] = 3333333,
6918                 [5] = 3566667,
6919                 [6] = 4266667,
6920         };
6921         static const unsigned int elk_vco[8] = {
6922                 [0] = 3200000,
6923                 [1] = 4000000,
6924                 [2] = 5333333,
6925                 [3] = 4800000,
6926         };
6927         static const unsigned int ctg_vco[8] = {
6928                 [0] = 3200000,
6929                 [1] = 4000000,
6930                 [2] = 5333333,
6931                 [3] = 6400000,
6932                 [4] = 2666667,
6933                 [5] = 4266667,
6934         };
6935         const unsigned int *vco_table;
6936         unsigned int vco;
6937         uint8_t tmp = 0;
6938
6939         /* FIXME other chipsets? */
6940         if (IS_GM45(dev))
6941                 vco_table = ctg_vco;
6942         else if (IS_G4X(dev))
6943                 vco_table = elk_vco;
6944         else if (IS_CRESTLINE(dev))
6945                 vco_table = cl_vco;
6946         else if (IS_PINEVIEW(dev))
6947                 vco_table = pnv_vco;
6948         else if (IS_G33(dev))
6949                 vco_table = blb_vco;
6950         else
6951                 return 0;
6952
6953         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6954
6955         vco = vco_table[tmp & 0x7];
6956         if (vco == 0)
6957                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6958         else
6959                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6960
6961         return vco;
6962 }
6963
6964 static int gm45_get_display_clock_speed(struct drm_device *dev)
6965 {
6966         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6967         uint16_t tmp = 0;
6968
6969         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6970
6971         cdclk_sel = (tmp >> 12) & 0x1;
6972
6973         switch (vco) {
6974         case 2666667:
6975         case 4000000:
6976         case 5333333:
6977                 return cdclk_sel ? 333333 : 222222;
6978         case 3200000:
6979                 return cdclk_sel ? 320000 : 228571;
6980         default:
6981                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6982                 return 222222;
6983         }
6984 }
6985
6986 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6987 {
6988         static const uint8_t div_3200[] = { 16, 10,  8 };
6989         static const uint8_t div_4000[] = { 20, 12, 10 };
6990         static const uint8_t div_5333[] = { 24, 16, 14 };
6991         const uint8_t *div_table;
6992         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6993         uint16_t tmp = 0;
6994
6995         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6996
6997         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6998
6999         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7000                 goto fail;
7001
7002         switch (vco) {
7003         case 3200000:
7004                 div_table = div_3200;
7005                 break;
7006         case 4000000:
7007                 div_table = div_4000;
7008                 break;
7009         case 5333333:
7010                 div_table = div_5333;
7011                 break;
7012         default:
7013                 goto fail;
7014         }
7015
7016         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7017
7018 fail:
7019         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
7020         return 200000;
7021 }
7022
7023 static int g33_get_display_clock_speed(struct drm_device *dev)
7024 {
7025         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
7026         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
7027         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
7028         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
7029         const uint8_t *div_table;
7030         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
7031         uint16_t tmp = 0;
7032
7033         pci_read_config_word(dev->pdev, GCFGC, &tmp);
7034
7035         cdclk_sel = (tmp >> 4) & 0x7;
7036
7037         if (cdclk_sel >= ARRAY_SIZE(div_3200))
7038                 goto fail;
7039
7040         switch (vco) {
7041         case 3200000:
7042                 div_table = div_3200;
7043                 break;
7044         case 4000000:
7045                 div_table = div_4000;
7046                 break;
7047         case 4800000:
7048                 div_table = div_4800;
7049                 break;
7050         case 5333333:
7051                 div_table = div_5333;
7052                 break;
7053         default:
7054                 goto fail;
7055         }
7056
7057         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
7058
7059 fail:
7060         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
7061         return 190476;
7062 }
7063
7064 static void
7065 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
7066 {
7067         while (*num > DATA_LINK_M_N_MASK ||
7068                *den > DATA_LINK_M_N_MASK) {
7069                 *num >>= 1;
7070                 *den >>= 1;
7071         }
7072 }
7073
7074 static void compute_m_n(unsigned int m, unsigned int n,
7075                         uint32_t *ret_m, uint32_t *ret_n)
7076 {
7077         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7078         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7079         intel_reduce_m_n_ratio(ret_m, ret_n);
7080 }
7081
7082 void
7083 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7084                        int pixel_clock, int link_clock,
7085                        struct intel_link_m_n *m_n)
7086 {
7087         m_n->tu = 64;
7088
7089         compute_m_n(bits_per_pixel * pixel_clock,
7090                     link_clock * nlanes * 8,
7091                     &m_n->gmch_m, &m_n->gmch_n);
7092
7093         compute_m_n(pixel_clock, link_clock,
7094                     &m_n->link_m, &m_n->link_n);
7095 }
7096
7097 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7098 {
7099         if (i915.panel_use_ssc >= 0)
7100                 return i915.panel_use_ssc != 0;
7101         return dev_priv->vbt.lvds_use_ssc
7102                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7103 }
7104
7105 static int i9xx_get_refclk(const struct intel_crtc_state *crtc_state,
7106                            int num_connectors)
7107 {
7108         struct drm_device *dev = crtc_state->base.crtc->dev;
7109         struct drm_i915_private *dev_priv = dev->dev_private;
7110         int refclk;
7111
7112         WARN_ON(!crtc_state->base.state);
7113
7114         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev) || IS_BROXTON(dev)) {
7115                 refclk = 100000;
7116         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7117             intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
7118                 refclk = dev_priv->vbt.lvds_ssc_freq;
7119                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7120         } else if (!IS_GEN2(dev)) {
7121                 refclk = 96000;
7122         } else {
7123                 refclk = 48000;
7124         }
7125
7126         return refclk;
7127 }
7128
7129 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7130 {
7131         return (1 << dpll->n) << 16 | dpll->m2;
7132 }
7133
7134 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7135 {
7136         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7137 }
7138
7139 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7140                                      struct intel_crtc_state *crtc_state,
7141                                      intel_clock_t *reduced_clock)
7142 {
7143         struct drm_device *dev = crtc->base.dev;
7144         u32 fp, fp2 = 0;
7145
7146         if (IS_PINEVIEW(dev)) {
7147                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7148                 if (reduced_clock)
7149                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7150         } else {
7151                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7152                 if (reduced_clock)
7153                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7154         }
7155
7156         crtc_state->dpll_hw_state.fp0 = fp;
7157
7158         crtc->lowfreq_avail = false;
7159         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7160             reduced_clock) {
7161                 crtc_state->dpll_hw_state.fp1 = fp2;
7162                 crtc->lowfreq_avail = true;
7163         } else {
7164                 crtc_state->dpll_hw_state.fp1 = fp;
7165         }
7166 }
7167
7168 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7169                 pipe)
7170 {
7171         u32 reg_val;
7172
7173         /*
7174          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7175          * and set it to a reasonable value instead.
7176          */
7177         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7178         reg_val &= 0xffffff00;
7179         reg_val |= 0x00000030;
7180         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7181
7182         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7183         reg_val &= 0x8cffffff;
7184         reg_val = 0x8c000000;
7185         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7186
7187         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7188         reg_val &= 0xffffff00;
7189         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7190
7191         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7192         reg_val &= 0x00ffffff;
7193         reg_val |= 0xb0000000;
7194         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7195 }
7196
7197 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7198                                          struct intel_link_m_n *m_n)
7199 {
7200         struct drm_device *dev = crtc->base.dev;
7201         struct drm_i915_private *dev_priv = dev->dev_private;
7202         int pipe = crtc->pipe;
7203
7204         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7205         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7206         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7207         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7208 }
7209
7210 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7211                                          struct intel_link_m_n *m_n,
7212                                          struct intel_link_m_n *m2_n2)
7213 {
7214         struct drm_device *dev = crtc->base.dev;
7215         struct drm_i915_private *dev_priv = dev->dev_private;
7216         int pipe = crtc->pipe;
7217         enum transcoder transcoder = crtc->config->cpu_transcoder;
7218
7219         if (INTEL_INFO(dev)->gen >= 5) {
7220                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7221                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7222                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7223                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7224                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7225                  * for gen < 8) and if DRRS is supported (to make sure the
7226                  * registers are not unnecessarily accessed).
7227                  */
7228                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7229                         crtc->config->has_drrs) {
7230                         I915_WRITE(PIPE_DATA_M2(transcoder),
7231                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7232                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7233                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7234                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7235                 }
7236         } else {
7237                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7238                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7239                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7240                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7241         }
7242 }
7243
7244 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7245 {
7246         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7247
7248         if (m_n == M1_N1) {
7249                 dp_m_n = &crtc->config->dp_m_n;
7250                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7251         } else if (m_n == M2_N2) {
7252
7253                 /*
7254                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7255                  * needs to be programmed into M1_N1.
7256                  */
7257                 dp_m_n = &crtc->config->dp_m2_n2;
7258         } else {
7259                 DRM_ERROR("Unsupported divider value\n");
7260                 return;
7261         }
7262
7263         if (crtc->config->has_pch_encoder)
7264                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7265         else
7266                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7267 }
7268
7269 static void vlv_compute_dpll(struct intel_crtc *crtc,
7270                              struct intel_crtc_state *pipe_config)
7271 {
7272         u32 dpll, dpll_md;
7273
7274         /*
7275          * Enable DPIO clock input. We should never disable the reference
7276          * clock for pipe B, since VGA hotplug / manual detection depends
7277          * on it.
7278          */
7279         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7280                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7281         /* We should never disable this, set it here for state tracking */
7282         if (crtc->pipe == PIPE_B)
7283                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7284         dpll |= DPLL_VCO_ENABLE;
7285         pipe_config->dpll_hw_state.dpll = dpll;
7286
7287         dpll_md = (pipe_config->pixel_multiplier - 1)
7288                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7289         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7290 }
7291
7292 static void vlv_prepare_pll(struct intel_crtc *crtc,
7293                             const struct intel_crtc_state *pipe_config)
7294 {
7295         struct drm_device *dev = crtc->base.dev;
7296         struct drm_i915_private *dev_priv = dev->dev_private;
7297         int pipe = crtc->pipe;
7298         u32 mdiv;
7299         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7300         u32 coreclk, reg_val;
7301
7302         mutex_lock(&dev_priv->sb_lock);
7303
7304         bestn = pipe_config->dpll.n;
7305         bestm1 = pipe_config->dpll.m1;
7306         bestm2 = pipe_config->dpll.m2;
7307         bestp1 = pipe_config->dpll.p1;
7308         bestp2 = pipe_config->dpll.p2;
7309
7310         /* See eDP HDMI DPIO driver vbios notes doc */
7311
7312         /* PLL B needs special handling */
7313         if (pipe == PIPE_B)
7314                 vlv_pllb_recal_opamp(dev_priv, pipe);
7315
7316         /* Set up Tx target for periodic Rcomp update */
7317         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7318
7319         /* Disable target IRef on PLL */
7320         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7321         reg_val &= 0x00ffffff;
7322         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7323
7324         /* Disable fast lock */
7325         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7326
7327         /* Set idtafcrecal before PLL is enabled */
7328         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7329         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7330         mdiv |= ((bestn << DPIO_N_SHIFT));
7331         mdiv |= (1 << DPIO_K_SHIFT);
7332
7333         /*
7334          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7335          * but we don't support that).
7336          * Note: don't use the DAC post divider as it seems unstable.
7337          */
7338         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7339         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7340
7341         mdiv |= DPIO_ENABLE_CALIBRATION;
7342         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7343
7344         /* Set HBR and RBR LPF coefficients */
7345         if (pipe_config->port_clock == 162000 ||
7346             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7347             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7348                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7349                                  0x009f0003);
7350         else
7351                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7352                                  0x00d0000f);
7353
7354         if (pipe_config->has_dp_encoder) {
7355                 /* Use SSC source */
7356                 if (pipe == PIPE_A)
7357                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7358                                          0x0df40000);
7359                 else
7360                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7361                                          0x0df70000);
7362         } else { /* HDMI or VGA */
7363                 /* Use bend source */
7364                 if (pipe == PIPE_A)
7365                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7366                                          0x0df70000);
7367                 else
7368                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7369                                          0x0df40000);
7370         }
7371
7372         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7373         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7374         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7375             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7376                 coreclk |= 0x01000000;
7377         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7378
7379         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7380         mutex_unlock(&dev_priv->sb_lock);
7381 }
7382
7383 static void chv_compute_dpll(struct intel_crtc *crtc,
7384                              struct intel_crtc_state *pipe_config)
7385 {
7386         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7387                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7388                 DPLL_VCO_ENABLE;
7389         if (crtc->pipe != PIPE_A)
7390                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7391
7392         pipe_config->dpll_hw_state.dpll_md =
7393                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7394 }
7395
7396 static void chv_prepare_pll(struct intel_crtc *crtc,
7397                             const struct intel_crtc_state *pipe_config)
7398 {
7399         struct drm_device *dev = crtc->base.dev;
7400         struct drm_i915_private *dev_priv = dev->dev_private;
7401         int pipe = crtc->pipe;
7402         i915_reg_t dpll_reg = DPLL(crtc->pipe);
7403         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7404         u32 loopfilter, tribuf_calcntr;
7405         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7406         u32 dpio_val;
7407         int vco;
7408
7409         bestn = pipe_config->dpll.n;
7410         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7411         bestm1 = pipe_config->dpll.m1;
7412         bestm2 = pipe_config->dpll.m2 >> 22;
7413         bestp1 = pipe_config->dpll.p1;
7414         bestp2 = pipe_config->dpll.p2;
7415         vco = pipe_config->dpll.vco;
7416         dpio_val = 0;
7417         loopfilter = 0;
7418
7419         /*
7420          * Enable Refclk and SSC
7421          */
7422         I915_WRITE(dpll_reg,
7423                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7424
7425         mutex_lock(&dev_priv->sb_lock);
7426
7427         /* p1 and p2 divider */
7428         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7429                         5 << DPIO_CHV_S1_DIV_SHIFT |
7430                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7431                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7432                         1 << DPIO_CHV_K_DIV_SHIFT);
7433
7434         /* Feedback post-divider - m2 */
7435         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7436
7437         /* Feedback refclk divider - n and m1 */
7438         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7439                         DPIO_CHV_M1_DIV_BY_2 |
7440                         1 << DPIO_CHV_N_DIV_SHIFT);
7441
7442         /* M2 fraction division */
7443         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7444
7445         /* M2 fraction division enable */
7446         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7447         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7448         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7449         if (bestm2_frac)
7450                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7451         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7452
7453         /* Program digital lock detect threshold */
7454         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7455         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7456                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7457         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7458         if (!bestm2_frac)
7459                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7460         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7461
7462         /* Loop filter */
7463         if (vco == 5400000) {
7464                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7465                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7466                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7467                 tribuf_calcntr = 0x9;
7468         } else if (vco <= 6200000) {
7469                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7470                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7471                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7472                 tribuf_calcntr = 0x9;
7473         } else if (vco <= 6480000) {
7474                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7475                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7476                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7477                 tribuf_calcntr = 0x8;
7478         } else {
7479                 /* Not supported. Apply the same limits as in the max case */
7480                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7481                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7482                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7483                 tribuf_calcntr = 0;
7484         }
7485         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7486
7487         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7488         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7489         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7490         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7491
7492         /* AFC Recal */
7493         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7494                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7495                         DPIO_AFC_RECAL);
7496
7497         mutex_unlock(&dev_priv->sb_lock);
7498 }
7499
7500 /**
7501  * vlv_force_pll_on - forcibly enable just the PLL
7502  * @dev_priv: i915 private structure
7503  * @pipe: pipe PLL to enable
7504  * @dpll: PLL configuration
7505  *
7506  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7507  * in cases where we need the PLL enabled even when @pipe is not going to
7508  * be enabled.
7509  */
7510 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7511                      const struct dpll *dpll)
7512 {
7513         struct intel_crtc *crtc =
7514                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7515         struct intel_crtc_state *pipe_config;
7516
7517         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7518         if (!pipe_config)
7519                 return -ENOMEM;
7520
7521         pipe_config->base.crtc = &crtc->base;
7522         pipe_config->pixel_multiplier = 1;
7523         pipe_config->dpll = *dpll;
7524
7525         if (IS_CHERRYVIEW(dev)) {
7526                 chv_compute_dpll(crtc, pipe_config);
7527                 chv_prepare_pll(crtc, pipe_config);
7528                 chv_enable_pll(crtc, pipe_config);
7529         } else {
7530                 vlv_compute_dpll(crtc, pipe_config);
7531                 vlv_prepare_pll(crtc, pipe_config);
7532                 vlv_enable_pll(crtc, pipe_config);
7533         }
7534
7535         kfree(pipe_config);
7536
7537         return 0;
7538 }
7539
7540 /**
7541  * vlv_force_pll_off - forcibly disable just the PLL
7542  * @dev_priv: i915 private structure
7543  * @pipe: pipe PLL to disable
7544  *
7545  * Disable the PLL for @pipe. To be used in cases where we need
7546  * the PLL enabled even when @pipe is not going to be enabled.
7547  */
7548 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7549 {
7550         if (IS_CHERRYVIEW(dev))
7551                 chv_disable_pll(to_i915(dev), pipe);
7552         else
7553                 vlv_disable_pll(to_i915(dev), pipe);
7554 }
7555
7556 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7557                               struct intel_crtc_state *crtc_state,
7558                               intel_clock_t *reduced_clock,
7559                               int num_connectors)
7560 {
7561         struct drm_device *dev = crtc->base.dev;
7562         struct drm_i915_private *dev_priv = dev->dev_private;
7563         u32 dpll;
7564         bool is_sdvo;
7565         struct dpll *clock = &crtc_state->dpll;
7566
7567         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7568
7569         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7570                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7571
7572         dpll = DPLL_VGA_MODE_DIS;
7573
7574         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7575                 dpll |= DPLLB_MODE_LVDS;
7576         else
7577                 dpll |= DPLLB_MODE_DAC_SERIAL;
7578
7579         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7580                 dpll |= (crtc_state->pixel_multiplier - 1)
7581                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7582         }
7583
7584         if (is_sdvo)
7585                 dpll |= DPLL_SDVO_HIGH_SPEED;
7586
7587         if (crtc_state->has_dp_encoder)
7588                 dpll |= DPLL_SDVO_HIGH_SPEED;
7589
7590         /* compute bitmask from p1 value */
7591         if (IS_PINEVIEW(dev))
7592                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7593         else {
7594                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7595                 if (IS_G4X(dev) && reduced_clock)
7596                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7597         }
7598         switch (clock->p2) {
7599         case 5:
7600                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7601                 break;
7602         case 7:
7603                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7604                 break;
7605         case 10:
7606                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7607                 break;
7608         case 14:
7609                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7610                 break;
7611         }
7612         if (INTEL_INFO(dev)->gen >= 4)
7613                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7614
7615         if (crtc_state->sdvo_tv_clock)
7616                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7617         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7618                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7619                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7620         else
7621                 dpll |= PLL_REF_INPUT_DREFCLK;
7622
7623         dpll |= DPLL_VCO_ENABLE;
7624         crtc_state->dpll_hw_state.dpll = dpll;
7625
7626         if (INTEL_INFO(dev)->gen >= 4) {
7627                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7628                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7629                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7630         }
7631 }
7632
7633 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7634                               struct intel_crtc_state *crtc_state,
7635                               intel_clock_t *reduced_clock,
7636                               int num_connectors)
7637 {
7638         struct drm_device *dev = crtc->base.dev;
7639         struct drm_i915_private *dev_priv = dev->dev_private;
7640         u32 dpll;
7641         struct dpll *clock = &crtc_state->dpll;
7642
7643         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7644
7645         dpll = DPLL_VGA_MODE_DIS;
7646
7647         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7648                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7649         } else {
7650                 if (clock->p1 == 2)
7651                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7652                 else
7653                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7654                 if (clock->p2 == 4)
7655                         dpll |= PLL_P2_DIVIDE_BY_4;
7656         }
7657
7658         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7659                 dpll |= DPLL_DVO_2X_MODE;
7660
7661         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7662                  intel_panel_use_ssc(dev_priv) && num_connectors < 2)
7663                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7664         else
7665                 dpll |= PLL_REF_INPUT_DREFCLK;
7666
7667         dpll |= DPLL_VCO_ENABLE;
7668         crtc_state->dpll_hw_state.dpll = dpll;
7669 }
7670
7671 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7672 {
7673         struct drm_device *dev = intel_crtc->base.dev;
7674         struct drm_i915_private *dev_priv = dev->dev_private;
7675         enum pipe pipe = intel_crtc->pipe;
7676         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7677         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7678         uint32_t crtc_vtotal, crtc_vblank_end;
7679         int vsyncshift = 0;
7680
7681         /* We need to be careful not to changed the adjusted mode, for otherwise
7682          * the hw state checker will get angry at the mismatch. */
7683         crtc_vtotal = adjusted_mode->crtc_vtotal;
7684         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7685
7686         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7687                 /* the chip adds 2 halflines automatically */
7688                 crtc_vtotal -= 1;
7689                 crtc_vblank_end -= 1;
7690
7691                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7692                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7693                 else
7694                         vsyncshift = adjusted_mode->crtc_hsync_start -
7695                                 adjusted_mode->crtc_htotal / 2;
7696                 if (vsyncshift < 0)
7697                         vsyncshift += adjusted_mode->crtc_htotal;
7698         }
7699
7700         if (INTEL_INFO(dev)->gen > 3)
7701                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7702
7703         I915_WRITE(HTOTAL(cpu_transcoder),
7704                    (adjusted_mode->crtc_hdisplay - 1) |
7705                    ((adjusted_mode->crtc_htotal - 1) << 16));
7706         I915_WRITE(HBLANK(cpu_transcoder),
7707                    (adjusted_mode->crtc_hblank_start - 1) |
7708                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7709         I915_WRITE(HSYNC(cpu_transcoder),
7710                    (adjusted_mode->crtc_hsync_start - 1) |
7711                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7712
7713         I915_WRITE(VTOTAL(cpu_transcoder),
7714                    (adjusted_mode->crtc_vdisplay - 1) |
7715                    ((crtc_vtotal - 1) << 16));
7716         I915_WRITE(VBLANK(cpu_transcoder),
7717                    (adjusted_mode->crtc_vblank_start - 1) |
7718                    ((crtc_vblank_end - 1) << 16));
7719         I915_WRITE(VSYNC(cpu_transcoder),
7720                    (adjusted_mode->crtc_vsync_start - 1) |
7721                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7722
7723         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7724          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7725          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7726          * bits. */
7727         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7728             (pipe == PIPE_B || pipe == PIPE_C))
7729                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7730
7731 }
7732
7733 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7734 {
7735         struct drm_device *dev = intel_crtc->base.dev;
7736         struct drm_i915_private *dev_priv = dev->dev_private;
7737         enum pipe pipe = intel_crtc->pipe;
7738
7739         /* pipesrc controls the size that is scaled from, which should
7740          * always be the user's requested size.
7741          */
7742         I915_WRITE(PIPESRC(pipe),
7743                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7744                    (intel_crtc->config->pipe_src_h - 1));
7745 }
7746
7747 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7748                                    struct intel_crtc_state *pipe_config)
7749 {
7750         struct drm_device *dev = crtc->base.dev;
7751         struct drm_i915_private *dev_priv = dev->dev_private;
7752         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7753         uint32_t tmp;
7754
7755         tmp = I915_READ(HTOTAL(cpu_transcoder));
7756         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7757         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7758         tmp = I915_READ(HBLANK(cpu_transcoder));
7759         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7760         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7761         tmp = I915_READ(HSYNC(cpu_transcoder));
7762         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7763         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7764
7765         tmp = I915_READ(VTOTAL(cpu_transcoder));
7766         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7767         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7768         tmp = I915_READ(VBLANK(cpu_transcoder));
7769         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7770         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7771         tmp = I915_READ(VSYNC(cpu_transcoder));
7772         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7773         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7774
7775         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7776                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7777                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7778                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7779         }
7780 }
7781
7782 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7783                                     struct intel_crtc_state *pipe_config)
7784 {
7785         struct drm_device *dev = crtc->base.dev;
7786         struct drm_i915_private *dev_priv = dev->dev_private;
7787         u32 tmp;
7788
7789         tmp = I915_READ(PIPESRC(crtc->pipe));
7790         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7791         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7792
7793         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7794         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7795 }
7796
7797 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7798                                  struct intel_crtc_state *pipe_config)
7799 {
7800         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7801         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7802         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7803         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7804
7805         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7806         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7807         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7808         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7809
7810         mode->flags = pipe_config->base.adjusted_mode.flags;
7811         mode->type = DRM_MODE_TYPE_DRIVER;
7812
7813         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7814         mode->flags |= pipe_config->base.adjusted_mode.flags;
7815
7816         mode->hsync = drm_mode_hsync(mode);
7817         mode->vrefresh = drm_mode_vrefresh(mode);
7818         drm_mode_set_name(mode);
7819 }
7820
7821 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7822 {
7823         struct drm_device *dev = intel_crtc->base.dev;
7824         struct drm_i915_private *dev_priv = dev->dev_private;
7825         uint32_t pipeconf;
7826
7827         pipeconf = 0;
7828
7829         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7830             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7831                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7832
7833         if (intel_crtc->config->double_wide)
7834                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7835
7836         /* only g4x and later have fancy bpc/dither controls */
7837         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7838                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7839                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7840                         pipeconf |= PIPECONF_DITHER_EN |
7841                                     PIPECONF_DITHER_TYPE_SP;
7842
7843                 switch (intel_crtc->config->pipe_bpp) {
7844                 case 18:
7845                         pipeconf |= PIPECONF_6BPC;
7846                         break;
7847                 case 24:
7848                         pipeconf |= PIPECONF_8BPC;
7849                         break;
7850                 case 30:
7851                         pipeconf |= PIPECONF_10BPC;
7852                         break;
7853                 default:
7854                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7855                         BUG();
7856                 }
7857         }
7858
7859         if (HAS_PIPE_CXSR(dev)) {
7860                 if (intel_crtc->lowfreq_avail) {
7861                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7862                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7863                 } else {
7864                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7865                 }
7866         }
7867
7868         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7869                 if (INTEL_INFO(dev)->gen < 4 ||
7870                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7871                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7872                 else
7873                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7874         } else
7875                 pipeconf |= PIPECONF_PROGRESSIVE;
7876
7877         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7878              intel_crtc->config->limited_color_range)
7879                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7880
7881         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7882         POSTING_READ(PIPECONF(intel_crtc->pipe));
7883 }
7884
7885 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7886                                    struct intel_crtc_state *crtc_state)
7887 {
7888         struct drm_device *dev = crtc->base.dev;
7889         struct drm_i915_private *dev_priv = dev->dev_private;
7890         int refclk, num_connectors = 0;
7891         intel_clock_t clock;
7892         bool ok;
7893         const intel_limit_t *limit;
7894         struct drm_atomic_state *state = crtc_state->base.state;
7895         struct drm_connector *connector;
7896         struct drm_connector_state *connector_state;
7897         int i;
7898
7899         memset(&crtc_state->dpll_hw_state, 0,
7900                sizeof(crtc_state->dpll_hw_state));
7901
7902         if (crtc_state->has_dsi_encoder)
7903                 return 0;
7904
7905         for_each_connector_in_state(state, connector, connector_state, i) {
7906                 if (connector_state->crtc == &crtc->base)
7907                         num_connectors++;
7908         }
7909
7910         if (!crtc_state->clock_set) {
7911                 refclk = i9xx_get_refclk(crtc_state, num_connectors);
7912
7913                 /*
7914                  * Returns a set of divisors for the desired target clock with
7915                  * the given refclk, or FALSE.  The returned values represent
7916                  * the clock equation: reflck * (5 * (m1 + 2) + (m2 + 2)) / (n +
7917                  * 2) / p1 / p2.
7918                  */
7919                 limit = intel_limit(crtc_state, refclk);
7920                 ok = dev_priv->display.find_dpll(limit, crtc_state,
7921                                                  crtc_state->port_clock,
7922                                                  refclk, NULL, &clock);
7923                 if (!ok) {
7924                         DRM_ERROR("Couldn't find PLL settings for mode!\n");
7925                         return -EINVAL;
7926                 }
7927
7928                 /* Compat-code for transition, will disappear. */
7929                 crtc_state->dpll.n = clock.n;
7930                 crtc_state->dpll.m1 = clock.m1;
7931                 crtc_state->dpll.m2 = clock.m2;
7932                 crtc_state->dpll.p1 = clock.p1;
7933                 crtc_state->dpll.p2 = clock.p2;
7934         }
7935
7936         if (IS_GEN2(dev)) {
7937                 i8xx_compute_dpll(crtc, crtc_state, NULL,
7938                                   num_connectors);
7939         } else if (IS_CHERRYVIEW(dev)) {
7940                 chv_compute_dpll(crtc, crtc_state);
7941         } else if (IS_VALLEYVIEW(dev)) {
7942                 vlv_compute_dpll(crtc, crtc_state);
7943         } else {
7944                 i9xx_compute_dpll(crtc, crtc_state, NULL,
7945                                   num_connectors);
7946         }
7947
7948         return 0;
7949 }
7950
7951 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7952                                  struct intel_crtc_state *pipe_config)
7953 {
7954         struct drm_device *dev = crtc->base.dev;
7955         struct drm_i915_private *dev_priv = dev->dev_private;
7956         uint32_t tmp;
7957
7958         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7959                 return;
7960
7961         tmp = I915_READ(PFIT_CONTROL);
7962         if (!(tmp & PFIT_ENABLE))
7963                 return;
7964
7965         /* Check whether the pfit is attached to our pipe. */
7966         if (INTEL_INFO(dev)->gen < 4) {
7967                 if (crtc->pipe != PIPE_B)
7968                         return;
7969         } else {
7970                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7971                         return;
7972         }
7973
7974         pipe_config->gmch_pfit.control = tmp;
7975         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7976         if (INTEL_INFO(dev)->gen < 5)
7977                 pipe_config->gmch_pfit.lvds_border_bits =
7978                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7979 }
7980
7981 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7982                                struct intel_crtc_state *pipe_config)
7983 {
7984         struct drm_device *dev = crtc->base.dev;
7985         struct drm_i915_private *dev_priv = dev->dev_private;
7986         int pipe = pipe_config->cpu_transcoder;
7987         intel_clock_t clock;
7988         u32 mdiv;
7989         int refclk = 100000;
7990
7991         /* In case of MIPI DPLL will not even be used */
7992         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
7993                 return;
7994
7995         mutex_lock(&dev_priv->sb_lock);
7996         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7997         mutex_unlock(&dev_priv->sb_lock);
7998
7999         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8000         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8001         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8002         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8003         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8004
8005         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8006 }
8007
8008 static void
8009 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8010                               struct intel_initial_plane_config *plane_config)
8011 {
8012         struct drm_device *dev = crtc->base.dev;
8013         struct drm_i915_private *dev_priv = dev->dev_private;
8014         u32 val, base, offset;
8015         int pipe = crtc->pipe, plane = crtc->plane;
8016         int fourcc, pixel_format;
8017         unsigned int aligned_height;
8018         struct drm_framebuffer *fb;
8019         struct intel_framebuffer *intel_fb;
8020
8021         val = I915_READ(DSPCNTR(plane));
8022         if (!(val & DISPLAY_PLANE_ENABLE))
8023                 return;
8024
8025         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8026         if (!intel_fb) {
8027                 DRM_DEBUG_KMS("failed to alloc fb\n");
8028                 return;
8029         }
8030
8031         fb = &intel_fb->base;
8032
8033         if (INTEL_INFO(dev)->gen >= 4) {
8034                 if (val & DISPPLANE_TILED) {
8035                         plane_config->tiling = I915_TILING_X;
8036                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8037                 }
8038         }
8039
8040         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8041         fourcc = i9xx_format_to_fourcc(pixel_format);
8042         fb->pixel_format = fourcc;
8043         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8044
8045         if (INTEL_INFO(dev)->gen >= 4) {
8046                 if (plane_config->tiling)
8047                         offset = I915_READ(DSPTILEOFF(plane));
8048                 else
8049                         offset = I915_READ(DSPLINOFF(plane));
8050                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8051         } else {
8052                 base = I915_READ(DSPADDR(plane));
8053         }
8054         plane_config->base = base;
8055
8056         val = I915_READ(PIPESRC(pipe));
8057         fb->width = ((val >> 16) & 0xfff) + 1;
8058         fb->height = ((val >> 0) & 0xfff) + 1;
8059
8060         val = I915_READ(DSPSTRIDE(pipe));
8061         fb->pitches[0] = val & 0xffffffc0;
8062
8063         aligned_height = intel_fb_align_height(dev, fb->height,
8064                                                fb->pixel_format,
8065                                                fb->modifier[0]);
8066
8067         plane_config->size = fb->pitches[0] * aligned_height;
8068
8069         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8070                       pipe_name(pipe), plane, fb->width, fb->height,
8071                       fb->bits_per_pixel, base, fb->pitches[0],
8072                       plane_config->size);
8073
8074         plane_config->fb = intel_fb;
8075 }
8076
8077 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8078                                struct intel_crtc_state *pipe_config)
8079 {
8080         struct drm_device *dev = crtc->base.dev;
8081         struct drm_i915_private *dev_priv = dev->dev_private;
8082         int pipe = pipe_config->cpu_transcoder;
8083         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8084         intel_clock_t clock;
8085         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8086         int refclk = 100000;
8087
8088         mutex_lock(&dev_priv->sb_lock);
8089         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8090         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8091         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8092         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8093         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8094         mutex_unlock(&dev_priv->sb_lock);
8095
8096         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8097         clock.m2 = (pll_dw0 & 0xff) << 22;
8098         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8099                 clock.m2 |= pll_dw2 & 0x3fffff;
8100         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8101         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8102         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8103
8104         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8105 }
8106
8107 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8108                                  struct intel_crtc_state *pipe_config)
8109 {
8110         struct drm_device *dev = crtc->base.dev;
8111         struct drm_i915_private *dev_priv = dev->dev_private;
8112         enum intel_display_power_domain power_domain;
8113         uint32_t tmp;
8114         bool ret;
8115
8116         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8117         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8118                 return false;
8119
8120         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8121         pipe_config->shared_dpll = NULL;
8122
8123         ret = false;
8124
8125         tmp = I915_READ(PIPECONF(crtc->pipe));
8126         if (!(tmp & PIPECONF_ENABLE))
8127                 goto out;
8128
8129         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8130                 switch (tmp & PIPECONF_BPC_MASK) {
8131                 case PIPECONF_6BPC:
8132                         pipe_config->pipe_bpp = 18;
8133                         break;
8134                 case PIPECONF_8BPC:
8135                         pipe_config->pipe_bpp = 24;
8136                         break;
8137                 case PIPECONF_10BPC:
8138                         pipe_config->pipe_bpp = 30;
8139                         break;
8140                 default:
8141                         break;
8142                 }
8143         }
8144
8145         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8146             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8147                 pipe_config->limited_color_range = true;
8148
8149         if (INTEL_INFO(dev)->gen < 4)
8150                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8151
8152         intel_get_pipe_timings(crtc, pipe_config);
8153         intel_get_pipe_src_size(crtc, pipe_config);
8154
8155         i9xx_get_pfit_config(crtc, pipe_config);
8156
8157         if (INTEL_INFO(dev)->gen >= 4) {
8158                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8159                 pipe_config->pixel_multiplier =
8160                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8161                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8162                 pipe_config->dpll_hw_state.dpll_md = tmp;
8163         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8164                 tmp = I915_READ(DPLL(crtc->pipe));
8165                 pipe_config->pixel_multiplier =
8166                         ((tmp & SDVO_MULTIPLIER_MASK)
8167                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8168         } else {
8169                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8170                  * port and will be fixed up in the encoder->get_config
8171                  * function. */
8172                 pipe_config->pixel_multiplier = 1;
8173         }
8174         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8175         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8176                 /*
8177                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8178                  * on 830. Filter it out here so that we don't
8179                  * report errors due to that.
8180                  */
8181                 if (IS_I830(dev))
8182                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8183
8184                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8185                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8186         } else {
8187                 /* Mask out read-only status bits. */
8188                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8189                                                      DPLL_PORTC_READY_MASK |
8190                                                      DPLL_PORTB_READY_MASK);
8191         }
8192
8193         if (IS_CHERRYVIEW(dev))
8194                 chv_crtc_clock_get(crtc, pipe_config);
8195         else if (IS_VALLEYVIEW(dev))
8196                 vlv_crtc_clock_get(crtc, pipe_config);
8197         else
8198                 i9xx_crtc_clock_get(crtc, pipe_config);
8199
8200         /*
8201          * Normally the dotclock is filled in by the encoder .get_config()
8202          * but in case the pipe is enabled w/o any ports we need a sane
8203          * default.
8204          */
8205         pipe_config->base.adjusted_mode.crtc_clock =
8206                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8207
8208         ret = true;
8209
8210 out:
8211         intel_display_power_put(dev_priv, power_domain);
8212
8213         return ret;
8214 }
8215
8216 static void ironlake_init_pch_refclk(struct drm_device *dev)
8217 {
8218         struct drm_i915_private *dev_priv = dev->dev_private;
8219         struct intel_encoder *encoder;
8220         u32 val, final;
8221         bool has_lvds = false;
8222         bool has_cpu_edp = false;
8223         bool has_panel = false;
8224         bool has_ck505 = false;
8225         bool can_ssc = false;
8226
8227         /* We need to take the global config into account */
8228         for_each_intel_encoder(dev, encoder) {
8229                 switch (encoder->type) {
8230                 case INTEL_OUTPUT_LVDS:
8231                         has_panel = true;
8232                         has_lvds = true;
8233                         break;
8234                 case INTEL_OUTPUT_EDP:
8235                         has_panel = true;
8236                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8237                                 has_cpu_edp = true;
8238                         break;
8239                 default:
8240                         break;
8241                 }
8242         }
8243
8244         if (HAS_PCH_IBX(dev)) {
8245                 has_ck505 = dev_priv->vbt.display_clock_mode;
8246                 can_ssc = has_ck505;
8247         } else {
8248                 has_ck505 = false;
8249                 can_ssc = true;
8250         }
8251
8252         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8253                       has_panel, has_lvds, has_ck505);
8254
8255         /* Ironlake: try to setup display ref clock before DPLL
8256          * enabling. This is only under driver's control after
8257          * PCH B stepping, previous chipset stepping should be
8258          * ignoring this setting.
8259          */
8260         val = I915_READ(PCH_DREF_CONTROL);
8261
8262         /* As we must carefully and slowly disable/enable each source in turn,
8263          * compute the final state we want first and check if we need to
8264          * make any changes at all.
8265          */
8266         final = val;
8267         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8268         if (has_ck505)
8269                 final |= DREF_NONSPREAD_CK505_ENABLE;
8270         else
8271                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8272
8273         final &= ~DREF_SSC_SOURCE_MASK;
8274         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8275         final &= ~DREF_SSC1_ENABLE;
8276
8277         if (has_panel) {
8278                 final |= DREF_SSC_SOURCE_ENABLE;
8279
8280                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8281                         final |= DREF_SSC1_ENABLE;
8282
8283                 if (has_cpu_edp) {
8284                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8285                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8286                         else
8287                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8288                 } else
8289                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8290         } else {
8291                 final |= DREF_SSC_SOURCE_DISABLE;
8292                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8293         }
8294
8295         if (final == val)
8296                 return;
8297
8298         /* Always enable nonspread source */
8299         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8300
8301         if (has_ck505)
8302                 val |= DREF_NONSPREAD_CK505_ENABLE;
8303         else
8304                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8305
8306         if (has_panel) {
8307                 val &= ~DREF_SSC_SOURCE_MASK;
8308                 val |= DREF_SSC_SOURCE_ENABLE;
8309
8310                 /* SSC must be turned on before enabling the CPU output  */
8311                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8312                         DRM_DEBUG_KMS("Using SSC on panel\n");
8313                         val |= DREF_SSC1_ENABLE;
8314                 } else
8315                         val &= ~DREF_SSC1_ENABLE;
8316
8317                 /* Get SSC going before enabling the outputs */
8318                 I915_WRITE(PCH_DREF_CONTROL, val);
8319                 POSTING_READ(PCH_DREF_CONTROL);
8320                 udelay(200);
8321
8322                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8323
8324                 /* Enable CPU source on CPU attached eDP */
8325                 if (has_cpu_edp) {
8326                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8327                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8328                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8329                         } else
8330                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8331                 } else
8332                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8333
8334                 I915_WRITE(PCH_DREF_CONTROL, val);
8335                 POSTING_READ(PCH_DREF_CONTROL);
8336                 udelay(200);
8337         } else {
8338                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8339
8340                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8341
8342                 /* Turn off CPU output */
8343                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8344
8345                 I915_WRITE(PCH_DREF_CONTROL, val);
8346                 POSTING_READ(PCH_DREF_CONTROL);
8347                 udelay(200);
8348
8349                 /* Turn off the SSC source */
8350                 val &= ~DREF_SSC_SOURCE_MASK;
8351                 val |= DREF_SSC_SOURCE_DISABLE;
8352
8353                 /* Turn off SSC1 */
8354                 val &= ~DREF_SSC1_ENABLE;
8355
8356                 I915_WRITE(PCH_DREF_CONTROL, val);
8357                 POSTING_READ(PCH_DREF_CONTROL);
8358                 udelay(200);
8359         }
8360
8361         BUG_ON(val != final);
8362 }
8363
8364 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8365 {
8366         uint32_t tmp;
8367
8368         tmp = I915_READ(SOUTH_CHICKEN2);
8369         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8370         I915_WRITE(SOUTH_CHICKEN2, tmp);
8371
8372         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8373                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8374                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8375
8376         tmp = I915_READ(SOUTH_CHICKEN2);
8377         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8378         I915_WRITE(SOUTH_CHICKEN2, tmp);
8379
8380         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8381                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8382                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8383 }
8384
8385 /* WaMPhyProgramming:hsw */
8386 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8387 {
8388         uint32_t tmp;
8389
8390         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8391         tmp &= ~(0xFF << 24);
8392         tmp |= (0x12 << 24);
8393         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8394
8395         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8396         tmp |= (1 << 11);
8397         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8398
8399         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8400         tmp |= (1 << 11);
8401         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8402
8403         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8404         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8405         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8406
8407         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8408         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8409         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8410
8411         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8412         tmp &= ~(7 << 13);
8413         tmp |= (5 << 13);
8414         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8415
8416         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8417         tmp &= ~(7 << 13);
8418         tmp |= (5 << 13);
8419         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8420
8421         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8422         tmp &= ~0xFF;
8423         tmp |= 0x1C;
8424         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8425
8426         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8427         tmp &= ~0xFF;
8428         tmp |= 0x1C;
8429         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8430
8431         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8432         tmp &= ~(0xFF << 16);
8433         tmp |= (0x1C << 16);
8434         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8435
8436         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8437         tmp &= ~(0xFF << 16);
8438         tmp |= (0x1C << 16);
8439         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8440
8441         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8442         tmp |= (1 << 27);
8443         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8444
8445         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8446         tmp |= (1 << 27);
8447         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8448
8449         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8450         tmp &= ~(0xF << 28);
8451         tmp |= (4 << 28);
8452         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8453
8454         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8455         tmp &= ~(0xF << 28);
8456         tmp |= (4 << 28);
8457         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8458 }
8459
8460 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8461  * Programming" based on the parameters passed:
8462  * - Sequence to enable CLKOUT_DP
8463  * - Sequence to enable CLKOUT_DP without spread
8464  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8465  */
8466 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8467                                  bool with_fdi)
8468 {
8469         struct drm_i915_private *dev_priv = dev->dev_private;
8470         uint32_t reg, tmp;
8471
8472         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8473                 with_spread = true;
8474         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8475                 with_fdi = false;
8476
8477         mutex_lock(&dev_priv->sb_lock);
8478
8479         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8480         tmp &= ~SBI_SSCCTL_DISABLE;
8481         tmp |= SBI_SSCCTL_PATHALT;
8482         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8483
8484         udelay(24);
8485
8486         if (with_spread) {
8487                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8488                 tmp &= ~SBI_SSCCTL_PATHALT;
8489                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8490
8491                 if (with_fdi) {
8492                         lpt_reset_fdi_mphy(dev_priv);
8493                         lpt_program_fdi_mphy(dev_priv);
8494                 }
8495         }
8496
8497         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8498         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8499         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8500         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8501
8502         mutex_unlock(&dev_priv->sb_lock);
8503 }
8504
8505 /* Sequence to disable CLKOUT_DP */
8506 static void lpt_disable_clkout_dp(struct drm_device *dev)
8507 {
8508         struct drm_i915_private *dev_priv = dev->dev_private;
8509         uint32_t reg, tmp;
8510
8511         mutex_lock(&dev_priv->sb_lock);
8512
8513         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8514         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8515         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8516         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8517
8518         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8519         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8520                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8521                         tmp |= SBI_SSCCTL_PATHALT;
8522                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8523                         udelay(32);
8524                 }
8525                 tmp |= SBI_SSCCTL_DISABLE;
8526                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8527         }
8528
8529         mutex_unlock(&dev_priv->sb_lock);
8530 }
8531
8532 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8533
8534 static const uint16_t sscdivintphase[] = {
8535         [BEND_IDX( 50)] = 0x3B23,
8536         [BEND_IDX( 45)] = 0x3B23,
8537         [BEND_IDX( 40)] = 0x3C23,
8538         [BEND_IDX( 35)] = 0x3C23,
8539         [BEND_IDX( 30)] = 0x3D23,
8540         [BEND_IDX( 25)] = 0x3D23,
8541         [BEND_IDX( 20)] = 0x3E23,
8542         [BEND_IDX( 15)] = 0x3E23,
8543         [BEND_IDX( 10)] = 0x3F23,
8544         [BEND_IDX(  5)] = 0x3F23,
8545         [BEND_IDX(  0)] = 0x0025,
8546         [BEND_IDX( -5)] = 0x0025,
8547         [BEND_IDX(-10)] = 0x0125,
8548         [BEND_IDX(-15)] = 0x0125,
8549         [BEND_IDX(-20)] = 0x0225,
8550         [BEND_IDX(-25)] = 0x0225,
8551         [BEND_IDX(-30)] = 0x0325,
8552         [BEND_IDX(-35)] = 0x0325,
8553         [BEND_IDX(-40)] = 0x0425,
8554         [BEND_IDX(-45)] = 0x0425,
8555         [BEND_IDX(-50)] = 0x0525,
8556 };
8557
8558 /*
8559  * Bend CLKOUT_DP
8560  * steps -50 to 50 inclusive, in steps of 5
8561  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8562  * change in clock period = -(steps / 10) * 5.787 ps
8563  */
8564 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8565 {
8566         uint32_t tmp;
8567         int idx = BEND_IDX(steps);
8568
8569         if (WARN_ON(steps % 5 != 0))
8570                 return;
8571
8572         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8573                 return;
8574
8575         mutex_lock(&dev_priv->sb_lock);
8576
8577         if (steps % 10 != 0)
8578                 tmp = 0xAAAAAAAB;
8579         else
8580                 tmp = 0x00000000;
8581         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8582
8583         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8584         tmp &= 0xffff0000;
8585         tmp |= sscdivintphase[idx];
8586         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8587
8588         mutex_unlock(&dev_priv->sb_lock);
8589 }
8590
8591 #undef BEND_IDX
8592
8593 static void lpt_init_pch_refclk(struct drm_device *dev)
8594 {
8595         struct intel_encoder *encoder;
8596         bool has_vga = false;
8597
8598         for_each_intel_encoder(dev, encoder) {
8599                 switch (encoder->type) {
8600                 case INTEL_OUTPUT_ANALOG:
8601                         has_vga = true;
8602                         break;
8603                 default:
8604                         break;
8605                 }
8606         }
8607
8608         if (has_vga) {
8609                 lpt_bend_clkout_dp(to_i915(dev), 0);
8610                 lpt_enable_clkout_dp(dev, true, true);
8611         } else {
8612                 lpt_disable_clkout_dp(dev);
8613         }
8614 }
8615
8616 /*
8617  * Initialize reference clocks when the driver loads
8618  */
8619 void intel_init_pch_refclk(struct drm_device *dev)
8620 {
8621         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8622                 ironlake_init_pch_refclk(dev);
8623         else if (HAS_PCH_LPT(dev))
8624                 lpt_init_pch_refclk(dev);
8625 }
8626
8627 static int ironlake_get_refclk(struct intel_crtc_state *crtc_state)
8628 {
8629         struct drm_device *dev = crtc_state->base.crtc->dev;
8630         struct drm_i915_private *dev_priv = dev->dev_private;
8631         struct drm_atomic_state *state = crtc_state->base.state;
8632         struct drm_connector *connector;
8633         struct drm_connector_state *connector_state;
8634         struct intel_encoder *encoder;
8635         int num_connectors = 0, i;
8636         bool is_lvds = false;
8637
8638         for_each_connector_in_state(state, connector, connector_state, i) {
8639                 if (connector_state->crtc != crtc_state->base.crtc)
8640                         continue;
8641
8642                 encoder = to_intel_encoder(connector_state->best_encoder);
8643
8644                 switch (encoder->type) {
8645                 case INTEL_OUTPUT_LVDS:
8646                         is_lvds = true;
8647                         break;
8648                 default:
8649                         break;
8650                 }
8651                 num_connectors++;
8652         }
8653
8654         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2) {
8655                 DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8656                               dev_priv->vbt.lvds_ssc_freq);
8657                 return dev_priv->vbt.lvds_ssc_freq;
8658         }
8659
8660         return 120000;
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 /*
8706  * Set up the pipe CSC unit.
8707  *
8708  * Currently only full range RGB to limited range RGB conversion
8709  * is supported, but eventually this should handle various
8710  * RGB<->YCbCr scenarios as well.
8711  */
8712 static void intel_set_pipe_csc(struct drm_crtc *crtc)
8713 {
8714         struct drm_device *dev = crtc->dev;
8715         struct drm_i915_private *dev_priv = dev->dev_private;
8716         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8717         int pipe = intel_crtc->pipe;
8718         uint16_t coeff = 0x7800; /* 1.0 */
8719
8720         /*
8721          * TODO: Check what kind of values actually come out of the pipe
8722          * with these coeff/postoff values and adjust to get the best
8723          * accuracy. Perhaps we even need to take the bpc value into
8724          * consideration.
8725          */
8726
8727         if (intel_crtc->config->limited_color_range)
8728                 coeff = ((235 - 16) * (1 << 12) / 255) & 0xff8; /* 0.xxx... */
8729
8730         /*
8731          * GY/GU and RY/RU should be the other way around according
8732          * to BSpec, but reality doesn't agree. Just set them up in
8733          * a way that results in the correct picture.
8734          */
8735         I915_WRITE(PIPE_CSC_COEFF_RY_GY(pipe), coeff << 16);
8736         I915_WRITE(PIPE_CSC_COEFF_BY(pipe), 0);
8737
8738         I915_WRITE(PIPE_CSC_COEFF_RU_GU(pipe), coeff);
8739         I915_WRITE(PIPE_CSC_COEFF_BU(pipe), 0);
8740
8741         I915_WRITE(PIPE_CSC_COEFF_RV_GV(pipe), 0);
8742         I915_WRITE(PIPE_CSC_COEFF_BV(pipe), coeff << 16);
8743
8744         I915_WRITE(PIPE_CSC_PREOFF_HI(pipe), 0);
8745         I915_WRITE(PIPE_CSC_PREOFF_ME(pipe), 0);
8746         I915_WRITE(PIPE_CSC_PREOFF_LO(pipe), 0);
8747
8748         if (INTEL_INFO(dev)->gen > 6) {
8749                 uint16_t postoff = 0;
8750
8751                 if (intel_crtc->config->limited_color_range)
8752                         postoff = (16 * (1 << 12) / 255) & 0x1fff;
8753
8754                 I915_WRITE(PIPE_CSC_POSTOFF_HI(pipe), postoff);
8755                 I915_WRITE(PIPE_CSC_POSTOFF_ME(pipe), postoff);
8756                 I915_WRITE(PIPE_CSC_POSTOFF_LO(pipe), postoff);
8757
8758                 I915_WRITE(PIPE_CSC_MODE(pipe), 0);
8759         } else {
8760                 uint32_t mode = CSC_MODE_YUV_TO_RGB;
8761
8762                 if (intel_crtc->config->limited_color_range)
8763                         mode |= CSC_BLACK_SCREEN_OFFSET;
8764
8765                 I915_WRITE(PIPE_CSC_MODE(pipe), mode);
8766         }
8767 }
8768
8769 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8770 {
8771         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8772         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8773         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8774         u32 val = 0;
8775
8776         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8777                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8778
8779         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8780                 val |= PIPECONF_INTERLACED_ILK;
8781         else
8782                 val |= PIPECONF_PROGRESSIVE;
8783
8784         I915_WRITE(PIPECONF(cpu_transcoder), val);
8785         POSTING_READ(PIPECONF(cpu_transcoder));
8786 }
8787
8788 static void haswell_set_pipe_gamma(struct drm_crtc *crtc)
8789 {
8790         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8791         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8792
8793         I915_WRITE(GAMMA_MODE(intel_crtc->pipe), GAMMA_MODE_MODE_8BIT);
8794         POSTING_READ(GAMMA_MODE(intel_crtc->pipe));
8795 }
8796
8797 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8798 {
8799         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8800         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8801
8802         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8803                 u32 val = 0;
8804
8805                 switch (intel_crtc->config->pipe_bpp) {
8806                 case 18:
8807                         val |= PIPEMISC_DITHER_6_BPC;
8808                         break;
8809                 case 24:
8810                         val |= PIPEMISC_DITHER_8_BPC;
8811                         break;
8812                 case 30:
8813                         val |= PIPEMISC_DITHER_10_BPC;
8814                         break;
8815                 case 36:
8816                         val |= PIPEMISC_DITHER_12_BPC;
8817                         break;
8818                 default:
8819                         /* Case prevented by pipe_config_set_bpp. */
8820                         BUG();
8821                 }
8822
8823                 if (intel_crtc->config->dither)
8824                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8825
8826                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8827         }
8828 }
8829
8830 static bool ironlake_compute_clocks(struct drm_crtc *crtc,
8831                                     struct intel_crtc_state *crtc_state,
8832                                     intel_clock_t *clock,
8833                                     bool *has_reduced_clock,
8834                                     intel_clock_t *reduced_clock)
8835 {
8836         struct drm_device *dev = crtc->dev;
8837         struct drm_i915_private *dev_priv = dev->dev_private;
8838         int refclk;
8839         const intel_limit_t *limit;
8840         bool ret;
8841
8842         refclk = ironlake_get_refclk(crtc_state);
8843
8844         /*
8845          * Returns a set of divisors for the desired target clock with the given
8846          * refclk, or FALSE.  The returned values represent the clock equation:
8847          * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
8848          */
8849         limit = intel_limit(crtc_state, refclk);
8850         ret = dev_priv->display.find_dpll(limit, crtc_state,
8851                                           crtc_state->port_clock,
8852                                           refclk, NULL, clock);
8853         if (!ret)
8854                 return false;
8855
8856         return true;
8857 }
8858
8859 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8860 {
8861         /*
8862          * Account for spread spectrum to avoid
8863          * oversubscribing the link. Max center spread
8864          * is 2.5%; use 5% for safety's sake.
8865          */
8866         u32 bps = target_clock * bpp * 21 / 20;
8867         return DIV_ROUND_UP(bps, link_bw * 8);
8868 }
8869
8870 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8871 {
8872         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8873 }
8874
8875 static uint32_t ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8876                                       struct intel_crtc_state *crtc_state,
8877                                       u32 *fp,
8878                                       intel_clock_t *reduced_clock, u32 *fp2)
8879 {
8880         struct drm_crtc *crtc = &intel_crtc->base;
8881         struct drm_device *dev = crtc->dev;
8882         struct drm_i915_private *dev_priv = dev->dev_private;
8883         struct drm_atomic_state *state = crtc_state->base.state;
8884         struct drm_connector *connector;
8885         struct drm_connector_state *connector_state;
8886         struct intel_encoder *encoder;
8887         uint32_t dpll;
8888         int factor, num_connectors = 0, i;
8889         bool is_lvds = false, is_sdvo = false;
8890
8891         for_each_connector_in_state(state, connector, connector_state, i) {
8892                 if (connector_state->crtc != crtc_state->base.crtc)
8893                         continue;
8894
8895                 encoder = to_intel_encoder(connector_state->best_encoder);
8896
8897                 switch (encoder->type) {
8898                 case INTEL_OUTPUT_LVDS:
8899                         is_lvds = true;
8900                         break;
8901                 case INTEL_OUTPUT_SDVO:
8902                 case INTEL_OUTPUT_HDMI:
8903                         is_sdvo = true;
8904                         break;
8905                 default:
8906                         break;
8907                 }
8908
8909                 num_connectors++;
8910         }
8911
8912         /* Enable autotuning of the PLL clock (if permissible) */
8913         factor = 21;
8914         if (is_lvds) {
8915                 if ((intel_panel_use_ssc(dev_priv) &&
8916                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8917                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8918                         factor = 25;
8919         } else if (crtc_state->sdvo_tv_clock)
8920                 factor = 20;
8921
8922         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8923                 *fp |= FP_CB_TUNE;
8924
8925         if (fp2 && (reduced_clock->m < factor * reduced_clock->n))
8926                 *fp2 |= FP_CB_TUNE;
8927
8928         dpll = 0;
8929
8930         if (is_lvds)
8931                 dpll |= DPLLB_MODE_LVDS;
8932         else
8933                 dpll |= DPLLB_MODE_DAC_SERIAL;
8934
8935         dpll |= (crtc_state->pixel_multiplier - 1)
8936                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8937
8938         if (is_sdvo)
8939                 dpll |= DPLL_SDVO_HIGH_SPEED;
8940         if (crtc_state->has_dp_encoder)
8941                 dpll |= DPLL_SDVO_HIGH_SPEED;
8942
8943         /* compute bitmask from p1 value */
8944         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8945         /* also FPA1 */
8946         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8947
8948         switch (crtc_state->dpll.p2) {
8949         case 5:
8950                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8951                 break;
8952         case 7:
8953                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8954                 break;
8955         case 10:
8956                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8957                 break;
8958         case 14:
8959                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8960                 break;
8961         }
8962
8963         if (is_lvds && intel_panel_use_ssc(dev_priv) && num_connectors < 2)
8964                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8965         else
8966                 dpll |= PLL_REF_INPUT_DREFCLK;
8967
8968         return dpll | DPLL_VCO_ENABLE;
8969 }
8970
8971 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8972                                        struct intel_crtc_state *crtc_state)
8973 {
8974         struct drm_device *dev = crtc->base.dev;
8975         intel_clock_t clock, reduced_clock;
8976         u32 dpll = 0, fp = 0, fp2 = 0;
8977         bool ok, has_reduced_clock = false;
8978         bool is_lvds = false;
8979         struct intel_shared_dpll *pll;
8980
8981         memset(&crtc_state->dpll_hw_state, 0,
8982                sizeof(crtc_state->dpll_hw_state));
8983
8984         is_lvds = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS);
8985
8986         WARN(!(HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)),
8987              "Unexpected PCH type %d\n", INTEL_PCH_TYPE(dev));
8988
8989         ok = ironlake_compute_clocks(&crtc->base, crtc_state, &clock,
8990                                      &has_reduced_clock, &reduced_clock);
8991         if (!ok && !crtc_state->clock_set) {
8992                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8993                 return -EINVAL;
8994         }
8995         /* Compat-code for transition, will disappear. */
8996         if (!crtc_state->clock_set) {
8997                 crtc_state->dpll.n = clock.n;
8998                 crtc_state->dpll.m1 = clock.m1;
8999                 crtc_state->dpll.m2 = clock.m2;
9000                 crtc_state->dpll.p1 = clock.p1;
9001                 crtc_state->dpll.p2 = clock.p2;
9002         }
9003
9004         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
9005         if (crtc_state->has_pch_encoder) {
9006                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
9007                 if (has_reduced_clock)
9008                         fp2 = i9xx_dpll_compute_fp(&reduced_clock);
9009
9010                 dpll = ironlake_compute_dpll(crtc, crtc_state,
9011                                              &fp, &reduced_clock,
9012                                              has_reduced_clock ? &fp2 : NULL);
9013
9014                 crtc_state->dpll_hw_state.dpll = dpll;
9015                 crtc_state->dpll_hw_state.fp0 = fp;
9016                 if (has_reduced_clock)
9017                         crtc_state->dpll_hw_state.fp1 = fp2;
9018                 else
9019                         crtc_state->dpll_hw_state.fp1 = fp;
9020
9021                 pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
9022                 if (pll == NULL) {
9023                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9024                                          pipe_name(crtc->pipe));
9025                         return -EINVAL;
9026                 }
9027         }
9028
9029         if (is_lvds && has_reduced_clock)
9030                 crtc->lowfreq_avail = true;
9031         else
9032                 crtc->lowfreq_avail = false;
9033
9034         return 0;
9035 }
9036
9037 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
9038                                          struct intel_link_m_n *m_n)
9039 {
9040         struct drm_device *dev = crtc->base.dev;
9041         struct drm_i915_private *dev_priv = dev->dev_private;
9042         enum pipe pipe = crtc->pipe;
9043
9044         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
9045         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
9046         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
9047                 & ~TU_SIZE_MASK;
9048         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
9049         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
9050                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9051 }
9052
9053 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
9054                                          enum transcoder transcoder,
9055                                          struct intel_link_m_n *m_n,
9056                                          struct intel_link_m_n *m2_n2)
9057 {
9058         struct drm_device *dev = crtc->base.dev;
9059         struct drm_i915_private *dev_priv = dev->dev_private;
9060         enum pipe pipe = crtc->pipe;
9061
9062         if (INTEL_INFO(dev)->gen >= 5) {
9063                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
9064                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
9065                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
9066                         & ~TU_SIZE_MASK;
9067                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
9068                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
9069                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9070                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
9071                  * gen < 8) and if DRRS is supported (to make sure the
9072                  * registers are not unnecessarily read).
9073                  */
9074                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
9075                         crtc->config->has_drrs) {
9076                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
9077                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
9078                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
9079                                         & ~TU_SIZE_MASK;
9080                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
9081                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
9082                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9083                 }
9084         } else {
9085                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
9086                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
9087                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
9088                         & ~TU_SIZE_MASK;
9089                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
9090                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
9091                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
9092         }
9093 }
9094
9095 void intel_dp_get_m_n(struct intel_crtc *crtc,
9096                       struct intel_crtc_state *pipe_config)
9097 {
9098         if (pipe_config->has_pch_encoder)
9099                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
9100         else
9101                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9102                                              &pipe_config->dp_m_n,
9103                                              &pipe_config->dp_m2_n2);
9104 }
9105
9106 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9107                                         struct intel_crtc_state *pipe_config)
9108 {
9109         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9110                                      &pipe_config->fdi_m_n, NULL);
9111 }
9112
9113 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9114                                     struct intel_crtc_state *pipe_config)
9115 {
9116         struct drm_device *dev = crtc->base.dev;
9117         struct drm_i915_private *dev_priv = dev->dev_private;
9118         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9119         uint32_t ps_ctrl = 0;
9120         int id = -1;
9121         int i;
9122
9123         /* find scaler attached to this pipe */
9124         for (i = 0; i < crtc->num_scalers; i++) {
9125                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9126                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9127                         id = i;
9128                         pipe_config->pch_pfit.enabled = true;
9129                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9130                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9131                         break;
9132                 }
9133         }
9134
9135         scaler_state->scaler_id = id;
9136         if (id >= 0) {
9137                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9138         } else {
9139                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9140         }
9141 }
9142
9143 static void
9144 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9145                                  struct intel_initial_plane_config *plane_config)
9146 {
9147         struct drm_device *dev = crtc->base.dev;
9148         struct drm_i915_private *dev_priv = dev->dev_private;
9149         u32 val, base, offset, stride_mult, tiling;
9150         int pipe = crtc->pipe;
9151         int fourcc, pixel_format;
9152         unsigned int aligned_height;
9153         struct drm_framebuffer *fb;
9154         struct intel_framebuffer *intel_fb;
9155
9156         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9157         if (!intel_fb) {
9158                 DRM_DEBUG_KMS("failed to alloc fb\n");
9159                 return;
9160         }
9161
9162         fb = &intel_fb->base;
9163
9164         val = I915_READ(PLANE_CTL(pipe, 0));
9165         if (!(val & PLANE_CTL_ENABLE))
9166                 goto error;
9167
9168         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9169         fourcc = skl_format_to_fourcc(pixel_format,
9170                                       val & PLANE_CTL_ORDER_RGBX,
9171                                       val & PLANE_CTL_ALPHA_MASK);
9172         fb->pixel_format = fourcc;
9173         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9174
9175         tiling = val & PLANE_CTL_TILED_MASK;
9176         switch (tiling) {
9177         case PLANE_CTL_TILED_LINEAR:
9178                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9179                 break;
9180         case PLANE_CTL_TILED_X:
9181                 plane_config->tiling = I915_TILING_X;
9182                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9183                 break;
9184         case PLANE_CTL_TILED_Y:
9185                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9186                 break;
9187         case PLANE_CTL_TILED_YF:
9188                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9189                 break;
9190         default:
9191                 MISSING_CASE(tiling);
9192                 goto error;
9193         }
9194
9195         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9196         plane_config->base = base;
9197
9198         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9199
9200         val = I915_READ(PLANE_SIZE(pipe, 0));
9201         fb->height = ((val >> 16) & 0xfff) + 1;
9202         fb->width = ((val >> 0) & 0x1fff) + 1;
9203
9204         val = I915_READ(PLANE_STRIDE(pipe, 0));
9205         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9206                                                 fb->pixel_format);
9207         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9208
9209         aligned_height = intel_fb_align_height(dev, fb->height,
9210                                                fb->pixel_format,
9211                                                fb->modifier[0]);
9212
9213         plane_config->size = fb->pitches[0] * aligned_height;
9214
9215         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9216                       pipe_name(pipe), fb->width, fb->height,
9217                       fb->bits_per_pixel, base, fb->pitches[0],
9218                       plane_config->size);
9219
9220         plane_config->fb = intel_fb;
9221         return;
9222
9223 error:
9224         kfree(fb);
9225 }
9226
9227 static void ironlake_get_pfit_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         uint32_t tmp;
9233
9234         tmp = I915_READ(PF_CTL(crtc->pipe));
9235
9236         if (tmp & PF_ENABLE) {
9237                 pipe_config->pch_pfit.enabled = true;
9238                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9239                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9240
9241                 /* We currently do not free assignements of panel fitters on
9242                  * ivb/hsw (since we don't use the higher upscaling modes which
9243                  * differentiates them) so just WARN about this case for now. */
9244                 if (IS_GEN7(dev)) {
9245                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9246                                 PF_PIPE_SEL_IVB(crtc->pipe));
9247                 }
9248         }
9249 }
9250
9251 static void
9252 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9253                                   struct intel_initial_plane_config *plane_config)
9254 {
9255         struct drm_device *dev = crtc->base.dev;
9256         struct drm_i915_private *dev_priv = dev->dev_private;
9257         u32 val, base, offset;
9258         int pipe = crtc->pipe;
9259         int fourcc, pixel_format;
9260         unsigned int aligned_height;
9261         struct drm_framebuffer *fb;
9262         struct intel_framebuffer *intel_fb;
9263
9264         val = I915_READ(DSPCNTR(pipe));
9265         if (!(val & DISPLAY_PLANE_ENABLE))
9266                 return;
9267
9268         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9269         if (!intel_fb) {
9270                 DRM_DEBUG_KMS("failed to alloc fb\n");
9271                 return;
9272         }
9273
9274         fb = &intel_fb->base;
9275
9276         if (INTEL_INFO(dev)->gen >= 4) {
9277                 if (val & DISPPLANE_TILED) {
9278                         plane_config->tiling = I915_TILING_X;
9279                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9280                 }
9281         }
9282
9283         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9284         fourcc = i9xx_format_to_fourcc(pixel_format);
9285         fb->pixel_format = fourcc;
9286         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9287
9288         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9289         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9290                 offset = I915_READ(DSPOFFSET(pipe));
9291         } else {
9292                 if (plane_config->tiling)
9293                         offset = I915_READ(DSPTILEOFF(pipe));
9294                 else
9295                         offset = I915_READ(DSPLINOFF(pipe));
9296         }
9297         plane_config->base = base;
9298
9299         val = I915_READ(PIPESRC(pipe));
9300         fb->width = ((val >> 16) & 0xfff) + 1;
9301         fb->height = ((val >> 0) & 0xfff) + 1;
9302
9303         val = I915_READ(DSPSTRIDE(pipe));
9304         fb->pitches[0] = val & 0xffffffc0;
9305
9306         aligned_height = intel_fb_align_height(dev, fb->height,
9307                                                fb->pixel_format,
9308                                                fb->modifier[0]);
9309
9310         plane_config->size = fb->pitches[0] * aligned_height;
9311
9312         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9313                       pipe_name(pipe), fb->width, fb->height,
9314                       fb->bits_per_pixel, base, fb->pitches[0],
9315                       plane_config->size);
9316
9317         plane_config->fb = intel_fb;
9318 }
9319
9320 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9321                                      struct intel_crtc_state *pipe_config)
9322 {
9323         struct drm_device *dev = crtc->base.dev;
9324         struct drm_i915_private *dev_priv = dev->dev_private;
9325         enum intel_display_power_domain power_domain;
9326         uint32_t tmp;
9327         bool ret;
9328
9329         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9330         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9331                 return false;
9332
9333         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9334         pipe_config->shared_dpll = NULL;
9335
9336         ret = false;
9337         tmp = I915_READ(PIPECONF(crtc->pipe));
9338         if (!(tmp & PIPECONF_ENABLE))
9339                 goto out;
9340
9341         switch (tmp & PIPECONF_BPC_MASK) {
9342         case PIPECONF_6BPC:
9343                 pipe_config->pipe_bpp = 18;
9344                 break;
9345         case PIPECONF_8BPC:
9346                 pipe_config->pipe_bpp = 24;
9347                 break;
9348         case PIPECONF_10BPC:
9349                 pipe_config->pipe_bpp = 30;
9350                 break;
9351         case PIPECONF_12BPC:
9352                 pipe_config->pipe_bpp = 36;
9353                 break;
9354         default:
9355                 break;
9356         }
9357
9358         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9359                 pipe_config->limited_color_range = true;
9360
9361         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9362                 struct intel_shared_dpll *pll;
9363                 enum intel_dpll_id pll_id;
9364
9365                 pipe_config->has_pch_encoder = true;
9366
9367                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9368                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9369                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9370
9371                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9372
9373                 if (HAS_PCH_IBX(dev_priv->dev)) {
9374                         pll_id = (enum intel_dpll_id) crtc->pipe;
9375                 } else {
9376                         tmp = I915_READ(PCH_DPLL_SEL);
9377                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9378                                 pll_id = DPLL_ID_PCH_PLL_B;
9379                         else
9380                                 pll_id= DPLL_ID_PCH_PLL_A;
9381                 }
9382
9383                 pipe_config->shared_dpll =
9384                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9385                 pll = pipe_config->shared_dpll;
9386
9387                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9388                                                  &pipe_config->dpll_hw_state));
9389
9390                 tmp = pipe_config->dpll_hw_state.dpll;
9391                 pipe_config->pixel_multiplier =
9392                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9393                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9394
9395                 ironlake_pch_clock_get(crtc, pipe_config);
9396         } else {
9397                 pipe_config->pixel_multiplier = 1;
9398         }
9399
9400         intel_get_pipe_timings(crtc, pipe_config);
9401         intel_get_pipe_src_size(crtc, pipe_config);
9402
9403         ironlake_get_pfit_config(crtc, pipe_config);
9404
9405         ret = true;
9406
9407 out:
9408         intel_display_power_put(dev_priv, power_domain);
9409
9410         return ret;
9411 }
9412
9413 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9414 {
9415         struct drm_device *dev = dev_priv->dev;
9416         struct intel_crtc *crtc;
9417
9418         for_each_intel_crtc(dev, crtc)
9419                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9420                      pipe_name(crtc->pipe));
9421
9422         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9423         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9424         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9425         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9426         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9427         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9428              "CPU PWM1 enabled\n");
9429         if (IS_HASWELL(dev))
9430                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9431                      "CPU PWM2 enabled\n");
9432         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9433              "PCH PWM1 enabled\n");
9434         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9435              "Utility pin enabled\n");
9436         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9437
9438         /*
9439          * In theory we can still leave IRQs enabled, as long as only the HPD
9440          * interrupts remain enabled. We used to check for that, but since it's
9441          * gen-specific and since we only disable LCPLL after we fully disable
9442          * the interrupts, the check below should be enough.
9443          */
9444         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9445 }
9446
9447 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9448 {
9449         struct drm_device *dev = dev_priv->dev;
9450
9451         if (IS_HASWELL(dev))
9452                 return I915_READ(D_COMP_HSW);
9453         else
9454                 return I915_READ(D_COMP_BDW);
9455 }
9456
9457 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9458 {
9459         struct drm_device *dev = dev_priv->dev;
9460
9461         if (IS_HASWELL(dev)) {
9462                 mutex_lock(&dev_priv->rps.hw_lock);
9463                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9464                                             val))
9465                         DRM_ERROR("Failed to write to D_COMP\n");
9466                 mutex_unlock(&dev_priv->rps.hw_lock);
9467         } else {
9468                 I915_WRITE(D_COMP_BDW, val);
9469                 POSTING_READ(D_COMP_BDW);
9470         }
9471 }
9472
9473 /*
9474  * This function implements pieces of two sequences from BSpec:
9475  * - Sequence for display software to disable LCPLL
9476  * - Sequence for display software to allow package C8+
9477  * The steps implemented here are just the steps that actually touch the LCPLL
9478  * register. Callers should take care of disabling all the display engine
9479  * functions, doing the mode unset, fixing interrupts, etc.
9480  */
9481 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9482                               bool switch_to_fclk, bool allow_power_down)
9483 {
9484         uint32_t val;
9485
9486         assert_can_disable_lcpll(dev_priv);
9487
9488         val = I915_READ(LCPLL_CTL);
9489
9490         if (switch_to_fclk) {
9491                 val |= LCPLL_CD_SOURCE_FCLK;
9492                 I915_WRITE(LCPLL_CTL, val);
9493
9494                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9495                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9496                         DRM_ERROR("Switching to FCLK failed\n");
9497
9498                 val = I915_READ(LCPLL_CTL);
9499         }
9500
9501         val |= LCPLL_PLL_DISABLE;
9502         I915_WRITE(LCPLL_CTL, val);
9503         POSTING_READ(LCPLL_CTL);
9504
9505         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9506                 DRM_ERROR("LCPLL still locked\n");
9507
9508         val = hsw_read_dcomp(dev_priv);
9509         val |= D_COMP_COMP_DISABLE;
9510         hsw_write_dcomp(dev_priv, val);
9511         ndelay(100);
9512
9513         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9514                      1))
9515                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9516
9517         if (allow_power_down) {
9518                 val = I915_READ(LCPLL_CTL);
9519                 val |= LCPLL_POWER_DOWN_ALLOW;
9520                 I915_WRITE(LCPLL_CTL, val);
9521                 POSTING_READ(LCPLL_CTL);
9522         }
9523 }
9524
9525 /*
9526  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9527  * source.
9528  */
9529 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9530 {
9531         uint32_t val;
9532
9533         val = I915_READ(LCPLL_CTL);
9534
9535         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9536                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9537                 return;
9538
9539         /*
9540          * Make sure we're not on PC8 state before disabling PC8, otherwise
9541          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9542          */
9543         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9544
9545         if (val & LCPLL_POWER_DOWN_ALLOW) {
9546                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9547                 I915_WRITE(LCPLL_CTL, val);
9548                 POSTING_READ(LCPLL_CTL);
9549         }
9550
9551         val = hsw_read_dcomp(dev_priv);
9552         val |= D_COMP_COMP_FORCE;
9553         val &= ~D_COMP_COMP_DISABLE;
9554         hsw_write_dcomp(dev_priv, val);
9555
9556         val = I915_READ(LCPLL_CTL);
9557         val &= ~LCPLL_PLL_DISABLE;
9558         I915_WRITE(LCPLL_CTL, val);
9559
9560         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9561                 DRM_ERROR("LCPLL not locked yet\n");
9562
9563         if (val & LCPLL_CD_SOURCE_FCLK) {
9564                 val = I915_READ(LCPLL_CTL);
9565                 val &= ~LCPLL_CD_SOURCE_FCLK;
9566                 I915_WRITE(LCPLL_CTL, val);
9567
9568                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9569                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9570                         DRM_ERROR("Switching back to LCPLL failed\n");
9571         }
9572
9573         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9574         intel_update_cdclk(dev_priv->dev);
9575 }
9576
9577 /*
9578  * Package states C8 and deeper are really deep PC states that can only be
9579  * reached when all the devices on the system allow it, so even if the graphics
9580  * device allows PC8+, it doesn't mean the system will actually get to these
9581  * states. Our driver only allows PC8+ when going into runtime PM.
9582  *
9583  * The requirements for PC8+ are that all the outputs are disabled, the power
9584  * well is disabled and most interrupts are disabled, and these are also
9585  * requirements for runtime PM. When these conditions are met, we manually do
9586  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9587  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9588  * hang the machine.
9589  *
9590  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9591  * the state of some registers, so when we come back from PC8+ we need to
9592  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9593  * need to take care of the registers kept by RC6. Notice that this happens even
9594  * if we don't put the device in PCI D3 state (which is what currently happens
9595  * because of the runtime PM support).
9596  *
9597  * For more, read "Display Sequences for Package C8" on the hardware
9598  * documentation.
9599  */
9600 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9601 {
9602         struct drm_device *dev = dev_priv->dev;
9603         uint32_t val;
9604
9605         DRM_DEBUG_KMS("Enabling package C8+\n");
9606
9607         if (HAS_PCH_LPT_LP(dev)) {
9608                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9609                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9610                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9611         }
9612
9613         lpt_disable_clkout_dp(dev);
9614         hsw_disable_lcpll(dev_priv, true, true);
9615 }
9616
9617 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9618 {
9619         struct drm_device *dev = dev_priv->dev;
9620         uint32_t val;
9621
9622         DRM_DEBUG_KMS("Disabling package C8+\n");
9623
9624         hsw_restore_lcpll(dev_priv);
9625         lpt_init_pch_refclk(dev);
9626
9627         if (HAS_PCH_LPT_LP(dev)) {
9628                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9629                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9630                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9631         }
9632 }
9633
9634 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9635 {
9636         struct drm_device *dev = old_state->dev;
9637         struct intel_atomic_state *old_intel_state =
9638                 to_intel_atomic_state(old_state);
9639         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9640
9641         broxton_set_cdclk(dev, req_cdclk);
9642 }
9643
9644 /* compute the max rate for new configuration */
9645 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9646 {
9647         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9648         struct drm_i915_private *dev_priv = state->dev->dev_private;
9649         struct drm_crtc *crtc;
9650         struct drm_crtc_state *cstate;
9651         struct intel_crtc_state *crtc_state;
9652         unsigned max_pixel_rate = 0, i;
9653         enum pipe pipe;
9654
9655         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9656                sizeof(intel_state->min_pixclk));
9657
9658         for_each_crtc_in_state(state, crtc, cstate, i) {
9659                 int pixel_rate;
9660
9661                 crtc_state = to_intel_crtc_state(cstate);
9662                 if (!crtc_state->base.enable) {
9663                         intel_state->min_pixclk[i] = 0;
9664                         continue;
9665                 }
9666
9667                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9668
9669                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9670                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9671                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9672
9673                 intel_state->min_pixclk[i] = pixel_rate;
9674         }
9675
9676         for_each_pipe(dev_priv, pipe)
9677                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9678
9679         return max_pixel_rate;
9680 }
9681
9682 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9683 {
9684         struct drm_i915_private *dev_priv = dev->dev_private;
9685         uint32_t val, data;
9686         int ret;
9687
9688         if (WARN((I915_READ(LCPLL_CTL) &
9689                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9690                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9691                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9692                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9693                  "trying to change cdclk frequency with cdclk not enabled\n"))
9694                 return;
9695
9696         mutex_lock(&dev_priv->rps.hw_lock);
9697         ret = sandybridge_pcode_write(dev_priv,
9698                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9699         mutex_unlock(&dev_priv->rps.hw_lock);
9700         if (ret) {
9701                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9702                 return;
9703         }
9704
9705         val = I915_READ(LCPLL_CTL);
9706         val |= LCPLL_CD_SOURCE_FCLK;
9707         I915_WRITE(LCPLL_CTL, val);
9708
9709         if (wait_for_us(I915_READ(LCPLL_CTL) &
9710                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9711                 DRM_ERROR("Switching to FCLK failed\n");
9712
9713         val = I915_READ(LCPLL_CTL);
9714         val &= ~LCPLL_CLK_FREQ_MASK;
9715
9716         switch (cdclk) {
9717         case 450000:
9718                 val |= LCPLL_CLK_FREQ_450;
9719                 data = 0;
9720                 break;
9721         case 540000:
9722                 val |= LCPLL_CLK_FREQ_54O_BDW;
9723                 data = 1;
9724                 break;
9725         case 337500:
9726                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9727                 data = 2;
9728                 break;
9729         case 675000:
9730                 val |= LCPLL_CLK_FREQ_675_BDW;
9731                 data = 3;
9732                 break;
9733         default:
9734                 WARN(1, "invalid cdclk frequency\n");
9735                 return;
9736         }
9737
9738         I915_WRITE(LCPLL_CTL, val);
9739
9740         val = I915_READ(LCPLL_CTL);
9741         val &= ~LCPLL_CD_SOURCE_FCLK;
9742         I915_WRITE(LCPLL_CTL, val);
9743
9744         if (wait_for_us((I915_READ(LCPLL_CTL) &
9745                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9746                 DRM_ERROR("Switching back to LCPLL failed\n");
9747
9748         mutex_lock(&dev_priv->rps.hw_lock);
9749         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9750         mutex_unlock(&dev_priv->rps.hw_lock);
9751
9752         intel_update_cdclk(dev);
9753
9754         WARN(cdclk != dev_priv->cdclk_freq,
9755              "cdclk requested %d kHz but got %d kHz\n",
9756              cdclk, dev_priv->cdclk_freq);
9757 }
9758
9759 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9760 {
9761         struct drm_i915_private *dev_priv = to_i915(state->dev);
9762         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9763         int max_pixclk = ilk_max_pixel_rate(state);
9764         int cdclk;
9765
9766         /*
9767          * FIXME should also account for plane ratio
9768          * once 64bpp pixel formats are supported.
9769          */
9770         if (max_pixclk > 540000)
9771                 cdclk = 675000;
9772         else if (max_pixclk > 450000)
9773                 cdclk = 540000;
9774         else if (max_pixclk > 337500)
9775                 cdclk = 450000;
9776         else
9777                 cdclk = 337500;
9778
9779         if (cdclk > dev_priv->max_cdclk_freq) {
9780                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9781                               cdclk, dev_priv->max_cdclk_freq);
9782                 return -EINVAL;
9783         }
9784
9785         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9786         if (!intel_state->active_crtcs)
9787                 intel_state->dev_cdclk = 337500;
9788
9789         return 0;
9790 }
9791
9792 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9793 {
9794         struct drm_device *dev = old_state->dev;
9795         struct intel_atomic_state *old_intel_state =
9796                 to_intel_atomic_state(old_state);
9797         unsigned req_cdclk = old_intel_state->dev_cdclk;
9798
9799         broadwell_set_cdclk(dev, req_cdclk);
9800 }
9801
9802 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9803                                       struct intel_crtc_state *crtc_state)
9804 {
9805         struct intel_encoder *intel_encoder =
9806                 intel_ddi_get_crtc_new_encoder(crtc_state);
9807
9808         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9809                 if (!intel_ddi_pll_select(crtc, crtc_state))
9810                         return -EINVAL;
9811         }
9812
9813         crtc->lowfreq_avail = false;
9814
9815         return 0;
9816 }
9817
9818 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9819                                 enum port port,
9820                                 struct intel_crtc_state *pipe_config)
9821 {
9822         enum intel_dpll_id id;
9823
9824         switch (port) {
9825         case PORT_A:
9826                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9827                 id = DPLL_ID_SKL_DPLL0;
9828                 break;
9829         case PORT_B:
9830                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9831                 id = DPLL_ID_SKL_DPLL1;
9832                 break;
9833         case PORT_C:
9834                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9835                 id = DPLL_ID_SKL_DPLL2;
9836                 break;
9837         default:
9838                 DRM_ERROR("Incorrect port type\n");
9839                 return;
9840         }
9841
9842         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9843 }
9844
9845 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9846                                 enum port port,
9847                                 struct intel_crtc_state *pipe_config)
9848 {
9849         enum intel_dpll_id id;
9850         u32 temp;
9851
9852         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9853         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9854
9855         switch (pipe_config->ddi_pll_sel) {
9856         case SKL_DPLL0:
9857                 id = DPLL_ID_SKL_DPLL0;
9858                 break;
9859         case SKL_DPLL1:
9860                 id = DPLL_ID_SKL_DPLL1;
9861                 break;
9862         case SKL_DPLL2:
9863                 id = DPLL_ID_SKL_DPLL2;
9864                 break;
9865         case SKL_DPLL3:
9866                 id = DPLL_ID_SKL_DPLL3;
9867                 break;
9868         default:
9869                 MISSING_CASE(pipe_config->ddi_pll_sel);
9870                 return;
9871         }
9872
9873         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9874 }
9875
9876 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9877                                 enum port port,
9878                                 struct intel_crtc_state *pipe_config)
9879 {
9880         enum intel_dpll_id id;
9881
9882         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9883
9884         switch (pipe_config->ddi_pll_sel) {
9885         case PORT_CLK_SEL_WRPLL1:
9886                 id = DPLL_ID_WRPLL1;
9887                 break;
9888         case PORT_CLK_SEL_WRPLL2:
9889                 id = DPLL_ID_WRPLL2;
9890                 break;
9891         case PORT_CLK_SEL_SPLL:
9892                 id = DPLL_ID_SPLL;
9893                 break;
9894         case PORT_CLK_SEL_LCPLL_810:
9895                 id = DPLL_ID_LCPLL_810;
9896                 break;
9897         case PORT_CLK_SEL_LCPLL_1350:
9898                 id = DPLL_ID_LCPLL_1350;
9899                 break;
9900         case PORT_CLK_SEL_LCPLL_2700:
9901                 id = DPLL_ID_LCPLL_2700;
9902                 break;
9903         default:
9904                 MISSING_CASE(pipe_config->ddi_pll_sel);
9905                 /* fall through */
9906         case PORT_CLK_SEL_NONE:
9907                 return;
9908         }
9909
9910         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9911 }
9912
9913 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9914                                        struct intel_crtc_state *pipe_config)
9915 {
9916         struct drm_device *dev = crtc->base.dev;
9917         struct drm_i915_private *dev_priv = dev->dev_private;
9918         struct intel_shared_dpll *pll;
9919         enum port port;
9920         uint32_t tmp;
9921
9922         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9923
9924         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9925
9926         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
9927                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9928         else if (IS_BROXTON(dev))
9929                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9930         else
9931                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9932
9933         pll = pipe_config->shared_dpll;
9934         if (pll) {
9935                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9936                                                  &pipe_config->dpll_hw_state));
9937         }
9938
9939         /*
9940          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9941          * DDI E. So just check whether this pipe is wired to DDI E and whether
9942          * the PCH transcoder is on.
9943          */
9944         if (INTEL_INFO(dev)->gen < 9 &&
9945             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9946                 pipe_config->has_pch_encoder = true;
9947
9948                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9949                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9950                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9951
9952                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9953         }
9954 }
9955
9956 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9957                                     struct intel_crtc_state *pipe_config)
9958 {
9959         struct drm_device *dev = crtc->base.dev;
9960         struct drm_i915_private *dev_priv = dev->dev_private;
9961         enum intel_display_power_domain power_domain;
9962         unsigned long power_domain_mask;
9963         uint32_t tmp;
9964         bool ret;
9965
9966         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9967         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9968                 return false;
9969         power_domain_mask = BIT(power_domain);
9970
9971         ret = false;
9972
9973         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9974         pipe_config->shared_dpll = NULL;
9975
9976         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9977         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9978                 enum pipe trans_edp_pipe;
9979                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9980                 default:
9981                         WARN(1, "unknown pipe linked to edp transcoder\n");
9982                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9983                 case TRANS_DDI_EDP_INPUT_A_ON:
9984                         trans_edp_pipe = PIPE_A;
9985                         break;
9986                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9987                         trans_edp_pipe = PIPE_B;
9988                         break;
9989                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9990                         trans_edp_pipe = PIPE_C;
9991                         break;
9992                 }
9993
9994                 if (trans_edp_pipe == crtc->pipe)
9995                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9996         }
9997
9998         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9999         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10000                 goto out;
10001         power_domain_mask |= BIT(power_domain);
10002
10003         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
10004         if (!(tmp & PIPECONF_ENABLE))
10005                 goto out;
10006
10007         haswell_get_ddi_port_state(crtc, pipe_config);
10008
10009         intel_get_pipe_timings(crtc, pipe_config);
10010         intel_get_pipe_src_size(crtc, pipe_config);
10011
10012         if (INTEL_INFO(dev)->gen >= 9) {
10013                 skl_init_scalers(dev, crtc, pipe_config);
10014         }
10015
10016         if (INTEL_INFO(dev)->gen >= 9) {
10017                 pipe_config->scaler_state.scaler_id = -1;
10018                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
10019         }
10020
10021         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10022         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10023                 power_domain_mask |= BIT(power_domain);
10024                 if (INTEL_INFO(dev)->gen >= 9)
10025                         skylake_get_pfit_config(crtc, pipe_config);
10026                 else
10027                         ironlake_get_pfit_config(crtc, pipe_config);
10028         }
10029
10030         if (IS_HASWELL(dev))
10031                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10032                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10033
10034         if (pipe_config->cpu_transcoder != TRANSCODER_EDP) {
10035                 pipe_config->pixel_multiplier =
10036                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10037         } else {
10038                 pipe_config->pixel_multiplier = 1;
10039         }
10040
10041         ret = true;
10042
10043 out:
10044         for_each_power_domain(power_domain, power_domain_mask)
10045                 intel_display_power_put(dev_priv, power_domain);
10046
10047         return ret;
10048 }
10049
10050 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10051                                const struct intel_plane_state *plane_state)
10052 {
10053         struct drm_device *dev = crtc->dev;
10054         struct drm_i915_private *dev_priv = dev->dev_private;
10055         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10056         uint32_t cntl = 0, size = 0;
10057
10058         if (plane_state && plane_state->visible) {
10059                 unsigned int width = plane_state->base.crtc_w;
10060                 unsigned int height = plane_state->base.crtc_h;
10061                 unsigned int stride = roundup_pow_of_two(width) * 4;
10062
10063                 switch (stride) {
10064                 default:
10065                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10066                                   width, stride);
10067                         stride = 256;
10068                         /* fallthrough */
10069                 case 256:
10070                 case 512:
10071                 case 1024:
10072                 case 2048:
10073                         break;
10074                 }
10075
10076                 cntl |= CURSOR_ENABLE |
10077                         CURSOR_GAMMA_ENABLE |
10078                         CURSOR_FORMAT_ARGB |
10079                         CURSOR_STRIDE(stride);
10080
10081                 size = (height << 12) | width;
10082         }
10083
10084         if (intel_crtc->cursor_cntl != 0 &&
10085             (intel_crtc->cursor_base != base ||
10086              intel_crtc->cursor_size != size ||
10087              intel_crtc->cursor_cntl != cntl)) {
10088                 /* On these chipsets we can only modify the base/size/stride
10089                  * whilst the cursor is disabled.
10090                  */
10091                 I915_WRITE(CURCNTR(PIPE_A), 0);
10092                 POSTING_READ(CURCNTR(PIPE_A));
10093                 intel_crtc->cursor_cntl = 0;
10094         }
10095
10096         if (intel_crtc->cursor_base != base) {
10097                 I915_WRITE(CURBASE(PIPE_A), base);
10098                 intel_crtc->cursor_base = base;
10099         }
10100
10101         if (intel_crtc->cursor_size != size) {
10102                 I915_WRITE(CURSIZE, size);
10103                 intel_crtc->cursor_size = size;
10104         }
10105
10106         if (intel_crtc->cursor_cntl != cntl) {
10107                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10108                 POSTING_READ(CURCNTR(PIPE_A));
10109                 intel_crtc->cursor_cntl = cntl;
10110         }
10111 }
10112
10113 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10114                                const struct intel_plane_state *plane_state)
10115 {
10116         struct drm_device *dev = crtc->dev;
10117         struct drm_i915_private *dev_priv = dev->dev_private;
10118         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10119         int pipe = intel_crtc->pipe;
10120         uint32_t cntl = 0;
10121
10122         if (plane_state && plane_state->visible) {
10123                 cntl = MCURSOR_GAMMA_ENABLE;
10124                 switch (plane_state->base.crtc_w) {
10125                         case 64:
10126                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10127                                 break;
10128                         case 128:
10129                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10130                                 break;
10131                         case 256:
10132                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10133                                 break;
10134                         default:
10135                                 MISSING_CASE(plane_state->base.crtc_w);
10136                                 return;
10137                 }
10138                 cntl |= pipe << 28; /* Connect to correct pipe */
10139
10140                 if (HAS_DDI(dev))
10141                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10142
10143                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10144                         cntl |= CURSOR_ROTATE_180;
10145         }
10146
10147         if (intel_crtc->cursor_cntl != cntl) {
10148                 I915_WRITE(CURCNTR(pipe), cntl);
10149                 POSTING_READ(CURCNTR(pipe));
10150                 intel_crtc->cursor_cntl = cntl;
10151         }
10152
10153         /* and commit changes on next vblank */
10154         I915_WRITE(CURBASE(pipe), base);
10155         POSTING_READ(CURBASE(pipe));
10156
10157         intel_crtc->cursor_base = base;
10158 }
10159
10160 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10161 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10162                                      const struct intel_plane_state *plane_state)
10163 {
10164         struct drm_device *dev = crtc->dev;
10165         struct drm_i915_private *dev_priv = dev->dev_private;
10166         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10167         int pipe = intel_crtc->pipe;
10168         u32 base = intel_crtc->cursor_addr;
10169         u32 pos = 0;
10170
10171         if (plane_state) {
10172                 int x = plane_state->base.crtc_x;
10173                 int y = plane_state->base.crtc_y;
10174
10175                 if (x < 0) {
10176                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10177                         x = -x;
10178                 }
10179                 pos |= x << CURSOR_X_SHIFT;
10180
10181                 if (y < 0) {
10182                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10183                         y = -y;
10184                 }
10185                 pos |= y << CURSOR_Y_SHIFT;
10186
10187                 /* ILK+ do this automagically */
10188                 if (HAS_GMCH_DISPLAY(dev) &&
10189                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10190                         base += (plane_state->base.crtc_h *
10191                                  plane_state->base.crtc_w - 1) * 4;
10192                 }
10193         }
10194
10195         I915_WRITE(CURPOS(pipe), pos);
10196
10197         if (IS_845G(dev) || IS_I865G(dev))
10198                 i845_update_cursor(crtc, base, plane_state);
10199         else
10200                 i9xx_update_cursor(crtc, base, plane_state);
10201 }
10202
10203 static bool cursor_size_ok(struct drm_device *dev,
10204                            uint32_t width, uint32_t height)
10205 {
10206         if (width == 0 || height == 0)
10207                 return false;
10208
10209         /*
10210          * 845g/865g are special in that they are only limited by
10211          * the width of their cursors, the height is arbitrary up to
10212          * the precision of the register. Everything else requires
10213          * square cursors, limited to a few power-of-two sizes.
10214          */
10215         if (IS_845G(dev) || IS_I865G(dev)) {
10216                 if ((width & 63) != 0)
10217                         return false;
10218
10219                 if (width > (IS_845G(dev) ? 64 : 512))
10220                         return false;
10221
10222                 if (height > 1023)
10223                         return false;
10224         } else {
10225                 switch (width | height) {
10226                 case 256:
10227                 case 128:
10228                         if (IS_GEN2(dev))
10229                                 return false;
10230                 case 64:
10231                         break;
10232                 default:
10233                         return false;
10234                 }
10235         }
10236
10237         return true;
10238 }
10239
10240 static void intel_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
10241                                  u16 *blue, uint32_t start, uint32_t size)
10242 {
10243         int end = (start + size > 256) ? 256 : start + size, i;
10244         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10245
10246         for (i = start; i < end; i++) {
10247                 intel_crtc->lut_r[i] = red[i] >> 8;
10248                 intel_crtc->lut_g[i] = green[i] >> 8;
10249                 intel_crtc->lut_b[i] = blue[i] >> 8;
10250         }
10251
10252         intel_crtc_load_lut(crtc);
10253 }
10254
10255 /* VESA 640x480x72Hz mode to set on the pipe */
10256 static struct drm_display_mode load_detect_mode = {
10257         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10258                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10259 };
10260
10261 struct drm_framebuffer *
10262 __intel_framebuffer_create(struct drm_device *dev,
10263                            struct drm_mode_fb_cmd2 *mode_cmd,
10264                            struct drm_i915_gem_object *obj)
10265 {
10266         struct intel_framebuffer *intel_fb;
10267         int ret;
10268
10269         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10270         if (!intel_fb)
10271                 return ERR_PTR(-ENOMEM);
10272
10273         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10274         if (ret)
10275                 goto err;
10276
10277         return &intel_fb->base;
10278
10279 err:
10280         kfree(intel_fb);
10281         return ERR_PTR(ret);
10282 }
10283
10284 static struct drm_framebuffer *
10285 intel_framebuffer_create(struct drm_device *dev,
10286                          struct drm_mode_fb_cmd2 *mode_cmd,
10287                          struct drm_i915_gem_object *obj)
10288 {
10289         struct drm_framebuffer *fb;
10290         int ret;
10291
10292         ret = i915_mutex_lock_interruptible(dev);
10293         if (ret)
10294                 return ERR_PTR(ret);
10295         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10296         mutex_unlock(&dev->struct_mutex);
10297
10298         return fb;
10299 }
10300
10301 static u32
10302 intel_framebuffer_pitch_for_width(int width, int bpp)
10303 {
10304         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10305         return ALIGN(pitch, 64);
10306 }
10307
10308 static u32
10309 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10310 {
10311         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10312         return PAGE_ALIGN(pitch * mode->vdisplay);
10313 }
10314
10315 static struct drm_framebuffer *
10316 intel_framebuffer_create_for_mode(struct drm_device *dev,
10317                                   struct drm_display_mode *mode,
10318                                   int depth, int bpp)
10319 {
10320         struct drm_framebuffer *fb;
10321         struct drm_i915_gem_object *obj;
10322         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10323
10324         obj = i915_gem_alloc_object(dev,
10325                                     intel_framebuffer_size_for_mode(mode, bpp));
10326         if (obj == NULL)
10327                 return ERR_PTR(-ENOMEM);
10328
10329         mode_cmd.width = mode->hdisplay;
10330         mode_cmd.height = mode->vdisplay;
10331         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10332                                                                 bpp);
10333         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10334
10335         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10336         if (IS_ERR(fb))
10337                 drm_gem_object_unreference_unlocked(&obj->base);
10338
10339         return fb;
10340 }
10341
10342 static struct drm_framebuffer *
10343 mode_fits_in_fbdev(struct drm_device *dev,
10344                    struct drm_display_mode *mode)
10345 {
10346 #ifdef CONFIG_DRM_FBDEV_EMULATION
10347         struct drm_i915_private *dev_priv = dev->dev_private;
10348         struct drm_i915_gem_object *obj;
10349         struct drm_framebuffer *fb;
10350
10351         if (!dev_priv->fbdev)
10352                 return NULL;
10353
10354         if (!dev_priv->fbdev->fb)
10355                 return NULL;
10356
10357         obj = dev_priv->fbdev->fb->obj;
10358         BUG_ON(!obj);
10359
10360         fb = &dev_priv->fbdev->fb->base;
10361         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10362                                                                fb->bits_per_pixel))
10363                 return NULL;
10364
10365         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10366                 return NULL;
10367
10368         drm_framebuffer_reference(fb);
10369         return fb;
10370 #else
10371         return NULL;
10372 #endif
10373 }
10374
10375 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10376                                            struct drm_crtc *crtc,
10377                                            struct drm_display_mode *mode,
10378                                            struct drm_framebuffer *fb,
10379                                            int x, int y)
10380 {
10381         struct drm_plane_state *plane_state;
10382         int hdisplay, vdisplay;
10383         int ret;
10384
10385         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10386         if (IS_ERR(plane_state))
10387                 return PTR_ERR(plane_state);
10388
10389         if (mode)
10390                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10391         else
10392                 hdisplay = vdisplay = 0;
10393
10394         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10395         if (ret)
10396                 return ret;
10397         drm_atomic_set_fb_for_plane(plane_state, fb);
10398         plane_state->crtc_x = 0;
10399         plane_state->crtc_y = 0;
10400         plane_state->crtc_w = hdisplay;
10401         plane_state->crtc_h = vdisplay;
10402         plane_state->src_x = x << 16;
10403         plane_state->src_y = y << 16;
10404         plane_state->src_w = hdisplay << 16;
10405         plane_state->src_h = vdisplay << 16;
10406
10407         return 0;
10408 }
10409
10410 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10411                                 struct drm_display_mode *mode,
10412                                 struct intel_load_detect_pipe *old,
10413                                 struct drm_modeset_acquire_ctx *ctx)
10414 {
10415         struct intel_crtc *intel_crtc;
10416         struct intel_encoder *intel_encoder =
10417                 intel_attached_encoder(connector);
10418         struct drm_crtc *possible_crtc;
10419         struct drm_encoder *encoder = &intel_encoder->base;
10420         struct drm_crtc *crtc = NULL;
10421         struct drm_device *dev = encoder->dev;
10422         struct drm_framebuffer *fb;
10423         struct drm_mode_config *config = &dev->mode_config;
10424         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10425         struct drm_connector_state *connector_state;
10426         struct intel_crtc_state *crtc_state;
10427         int ret, i = -1;
10428
10429         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10430                       connector->base.id, connector->name,
10431                       encoder->base.id, encoder->name);
10432
10433         old->restore_state = NULL;
10434
10435 retry:
10436         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10437         if (ret)
10438                 goto fail;
10439
10440         /*
10441          * Algorithm gets a little messy:
10442          *
10443          *   - if the connector already has an assigned crtc, use it (but make
10444          *     sure it's on first)
10445          *
10446          *   - try to find the first unused crtc that can drive this connector,
10447          *     and use that if we find one
10448          */
10449
10450         /* See if we already have a CRTC for this connector */
10451         if (connector->state->crtc) {
10452                 crtc = connector->state->crtc;
10453
10454                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10455                 if (ret)
10456                         goto fail;
10457
10458                 /* Make sure the crtc and connector are running */
10459                 goto found;
10460         }
10461
10462         /* Find an unused one (if possible) */
10463         for_each_crtc(dev, possible_crtc) {
10464                 i++;
10465                 if (!(encoder->possible_crtcs & (1 << i)))
10466                         continue;
10467
10468                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10469                 if (ret)
10470                         goto fail;
10471
10472                 if (possible_crtc->state->enable) {
10473                         drm_modeset_unlock(&possible_crtc->mutex);
10474                         continue;
10475                 }
10476
10477                 crtc = possible_crtc;
10478                 break;
10479         }
10480
10481         /*
10482          * If we didn't find an unused CRTC, don't use any.
10483          */
10484         if (!crtc) {
10485                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10486                 goto fail;
10487         }
10488
10489 found:
10490         intel_crtc = to_intel_crtc(crtc);
10491
10492         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10493         if (ret)
10494                 goto fail;
10495
10496         state = drm_atomic_state_alloc(dev);
10497         restore_state = drm_atomic_state_alloc(dev);
10498         if (!state || !restore_state) {
10499                 ret = -ENOMEM;
10500                 goto fail;
10501         }
10502
10503         state->acquire_ctx = ctx;
10504         restore_state->acquire_ctx = ctx;
10505
10506         connector_state = drm_atomic_get_connector_state(state, connector);
10507         if (IS_ERR(connector_state)) {
10508                 ret = PTR_ERR(connector_state);
10509                 goto fail;
10510         }
10511
10512         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10513         if (ret)
10514                 goto fail;
10515
10516         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10517         if (IS_ERR(crtc_state)) {
10518                 ret = PTR_ERR(crtc_state);
10519                 goto fail;
10520         }
10521
10522         crtc_state->base.active = crtc_state->base.enable = true;
10523
10524         if (!mode)
10525                 mode = &load_detect_mode;
10526
10527         /* We need a framebuffer large enough to accommodate all accesses
10528          * that the plane may generate whilst we perform load detection.
10529          * We can not rely on the fbcon either being present (we get called
10530          * during its initialisation to detect all boot displays, or it may
10531          * not even exist) or that it is large enough to satisfy the
10532          * requested mode.
10533          */
10534         fb = mode_fits_in_fbdev(dev, mode);
10535         if (fb == NULL) {
10536                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10537                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10538         } else
10539                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10540         if (IS_ERR(fb)) {
10541                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10542                 goto fail;
10543         }
10544
10545         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10546         if (ret)
10547                 goto fail;
10548
10549         drm_framebuffer_unreference(fb);
10550
10551         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10552         if (ret)
10553                 goto fail;
10554
10555         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10556         if (!ret)
10557                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10558         if (!ret)
10559                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10560         if (ret) {
10561                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10562                 goto fail;
10563         }
10564
10565         ret = drm_atomic_commit(state);
10566         if (ret) {
10567                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10568                 goto fail;
10569         }
10570
10571         old->restore_state = restore_state;
10572
10573         /* let the connector get through one full cycle before testing */
10574         intel_wait_for_vblank(dev, intel_crtc->pipe);
10575         return true;
10576
10577 fail:
10578         drm_atomic_state_free(state);
10579         drm_atomic_state_free(restore_state);
10580         restore_state = state = NULL;
10581
10582         if (ret == -EDEADLK) {
10583                 drm_modeset_backoff(ctx);
10584                 goto retry;
10585         }
10586
10587         return false;
10588 }
10589
10590 void intel_release_load_detect_pipe(struct drm_connector *connector,
10591                                     struct intel_load_detect_pipe *old,
10592                                     struct drm_modeset_acquire_ctx *ctx)
10593 {
10594         struct intel_encoder *intel_encoder =
10595                 intel_attached_encoder(connector);
10596         struct drm_encoder *encoder = &intel_encoder->base;
10597         struct drm_atomic_state *state = old->restore_state;
10598         int ret;
10599
10600         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10601                       connector->base.id, connector->name,
10602                       encoder->base.id, encoder->name);
10603
10604         if (!state)
10605                 return;
10606
10607         ret = drm_atomic_commit(state);
10608         if (ret) {
10609                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10610                 drm_atomic_state_free(state);
10611         }
10612 }
10613
10614 static int i9xx_pll_refclk(struct drm_device *dev,
10615                            const struct intel_crtc_state *pipe_config)
10616 {
10617         struct drm_i915_private *dev_priv = dev->dev_private;
10618         u32 dpll = pipe_config->dpll_hw_state.dpll;
10619
10620         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10621                 return dev_priv->vbt.lvds_ssc_freq;
10622         else if (HAS_PCH_SPLIT(dev))
10623                 return 120000;
10624         else if (!IS_GEN2(dev))
10625                 return 96000;
10626         else
10627                 return 48000;
10628 }
10629
10630 /* Returns the clock of the currently programmed mode of the given pipe. */
10631 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10632                                 struct intel_crtc_state *pipe_config)
10633 {
10634         struct drm_device *dev = crtc->base.dev;
10635         struct drm_i915_private *dev_priv = dev->dev_private;
10636         int pipe = pipe_config->cpu_transcoder;
10637         u32 dpll = pipe_config->dpll_hw_state.dpll;
10638         u32 fp;
10639         intel_clock_t clock;
10640         int port_clock;
10641         int refclk = i9xx_pll_refclk(dev, pipe_config);
10642
10643         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10644                 fp = pipe_config->dpll_hw_state.fp0;
10645         else
10646                 fp = pipe_config->dpll_hw_state.fp1;
10647
10648         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10649         if (IS_PINEVIEW(dev)) {
10650                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10651                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10652         } else {
10653                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10654                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10655         }
10656
10657         if (!IS_GEN2(dev)) {
10658                 if (IS_PINEVIEW(dev))
10659                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10660                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10661                 else
10662                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10663                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10664
10665                 switch (dpll & DPLL_MODE_MASK) {
10666                 case DPLLB_MODE_DAC_SERIAL:
10667                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10668                                 5 : 10;
10669                         break;
10670                 case DPLLB_MODE_LVDS:
10671                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10672                                 7 : 14;
10673                         break;
10674                 default:
10675                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10676                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10677                         return;
10678                 }
10679
10680                 if (IS_PINEVIEW(dev))
10681                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10682                 else
10683                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10684         } else {
10685                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10686                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10687
10688                 if (is_lvds) {
10689                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10690                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10691
10692                         if (lvds & LVDS_CLKB_POWER_UP)
10693                                 clock.p2 = 7;
10694                         else
10695                                 clock.p2 = 14;
10696                 } else {
10697                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10698                                 clock.p1 = 2;
10699                         else {
10700                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10701                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10702                         }
10703                         if (dpll & PLL_P2_DIVIDE_BY_4)
10704                                 clock.p2 = 4;
10705                         else
10706                                 clock.p2 = 2;
10707                 }
10708
10709                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10710         }
10711
10712         /*
10713          * This value includes pixel_multiplier. We will use
10714          * port_clock to compute adjusted_mode.crtc_clock in the
10715          * encoder's get_config() function.
10716          */
10717         pipe_config->port_clock = port_clock;
10718 }
10719
10720 int intel_dotclock_calculate(int link_freq,
10721                              const struct intel_link_m_n *m_n)
10722 {
10723         /*
10724          * The calculation for the data clock is:
10725          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10726          * But we want to avoid losing precison if possible, so:
10727          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10728          *
10729          * and the link clock is simpler:
10730          * link_clock = (m * link_clock) / n
10731          */
10732
10733         if (!m_n->link_n)
10734                 return 0;
10735
10736         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10737 }
10738
10739 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10740                                    struct intel_crtc_state *pipe_config)
10741 {
10742         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10743
10744         /* read out port_clock from the DPLL */
10745         i9xx_crtc_clock_get(crtc, pipe_config);
10746
10747         /*
10748          * In case there is an active pipe without active ports,
10749          * we may need some idea for the dotclock anyway.
10750          * Calculate one based on the FDI configuration.
10751          */
10752         pipe_config->base.adjusted_mode.crtc_clock =
10753                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10754                                          &pipe_config->fdi_m_n);
10755 }
10756
10757 /** Returns the currently programmed mode of the given pipe. */
10758 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10759                                              struct drm_crtc *crtc)
10760 {
10761         struct drm_i915_private *dev_priv = dev->dev_private;
10762         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10763         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10764         struct drm_display_mode *mode;
10765         struct intel_crtc_state *pipe_config;
10766         int htot = I915_READ(HTOTAL(cpu_transcoder));
10767         int hsync = I915_READ(HSYNC(cpu_transcoder));
10768         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10769         int vsync = I915_READ(VSYNC(cpu_transcoder));
10770         enum pipe pipe = intel_crtc->pipe;
10771
10772         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10773         if (!mode)
10774                 return NULL;
10775
10776         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10777         if (!pipe_config) {
10778                 kfree(mode);
10779                 return NULL;
10780         }
10781
10782         /*
10783          * Construct a pipe_config sufficient for getting the clock info
10784          * back out of crtc_clock_get.
10785          *
10786          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10787          * to use a real value here instead.
10788          */
10789         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10790         pipe_config->pixel_multiplier = 1;
10791         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10792         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10793         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10794         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10795
10796         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10797         mode->hdisplay = (htot & 0xffff) + 1;
10798         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10799         mode->hsync_start = (hsync & 0xffff) + 1;
10800         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10801         mode->vdisplay = (vtot & 0xffff) + 1;
10802         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10803         mode->vsync_start = (vsync & 0xffff) + 1;
10804         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10805
10806         drm_mode_set_name(mode);
10807
10808         kfree(pipe_config);
10809
10810         return mode;
10811 }
10812
10813 void intel_mark_busy(struct drm_device *dev)
10814 {
10815         struct drm_i915_private *dev_priv = dev->dev_private;
10816
10817         if (dev_priv->mm.busy)
10818                 return;
10819
10820         intel_runtime_pm_get(dev_priv);
10821         i915_update_gfx_val(dev_priv);
10822         if (INTEL_INFO(dev)->gen >= 6)
10823                 gen6_rps_busy(dev_priv);
10824         dev_priv->mm.busy = true;
10825 }
10826
10827 void intel_mark_idle(struct drm_device *dev)
10828 {
10829         struct drm_i915_private *dev_priv = dev->dev_private;
10830
10831         if (!dev_priv->mm.busy)
10832                 return;
10833
10834         dev_priv->mm.busy = false;
10835
10836         if (INTEL_INFO(dev)->gen >= 6)
10837                 gen6_rps_idle(dev->dev_private);
10838
10839         intel_runtime_pm_put(dev_priv);
10840 }
10841
10842 static void intel_crtc_destroy(struct drm_crtc *crtc)
10843 {
10844         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10845         struct drm_device *dev = crtc->dev;
10846         struct intel_unpin_work *work;
10847
10848         spin_lock_irq(&dev->event_lock);
10849         work = intel_crtc->unpin_work;
10850         intel_crtc->unpin_work = NULL;
10851         spin_unlock_irq(&dev->event_lock);
10852
10853         if (work) {
10854                 cancel_work_sync(&work->work);
10855                 kfree(work);
10856         }
10857
10858         drm_crtc_cleanup(crtc);
10859
10860         kfree(intel_crtc);
10861 }
10862
10863 static void intel_unpin_work_fn(struct work_struct *__work)
10864 {
10865         struct intel_unpin_work *work =
10866                 container_of(__work, struct intel_unpin_work, work);
10867         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10868         struct drm_device *dev = crtc->base.dev;
10869         struct drm_plane *primary = crtc->base.primary;
10870
10871         mutex_lock(&dev->struct_mutex);
10872         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
10873         drm_gem_object_unreference(&work->pending_flip_obj->base);
10874
10875         if (work->flip_queued_req)
10876                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10877         mutex_unlock(&dev->struct_mutex);
10878
10879         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10880         intel_fbc_post_update(crtc);
10881         drm_framebuffer_unreference(work->old_fb);
10882
10883         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10884         atomic_dec(&crtc->unpin_work_count);
10885
10886         kfree(work);
10887 }
10888
10889 static void do_intel_finish_page_flip(struct drm_device *dev,
10890                                       struct drm_crtc *crtc)
10891 {
10892         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10893         struct intel_unpin_work *work;
10894         unsigned long flags;
10895
10896         /* Ignore early vblank irqs */
10897         if (intel_crtc == NULL)
10898                 return;
10899
10900         /*
10901          * This is called both by irq handlers and the reset code (to complete
10902          * lost pageflips) so needs the full irqsave spinlocks.
10903          */
10904         spin_lock_irqsave(&dev->event_lock, flags);
10905         work = intel_crtc->unpin_work;
10906
10907         /* Ensure we don't miss a work->pending update ... */
10908         smp_rmb();
10909
10910         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10911                 spin_unlock_irqrestore(&dev->event_lock, flags);
10912                 return;
10913         }
10914
10915         page_flip_completed(intel_crtc);
10916
10917         spin_unlock_irqrestore(&dev->event_lock, flags);
10918 }
10919
10920 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10921 {
10922         struct drm_i915_private *dev_priv = dev->dev_private;
10923         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10924
10925         do_intel_finish_page_flip(dev, crtc);
10926 }
10927
10928 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10929 {
10930         struct drm_i915_private *dev_priv = dev->dev_private;
10931         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10932
10933         do_intel_finish_page_flip(dev, crtc);
10934 }
10935
10936 /* Is 'a' after or equal to 'b'? */
10937 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10938 {
10939         return !((a - b) & 0x80000000);
10940 }
10941
10942 static bool page_flip_finished(struct intel_crtc *crtc)
10943 {
10944         struct drm_device *dev = crtc->base.dev;
10945         struct drm_i915_private *dev_priv = dev->dev_private;
10946
10947         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10948             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10949                 return true;
10950
10951         /*
10952          * The relevant registers doen't exist on pre-ctg.
10953          * As the flip done interrupt doesn't trigger for mmio
10954          * flips on gmch platforms, a flip count check isn't
10955          * really needed there. But since ctg has the registers,
10956          * include it in the check anyway.
10957          */
10958         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10959                 return true;
10960
10961         /*
10962          * BDW signals flip done immediately if the plane
10963          * is disabled, even if the plane enable is already
10964          * armed to occur at the next vblank :(
10965          */
10966
10967         /*
10968          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10969          * used the same base address. In that case the mmio flip might
10970          * have completed, but the CS hasn't even executed the flip yet.
10971          *
10972          * A flip count check isn't enough as the CS might have updated
10973          * the base address just after start of vblank, but before we
10974          * managed to process the interrupt. This means we'd complete the
10975          * CS flip too soon.
10976          *
10977          * Combining both checks should get us a good enough result. It may
10978          * still happen that the CS flip has been executed, but has not
10979          * yet actually completed. But in case the base address is the same
10980          * anyway, we don't really care.
10981          */
10982         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10983                 crtc->unpin_work->gtt_offset &&
10984                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10985                                     crtc->unpin_work->flip_count);
10986 }
10987
10988 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10989 {
10990         struct drm_i915_private *dev_priv = dev->dev_private;
10991         struct intel_crtc *intel_crtc =
10992                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10993         unsigned long flags;
10994
10995
10996         /*
10997          * This is called both by irq handlers and the reset code (to complete
10998          * lost pageflips) so needs the full irqsave spinlocks.
10999          *
11000          * NB: An MMIO update of the plane base pointer will also
11001          * generate a page-flip completion irq, i.e. every modeset
11002          * is also accompanied by a spurious intel_prepare_page_flip().
11003          */
11004         spin_lock_irqsave(&dev->event_lock, flags);
11005         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
11006                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
11007         spin_unlock_irqrestore(&dev->event_lock, flags);
11008 }
11009
11010 static inline void intel_mark_page_flip_active(struct intel_unpin_work *work)
11011 {
11012         /* Ensure that the work item is consistent when activating it ... */
11013         smp_wmb();
11014         atomic_set(&work->pending, INTEL_FLIP_PENDING);
11015         /* and that it is marked active as soon as the irq could fire. */
11016         smp_wmb();
11017 }
11018
11019 static int intel_gen2_queue_flip(struct drm_device *dev,
11020                                  struct drm_crtc *crtc,
11021                                  struct drm_framebuffer *fb,
11022                                  struct drm_i915_gem_object *obj,
11023                                  struct drm_i915_gem_request *req,
11024                                  uint32_t flags)
11025 {
11026         struct intel_engine_cs *engine = req->engine;
11027         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11028         u32 flip_mask;
11029         int ret;
11030
11031         ret = intel_ring_begin(req, 6);
11032         if (ret)
11033                 return ret;
11034
11035         /* Can't queue multiple flips, so wait for the previous
11036          * one to finish before executing the next.
11037          */
11038         if (intel_crtc->plane)
11039                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11040         else
11041                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11042         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11043         intel_ring_emit(engine, MI_NOOP);
11044         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11045                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11046         intel_ring_emit(engine, fb->pitches[0]);
11047         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11048         intel_ring_emit(engine, 0); /* aux display base address, unused */
11049
11050         intel_mark_page_flip_active(intel_crtc->unpin_work);
11051         return 0;
11052 }
11053
11054 static int intel_gen3_queue_flip(struct drm_device *dev,
11055                                  struct drm_crtc *crtc,
11056                                  struct drm_framebuffer *fb,
11057                                  struct drm_i915_gem_object *obj,
11058                                  struct drm_i915_gem_request *req,
11059                                  uint32_t flags)
11060 {
11061         struct intel_engine_cs *engine = req->engine;
11062         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11063         u32 flip_mask;
11064         int ret;
11065
11066         ret = intel_ring_begin(req, 6);
11067         if (ret)
11068                 return ret;
11069
11070         if (intel_crtc->plane)
11071                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11072         else
11073                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11074         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11075         intel_ring_emit(engine, MI_NOOP);
11076         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 |
11077                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11078         intel_ring_emit(engine, fb->pitches[0]);
11079         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11080         intel_ring_emit(engine, MI_NOOP);
11081
11082         intel_mark_page_flip_active(intel_crtc->unpin_work);
11083         return 0;
11084 }
11085
11086 static int intel_gen4_queue_flip(struct drm_device *dev,
11087                                  struct drm_crtc *crtc,
11088                                  struct drm_framebuffer *fb,
11089                                  struct drm_i915_gem_object *obj,
11090                                  struct drm_i915_gem_request *req,
11091                                  uint32_t flags)
11092 {
11093         struct intel_engine_cs *engine = req->engine;
11094         struct drm_i915_private *dev_priv = dev->dev_private;
11095         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11096         uint32_t pf, pipesrc;
11097         int ret;
11098
11099         ret = intel_ring_begin(req, 4);
11100         if (ret)
11101                 return ret;
11102
11103         /* i965+ uses the linear or tiled offsets from the
11104          * Display Registers (which do not change across a page-flip)
11105          * so we need only reprogram the base address.
11106          */
11107         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11108                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11109         intel_ring_emit(engine, fb->pitches[0]);
11110         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset |
11111                         obj->tiling_mode);
11112
11113         /* XXX Enabling the panel-fitter across page-flip is so far
11114          * untested on non-native modes, so ignore it for now.
11115          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11116          */
11117         pf = 0;
11118         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11119         intel_ring_emit(engine, pf | pipesrc);
11120
11121         intel_mark_page_flip_active(intel_crtc->unpin_work);
11122         return 0;
11123 }
11124
11125 static int intel_gen6_queue_flip(struct drm_device *dev,
11126                                  struct drm_crtc *crtc,
11127                                  struct drm_framebuffer *fb,
11128                                  struct drm_i915_gem_object *obj,
11129                                  struct drm_i915_gem_request *req,
11130                                  uint32_t flags)
11131 {
11132         struct intel_engine_cs *engine = req->engine;
11133         struct drm_i915_private *dev_priv = dev->dev_private;
11134         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11135         uint32_t pf, pipesrc;
11136         int ret;
11137
11138         ret = intel_ring_begin(req, 4);
11139         if (ret)
11140                 return ret;
11141
11142         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11143                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11144         intel_ring_emit(engine, fb->pitches[0] | obj->tiling_mode);
11145         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11146
11147         /* Contrary to the suggestions in the documentation,
11148          * "Enable Panel Fitter" does not seem to be required when page
11149          * flipping with a non-native mode, and worse causes a normal
11150          * modeset to fail.
11151          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11152          */
11153         pf = 0;
11154         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11155         intel_ring_emit(engine, pf | pipesrc);
11156
11157         intel_mark_page_flip_active(intel_crtc->unpin_work);
11158         return 0;
11159 }
11160
11161 static int intel_gen7_queue_flip(struct drm_device *dev,
11162                                  struct drm_crtc *crtc,
11163                                  struct drm_framebuffer *fb,
11164                                  struct drm_i915_gem_object *obj,
11165                                  struct drm_i915_gem_request *req,
11166                                  uint32_t flags)
11167 {
11168         struct intel_engine_cs *engine = req->engine;
11169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11170         uint32_t plane_bit = 0;
11171         int len, ret;
11172
11173         switch (intel_crtc->plane) {
11174         case PLANE_A:
11175                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11176                 break;
11177         case PLANE_B:
11178                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11179                 break;
11180         case PLANE_C:
11181                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11182                 break;
11183         default:
11184                 WARN_ONCE(1, "unknown plane in flip command\n");
11185                 return -ENODEV;
11186         }
11187
11188         len = 4;
11189         if (engine->id == RCS) {
11190                 len += 6;
11191                 /*
11192                  * On Gen 8, SRM is now taking an extra dword to accommodate
11193                  * 48bits addresses, and we need a NOOP for the batch size to
11194                  * stay even.
11195                  */
11196                 if (IS_GEN8(dev))
11197                         len += 2;
11198         }
11199
11200         /*
11201          * BSpec MI_DISPLAY_FLIP for IVB:
11202          * "The full packet must be contained within the same cache line."
11203          *
11204          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11205          * cacheline, if we ever start emitting more commands before
11206          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11207          * then do the cacheline alignment, and finally emit the
11208          * MI_DISPLAY_FLIP.
11209          */
11210         ret = intel_ring_cacheline_align(req);
11211         if (ret)
11212                 return ret;
11213
11214         ret = intel_ring_begin(req, len);
11215         if (ret)
11216                 return ret;
11217
11218         /* Unmask the flip-done completion message. Note that the bspec says that
11219          * we should do this for both the BCS and RCS, and that we must not unmask
11220          * more than one flip event at any time (or ensure that one flip message
11221          * can be sent by waiting for flip-done prior to queueing new flips).
11222          * Experimentation says that BCS works despite DERRMR masking all
11223          * flip-done completion events and that unmasking all planes at once
11224          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11225          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11226          */
11227         if (engine->id == RCS) {
11228                 intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
11229                 intel_ring_emit_reg(engine, DERRMR);
11230                 intel_ring_emit(engine, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11231                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11232                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11233                 if (IS_GEN8(dev))
11234                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM_GEN8 |
11235                                               MI_SRM_LRM_GLOBAL_GTT);
11236                 else
11237                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM |
11238                                               MI_SRM_LRM_GLOBAL_GTT);
11239                 intel_ring_emit_reg(engine, DERRMR);
11240                 intel_ring_emit(engine, engine->scratch.gtt_offset + 256);
11241                 if (IS_GEN8(dev)) {
11242                         intel_ring_emit(engine, 0);
11243                         intel_ring_emit(engine, MI_NOOP);
11244                 }
11245         }
11246
11247         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 | plane_bit);
11248         intel_ring_emit(engine, (fb->pitches[0] | obj->tiling_mode));
11249         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11250         intel_ring_emit(engine, (MI_NOOP));
11251
11252         intel_mark_page_flip_active(intel_crtc->unpin_work);
11253         return 0;
11254 }
11255
11256 static bool use_mmio_flip(struct intel_engine_cs *engine,
11257                           struct drm_i915_gem_object *obj)
11258 {
11259         /*
11260          * This is not being used for older platforms, because
11261          * non-availability of flip done interrupt forces us to use
11262          * CS flips. Older platforms derive flip done using some clever
11263          * tricks involving the flip_pending status bits and vblank irqs.
11264          * So using MMIO flips there would disrupt this mechanism.
11265          */
11266
11267         if (engine == NULL)
11268                 return true;
11269
11270         if (INTEL_INFO(engine->dev)->gen < 5)
11271                 return false;
11272
11273         if (i915.use_mmio_flip < 0)
11274                 return false;
11275         else if (i915.use_mmio_flip > 0)
11276                 return true;
11277         else if (i915.enable_execlists)
11278                 return true;
11279         else if (obj->base.dma_buf &&
11280                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11281                                                        false))
11282                 return true;
11283         else
11284                 return engine != i915_gem_request_get_engine(obj->last_write_req);
11285 }
11286
11287 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11288                              unsigned int rotation,
11289                              struct intel_unpin_work *work)
11290 {
11291         struct drm_device *dev = intel_crtc->base.dev;
11292         struct drm_i915_private *dev_priv = dev->dev_private;
11293         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11294         const enum pipe pipe = intel_crtc->pipe;
11295         u32 ctl, stride, tile_height;
11296
11297         ctl = I915_READ(PLANE_CTL(pipe, 0));
11298         ctl &= ~PLANE_CTL_TILED_MASK;
11299         switch (fb->modifier[0]) {
11300         case DRM_FORMAT_MOD_NONE:
11301                 break;
11302         case I915_FORMAT_MOD_X_TILED:
11303                 ctl |= PLANE_CTL_TILED_X;
11304                 break;
11305         case I915_FORMAT_MOD_Y_TILED:
11306                 ctl |= PLANE_CTL_TILED_Y;
11307                 break;
11308         case I915_FORMAT_MOD_Yf_TILED:
11309                 ctl |= PLANE_CTL_TILED_YF;
11310                 break;
11311         default:
11312                 MISSING_CASE(fb->modifier[0]);
11313         }
11314
11315         /*
11316          * The stride is either expressed as a multiple of 64 bytes chunks for
11317          * linear buffers or in number of tiles for tiled buffers.
11318          */
11319         if (intel_rotation_90_or_270(rotation)) {
11320                 /* stride = Surface height in tiles */
11321                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11322                 stride = DIV_ROUND_UP(fb->height, tile_height);
11323         } else {
11324                 stride = fb->pitches[0] /
11325                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11326                                                   fb->pixel_format);
11327         }
11328
11329         /*
11330          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11331          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11332          */
11333         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11334         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11335
11336         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11337         POSTING_READ(PLANE_SURF(pipe, 0));
11338 }
11339
11340 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11341                              struct intel_unpin_work *work)
11342 {
11343         struct drm_device *dev = intel_crtc->base.dev;
11344         struct drm_i915_private *dev_priv = dev->dev_private;
11345         struct intel_framebuffer *intel_fb =
11346                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11347         struct drm_i915_gem_object *obj = intel_fb->obj;
11348         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11349         u32 dspcntr;
11350
11351         dspcntr = I915_READ(reg);
11352
11353         if (obj->tiling_mode != I915_TILING_NONE)
11354                 dspcntr |= DISPPLANE_TILED;
11355         else
11356                 dspcntr &= ~DISPPLANE_TILED;
11357
11358         I915_WRITE(reg, dspcntr);
11359
11360         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11361         POSTING_READ(DSPSURF(intel_crtc->plane));
11362 }
11363
11364 /*
11365  * XXX: This is the temporary way to update the plane registers until we get
11366  * around to using the usual plane update functions for MMIO flips
11367  */
11368 static void intel_do_mmio_flip(struct intel_mmio_flip *mmio_flip)
11369 {
11370         struct intel_crtc *crtc = mmio_flip->crtc;
11371         struct intel_unpin_work *work;
11372
11373         spin_lock_irq(&crtc->base.dev->event_lock);
11374         work = crtc->unpin_work;
11375         spin_unlock_irq(&crtc->base.dev->event_lock);
11376         if (work == NULL)
11377                 return;
11378
11379         intel_mark_page_flip_active(work);
11380
11381         intel_pipe_update_start(crtc);
11382
11383         if (INTEL_INFO(mmio_flip->i915)->gen >= 9)
11384                 skl_do_mmio_flip(crtc, mmio_flip->rotation, work);
11385         else
11386                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11387                 ilk_do_mmio_flip(crtc, work);
11388
11389         intel_pipe_update_end(crtc);
11390 }
11391
11392 static void intel_mmio_flip_work_func(struct work_struct *work)
11393 {
11394         struct intel_mmio_flip *mmio_flip =
11395                 container_of(work, struct intel_mmio_flip, work);
11396         struct intel_framebuffer *intel_fb =
11397                 to_intel_framebuffer(mmio_flip->crtc->base.primary->fb);
11398         struct drm_i915_gem_object *obj = intel_fb->obj;
11399
11400         if (mmio_flip->req) {
11401                 WARN_ON(__i915_wait_request(mmio_flip->req,
11402                                             mmio_flip->crtc->reset_counter,
11403                                             false, NULL,
11404                                             &mmio_flip->i915->rps.mmioflips));
11405                 i915_gem_request_unreference__unlocked(mmio_flip->req);
11406         }
11407
11408         /* For framebuffer backed by dmabuf, wait for fence */
11409         if (obj->base.dma_buf)
11410                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11411                                                             false, false,
11412                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11413
11414         intel_do_mmio_flip(mmio_flip);
11415         kfree(mmio_flip);
11416 }
11417
11418 static int intel_queue_mmio_flip(struct drm_device *dev,
11419                                  struct drm_crtc *crtc,
11420                                  struct drm_i915_gem_object *obj)
11421 {
11422         struct intel_mmio_flip *mmio_flip;
11423
11424         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11425         if (mmio_flip == NULL)
11426                 return -ENOMEM;
11427
11428         mmio_flip->i915 = to_i915(dev);
11429         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11430         mmio_flip->crtc = to_intel_crtc(crtc);
11431         mmio_flip->rotation = crtc->primary->state->rotation;
11432
11433         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11434         schedule_work(&mmio_flip->work);
11435
11436         return 0;
11437 }
11438
11439 static int intel_default_queue_flip(struct drm_device *dev,
11440                                     struct drm_crtc *crtc,
11441                                     struct drm_framebuffer *fb,
11442                                     struct drm_i915_gem_object *obj,
11443                                     struct drm_i915_gem_request *req,
11444                                     uint32_t flags)
11445 {
11446         return -ENODEV;
11447 }
11448
11449 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11450                                          struct drm_crtc *crtc)
11451 {
11452         struct drm_i915_private *dev_priv = dev->dev_private;
11453         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11454         struct intel_unpin_work *work = intel_crtc->unpin_work;
11455         u32 addr;
11456
11457         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11458                 return true;
11459
11460         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11461                 return false;
11462
11463         if (!work->enable_stall_check)
11464                 return false;
11465
11466         if (work->flip_ready_vblank == 0) {
11467                 if (work->flip_queued_req &&
11468                     !i915_gem_request_completed(work->flip_queued_req, true))
11469                         return false;
11470
11471                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11472         }
11473
11474         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11475                 return false;
11476
11477         /* Potential stall - if we see that the flip has happened,
11478          * assume a missed interrupt. */
11479         if (INTEL_INFO(dev)->gen >= 4)
11480                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11481         else
11482                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11483
11484         /* There is a potential issue here with a false positive after a flip
11485          * to the same address. We could address this by checking for a
11486          * non-incrementing frame counter.
11487          */
11488         return addr == work->gtt_offset;
11489 }
11490
11491 void intel_check_page_flip(struct drm_device *dev, int pipe)
11492 {
11493         struct drm_i915_private *dev_priv = dev->dev_private;
11494         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11495         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11496         struct intel_unpin_work *work;
11497
11498         WARN_ON(!in_interrupt());
11499
11500         if (crtc == NULL)
11501                 return;
11502
11503         spin_lock(&dev->event_lock);
11504         work = intel_crtc->unpin_work;
11505         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11506                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11507                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11508                 page_flip_completed(intel_crtc);
11509                 work = NULL;
11510         }
11511         if (work != NULL &&
11512             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11513                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11514         spin_unlock(&dev->event_lock);
11515 }
11516
11517 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11518                                 struct drm_framebuffer *fb,
11519                                 struct drm_pending_vblank_event *event,
11520                                 uint32_t page_flip_flags)
11521 {
11522         struct drm_device *dev = crtc->dev;
11523         struct drm_i915_private *dev_priv = dev->dev_private;
11524         struct drm_framebuffer *old_fb = crtc->primary->fb;
11525         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11526         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11527         struct drm_plane *primary = crtc->primary;
11528         enum pipe pipe = intel_crtc->pipe;
11529         struct intel_unpin_work *work;
11530         struct intel_engine_cs *engine;
11531         bool mmio_flip;
11532         struct drm_i915_gem_request *request = NULL;
11533         int ret;
11534
11535         /*
11536          * drm_mode_page_flip_ioctl() should already catch this, but double
11537          * check to be safe.  In the future we may enable pageflipping from
11538          * a disabled primary plane.
11539          */
11540         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11541                 return -EBUSY;
11542
11543         /* Can't change pixel format via MI display flips. */
11544         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11545                 return -EINVAL;
11546
11547         /*
11548          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11549          * Note that pitch changes could also affect these register.
11550          */
11551         if (INTEL_INFO(dev)->gen > 3 &&
11552             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11553              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11554                 return -EINVAL;
11555
11556         if (i915_terminally_wedged(&dev_priv->gpu_error))
11557                 goto out_hang;
11558
11559         work = kzalloc(sizeof(*work), GFP_KERNEL);
11560         if (work == NULL)
11561                 return -ENOMEM;
11562
11563         work->event = event;
11564         work->crtc = crtc;
11565         work->old_fb = old_fb;
11566         INIT_WORK(&work->work, intel_unpin_work_fn);
11567
11568         ret = drm_crtc_vblank_get(crtc);
11569         if (ret)
11570                 goto free_work;
11571
11572         /* We borrow the event spin lock for protecting unpin_work */
11573         spin_lock_irq(&dev->event_lock);
11574         if (intel_crtc->unpin_work) {
11575                 /* Before declaring the flip queue wedged, check if
11576                  * the hardware completed the operation behind our backs.
11577                  */
11578                 if (__intel_pageflip_stall_check(dev, crtc)) {
11579                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11580                         page_flip_completed(intel_crtc);
11581                 } else {
11582                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11583                         spin_unlock_irq(&dev->event_lock);
11584
11585                         drm_crtc_vblank_put(crtc);
11586                         kfree(work);
11587                         return -EBUSY;
11588                 }
11589         }
11590         intel_crtc->unpin_work = work;
11591         spin_unlock_irq(&dev->event_lock);
11592
11593         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11594                 flush_workqueue(dev_priv->wq);
11595
11596         /* Reference the objects for the scheduled work. */
11597         drm_framebuffer_reference(work->old_fb);
11598         drm_gem_object_reference(&obj->base);
11599
11600         crtc->primary->fb = fb;
11601         update_state_fb(crtc->primary);
11602         intel_fbc_pre_update(intel_crtc);
11603
11604         work->pending_flip_obj = obj;
11605
11606         ret = i915_mutex_lock_interruptible(dev);
11607         if (ret)
11608                 goto cleanup;
11609
11610         atomic_inc(&intel_crtc->unpin_work_count);
11611         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11612
11613         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11614                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11615
11616         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11617                 engine = &dev_priv->engine[BCS];
11618                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11619                         /* vlv: DISPLAY_FLIP fails to change tiling */
11620                         engine = NULL;
11621         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11622                 engine = &dev_priv->engine[BCS];
11623         } else if (INTEL_INFO(dev)->gen >= 7) {
11624                 engine = i915_gem_request_get_engine(obj->last_write_req);
11625                 if (engine == NULL || engine->id != RCS)
11626                         engine = &dev_priv->engine[BCS];
11627         } else {
11628                 engine = &dev_priv->engine[RCS];
11629         }
11630
11631         mmio_flip = use_mmio_flip(engine, obj);
11632
11633         /* When using CS flips, we want to emit semaphores between rings.
11634          * However, when using mmio flips we will create a task to do the
11635          * synchronisation, so all we want here is to pin the framebuffer
11636          * into the display plane and skip any waits.
11637          */
11638         if (!mmio_flip) {
11639                 ret = i915_gem_object_sync(obj, engine, &request);
11640                 if (ret)
11641                         goto cleanup_pending;
11642         }
11643
11644         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11645         if (ret)
11646                 goto cleanup_pending;
11647
11648         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11649                                                   obj, 0);
11650         work->gtt_offset += intel_crtc->dspaddr_offset;
11651
11652         if (mmio_flip) {
11653                 ret = intel_queue_mmio_flip(dev, crtc, obj);
11654                 if (ret)
11655                         goto cleanup_unpin;
11656
11657                 i915_gem_request_assign(&work->flip_queued_req,
11658                                         obj->last_write_req);
11659         } else {
11660                 if (!request) {
11661                         request = i915_gem_request_alloc(engine, NULL);
11662                         if (IS_ERR(request)) {
11663                                 ret = PTR_ERR(request);
11664                                 goto cleanup_unpin;
11665                         }
11666                 }
11667
11668                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11669                                                    page_flip_flags);
11670                 if (ret)
11671                         goto cleanup_unpin;
11672
11673                 i915_gem_request_assign(&work->flip_queued_req, request);
11674         }
11675
11676         if (request)
11677                 i915_add_request_no_flush(request);
11678
11679         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11680         work->enable_stall_check = true;
11681
11682         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11683                           to_intel_plane(primary)->frontbuffer_bit);
11684         mutex_unlock(&dev->struct_mutex);
11685
11686         intel_frontbuffer_flip_prepare(dev,
11687                                        to_intel_plane(primary)->frontbuffer_bit);
11688
11689         trace_i915_flip_request(intel_crtc->plane, obj);
11690
11691         return 0;
11692
11693 cleanup_unpin:
11694         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11695 cleanup_pending:
11696         if (!IS_ERR_OR_NULL(request))
11697                 i915_gem_request_cancel(request);
11698         atomic_dec(&intel_crtc->unpin_work_count);
11699         mutex_unlock(&dev->struct_mutex);
11700 cleanup:
11701         crtc->primary->fb = old_fb;
11702         update_state_fb(crtc->primary);
11703
11704         drm_gem_object_unreference_unlocked(&obj->base);
11705         drm_framebuffer_unreference(work->old_fb);
11706
11707         spin_lock_irq(&dev->event_lock);
11708         intel_crtc->unpin_work = NULL;
11709         spin_unlock_irq(&dev->event_lock);
11710
11711         drm_crtc_vblank_put(crtc);
11712 free_work:
11713         kfree(work);
11714
11715         if (ret == -EIO) {
11716                 struct drm_atomic_state *state;
11717                 struct drm_plane_state *plane_state;
11718
11719 out_hang:
11720                 state = drm_atomic_state_alloc(dev);
11721                 if (!state)
11722                         return -ENOMEM;
11723                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11724
11725 retry:
11726                 plane_state = drm_atomic_get_plane_state(state, primary);
11727                 ret = PTR_ERR_OR_ZERO(plane_state);
11728                 if (!ret) {
11729                         drm_atomic_set_fb_for_plane(plane_state, fb);
11730
11731                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11732                         if (!ret)
11733                                 ret = drm_atomic_commit(state);
11734                 }
11735
11736                 if (ret == -EDEADLK) {
11737                         drm_modeset_backoff(state->acquire_ctx);
11738                         drm_atomic_state_clear(state);
11739                         goto retry;
11740                 }
11741
11742                 if (ret)
11743                         drm_atomic_state_free(state);
11744
11745                 if (ret == 0 && event) {
11746                         spin_lock_irq(&dev->event_lock);
11747                         drm_send_vblank_event(dev, pipe, event);
11748                         spin_unlock_irq(&dev->event_lock);
11749                 }
11750         }
11751         return ret;
11752 }
11753
11754
11755 /**
11756  * intel_wm_need_update - Check whether watermarks need updating
11757  * @plane: drm plane
11758  * @state: new plane state
11759  *
11760  * Check current plane state versus the new one to determine whether
11761  * watermarks need to be recalculated.
11762  *
11763  * Returns true or false.
11764  */
11765 static bool intel_wm_need_update(struct drm_plane *plane,
11766                                  struct drm_plane_state *state)
11767 {
11768         struct intel_plane_state *new = to_intel_plane_state(state);
11769         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11770
11771         /* Update watermarks on tiling or size changes. */
11772         if (new->visible != cur->visible)
11773                 return true;
11774
11775         if (!cur->base.fb || !new->base.fb)
11776                 return false;
11777
11778         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11779             cur->base.rotation != new->base.rotation ||
11780             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11781             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11782             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11783             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11784                 return true;
11785
11786         return false;
11787 }
11788
11789 static bool needs_scaling(struct intel_plane_state *state)
11790 {
11791         int src_w = drm_rect_width(&state->src) >> 16;
11792         int src_h = drm_rect_height(&state->src) >> 16;
11793         int dst_w = drm_rect_width(&state->dst);
11794         int dst_h = drm_rect_height(&state->dst);
11795
11796         return (src_w != dst_w || src_h != dst_h);
11797 }
11798
11799 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11800                                     struct drm_plane_state *plane_state)
11801 {
11802         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11803         struct drm_crtc *crtc = crtc_state->crtc;
11804         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11805         struct drm_plane *plane = plane_state->plane;
11806         struct drm_device *dev = crtc->dev;
11807         struct drm_i915_private *dev_priv = to_i915(dev);
11808         struct intel_plane_state *old_plane_state =
11809                 to_intel_plane_state(plane->state);
11810         int idx = intel_crtc->base.base.id, ret;
11811         bool mode_changed = needs_modeset(crtc_state);
11812         bool was_crtc_enabled = crtc->state->active;
11813         bool is_crtc_enabled = crtc_state->active;
11814         bool turn_off, turn_on, visible, was_visible;
11815         struct drm_framebuffer *fb = plane_state->fb;
11816
11817         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11818             plane->type != DRM_PLANE_TYPE_CURSOR) {
11819                 ret = skl_update_scaler_plane(
11820                         to_intel_crtc_state(crtc_state),
11821                         to_intel_plane_state(plane_state));
11822                 if (ret)
11823                         return ret;
11824         }
11825
11826         was_visible = old_plane_state->visible;
11827         visible = to_intel_plane_state(plane_state)->visible;
11828
11829         if (!was_crtc_enabled && WARN_ON(was_visible))
11830                 was_visible = false;
11831
11832         /*
11833          * Visibility is calculated as if the crtc was on, but
11834          * after scaler setup everything depends on it being off
11835          * when the crtc isn't active.
11836          */
11837         if (!is_crtc_enabled)
11838                 to_intel_plane_state(plane_state)->visible = visible = false;
11839
11840         if (!was_visible && !visible)
11841                 return 0;
11842
11843         if (fb != old_plane_state->base.fb)
11844                 pipe_config->fb_changed = true;
11845
11846         turn_off = was_visible && (!visible || mode_changed);
11847         turn_on = visible && (!was_visible || mode_changed);
11848
11849         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11850                          plane->base.id, fb ? fb->base.id : -1);
11851
11852         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11853                          plane->base.id, was_visible, visible,
11854                          turn_off, turn_on, mode_changed);
11855
11856         if (turn_on) {
11857                 pipe_config->update_wm_pre = true;
11858
11859                 /* must disable cxsr around plane enable/disable */
11860                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11861                         pipe_config->disable_cxsr = true;
11862         } else if (turn_off) {
11863                 pipe_config->update_wm_post = true;
11864
11865                 /* must disable cxsr around plane enable/disable */
11866                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11867                         pipe_config->disable_cxsr = true;
11868         } else if (intel_wm_need_update(plane, plane_state)) {
11869                 /* FIXME bollocks */
11870                 pipe_config->update_wm_pre = true;
11871                 pipe_config->update_wm_post = true;
11872         }
11873
11874         /* Pre-gen9 platforms need two-step watermark updates */
11875         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11876             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11877                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11878
11879         if (visible || was_visible)
11880                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11881
11882         /*
11883          * WaCxSRDisabledForSpriteScaling:ivb
11884          *
11885          * cstate->update_wm was already set above, so this flag will
11886          * take effect when we commit and program watermarks.
11887          */
11888         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
11889             needs_scaling(to_intel_plane_state(plane_state)) &&
11890             !needs_scaling(old_plane_state))
11891                 pipe_config->disable_lp_wm = true;
11892
11893         return 0;
11894 }
11895
11896 static bool encoders_cloneable(const struct intel_encoder *a,
11897                                const struct intel_encoder *b)
11898 {
11899         /* masks could be asymmetric, so check both ways */
11900         return a == b || (a->cloneable & (1 << b->type) &&
11901                           b->cloneable & (1 << a->type));
11902 }
11903
11904 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11905                                          struct intel_crtc *crtc,
11906                                          struct intel_encoder *encoder)
11907 {
11908         struct intel_encoder *source_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                 source_encoder =
11918                         to_intel_encoder(connector_state->best_encoder);
11919                 if (!encoders_cloneable(encoder, source_encoder))
11920                         return false;
11921         }
11922
11923         return true;
11924 }
11925
11926 static bool check_encoder_cloning(struct drm_atomic_state *state,
11927                                   struct intel_crtc *crtc)
11928 {
11929         struct intel_encoder *encoder;
11930         struct drm_connector *connector;
11931         struct drm_connector_state *connector_state;
11932         int i;
11933
11934         for_each_connector_in_state(state, connector, connector_state, i) {
11935                 if (connector_state->crtc != &crtc->base)
11936                         continue;
11937
11938                 encoder = to_intel_encoder(connector_state->best_encoder);
11939                 if (!check_single_encoder_cloning(state, crtc, encoder))
11940                         return false;
11941         }
11942
11943         return true;
11944 }
11945
11946 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11947                                    struct drm_crtc_state *crtc_state)
11948 {
11949         struct drm_device *dev = crtc->dev;
11950         struct drm_i915_private *dev_priv = dev->dev_private;
11951         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11952         struct intel_crtc_state *pipe_config =
11953                 to_intel_crtc_state(crtc_state);
11954         struct drm_atomic_state *state = crtc_state->state;
11955         int ret;
11956         bool mode_changed = needs_modeset(crtc_state);
11957
11958         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11959                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11960                 return -EINVAL;
11961         }
11962
11963         if (mode_changed && !crtc_state->active)
11964                 pipe_config->update_wm_post = true;
11965
11966         if (mode_changed && crtc_state->enable &&
11967             dev_priv->display.crtc_compute_clock &&
11968             !WARN_ON(pipe_config->shared_dpll)) {
11969                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11970                                                            pipe_config);
11971                 if (ret)
11972                         return ret;
11973         }
11974
11975         ret = 0;
11976         if (dev_priv->display.compute_pipe_wm) {
11977                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11978                 if (ret) {
11979                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11980                         return ret;
11981                 }
11982         }
11983
11984         if (dev_priv->display.compute_intermediate_wm &&
11985             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11986                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11987                         return 0;
11988
11989                 /*
11990                  * Calculate 'intermediate' watermarks that satisfy both the
11991                  * old state and the new state.  We can program these
11992                  * immediately.
11993                  */
11994                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
11995                                                                 intel_crtc,
11996                                                                 pipe_config);
11997                 if (ret) {
11998                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11999                         return ret;
12000                 }
12001         }
12002
12003         if (INTEL_INFO(dev)->gen >= 9) {
12004                 if (mode_changed)
12005                         ret = skl_update_scaler_crtc(pipe_config);
12006
12007                 if (!ret)
12008                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
12009                                                          pipe_config);
12010         }
12011
12012         return ret;
12013 }
12014
12015 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
12016         .mode_set_base_atomic = intel_pipe_set_base_atomic,
12017         .load_lut = intel_crtc_load_lut,
12018         .atomic_begin = intel_begin_crtc_commit,
12019         .atomic_flush = intel_finish_crtc_commit,
12020         .atomic_check = intel_crtc_atomic_check,
12021 };
12022
12023 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
12024 {
12025         struct intel_connector *connector;
12026
12027         for_each_intel_connector(dev, connector) {
12028                 if (connector->base.encoder) {
12029                         connector->base.state->best_encoder =
12030                                 connector->base.encoder;
12031                         connector->base.state->crtc =
12032                                 connector->base.encoder->crtc;
12033                 } else {
12034                         connector->base.state->best_encoder = NULL;
12035                         connector->base.state->crtc = NULL;
12036                 }
12037         }
12038 }
12039
12040 static void
12041 connected_sink_compute_bpp(struct intel_connector *connector,
12042                            struct intel_crtc_state *pipe_config)
12043 {
12044         int bpp = pipe_config->pipe_bpp;
12045
12046         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12047                 connector->base.base.id,
12048                 connector->base.name);
12049
12050         /* Don't use an invalid EDID bpc value */
12051         if (connector->base.display_info.bpc &&
12052             connector->base.display_info.bpc * 3 < bpp) {
12053                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12054                               bpp, connector->base.display_info.bpc*3);
12055                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12056         }
12057
12058         /* Clamp bpp to default limit on screens without EDID 1.4 */
12059         if (connector->base.display_info.bpc == 0) {
12060                 int type = connector->base.connector_type;
12061                 int clamp_bpp = 24;
12062
12063                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12064                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12065                     type == DRM_MODE_CONNECTOR_eDP)
12066                         clamp_bpp = 18;
12067
12068                 if (bpp > clamp_bpp) {
12069                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12070                                       bpp, clamp_bpp);
12071                         pipe_config->pipe_bpp = clamp_bpp;
12072                 }
12073         }
12074 }
12075
12076 static int
12077 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12078                           struct intel_crtc_state *pipe_config)
12079 {
12080         struct drm_device *dev = crtc->base.dev;
12081         struct drm_atomic_state *state;
12082         struct drm_connector *connector;
12083         struct drm_connector_state *connector_state;
12084         int bpp, i;
12085
12086         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12087                 bpp = 10*3;
12088         else if (INTEL_INFO(dev)->gen >= 5)
12089                 bpp = 12*3;
12090         else
12091                 bpp = 8*3;
12092
12093
12094         pipe_config->pipe_bpp = bpp;
12095
12096         state = pipe_config->base.state;
12097
12098         /* Clamp display bpp to EDID value */
12099         for_each_connector_in_state(state, connector, connector_state, i) {
12100                 if (connector_state->crtc != &crtc->base)
12101                         continue;
12102
12103                 connected_sink_compute_bpp(to_intel_connector(connector),
12104                                            pipe_config);
12105         }
12106
12107         return bpp;
12108 }
12109
12110 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12111 {
12112         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12113                         "type: 0x%x flags: 0x%x\n",
12114                 mode->crtc_clock,
12115                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12116                 mode->crtc_hsync_end, mode->crtc_htotal,
12117                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12118                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12119 }
12120
12121 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12122                                    struct intel_crtc_state *pipe_config,
12123                                    const char *context)
12124 {
12125         struct drm_device *dev = crtc->base.dev;
12126         struct drm_plane *plane;
12127         struct intel_plane *intel_plane;
12128         struct intel_plane_state *state;
12129         struct drm_framebuffer *fb;
12130
12131         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12132                       context, pipe_config, pipe_name(crtc->pipe));
12133
12134         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12135         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12136                       pipe_config->pipe_bpp, pipe_config->dither);
12137         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12138                       pipe_config->has_pch_encoder,
12139                       pipe_config->fdi_lanes,
12140                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12141                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12142                       pipe_config->fdi_m_n.tu);
12143         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12144                       pipe_config->has_dp_encoder,
12145                       pipe_config->lane_count,
12146                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12147                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12148                       pipe_config->dp_m_n.tu);
12149
12150         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12151                       pipe_config->has_dp_encoder,
12152                       pipe_config->lane_count,
12153                       pipe_config->dp_m2_n2.gmch_m,
12154                       pipe_config->dp_m2_n2.gmch_n,
12155                       pipe_config->dp_m2_n2.link_m,
12156                       pipe_config->dp_m2_n2.link_n,
12157                       pipe_config->dp_m2_n2.tu);
12158
12159         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12160                       pipe_config->has_audio,
12161                       pipe_config->has_infoframe);
12162
12163         DRM_DEBUG_KMS("requested mode:\n");
12164         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12165         DRM_DEBUG_KMS("adjusted mode:\n");
12166         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12167         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12168         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12169         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12170                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12171         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12172                       crtc->num_scalers,
12173                       pipe_config->scaler_state.scaler_users,
12174                       pipe_config->scaler_state.scaler_id);
12175         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12176                       pipe_config->gmch_pfit.control,
12177                       pipe_config->gmch_pfit.pgm_ratios,
12178                       pipe_config->gmch_pfit.lvds_border_bits);
12179         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12180                       pipe_config->pch_pfit.pos,
12181                       pipe_config->pch_pfit.size,
12182                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12183         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12184         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12185
12186         if (IS_BROXTON(dev)) {
12187                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12188                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12189                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12190                               pipe_config->ddi_pll_sel,
12191                               pipe_config->dpll_hw_state.ebb0,
12192                               pipe_config->dpll_hw_state.ebb4,
12193                               pipe_config->dpll_hw_state.pll0,
12194                               pipe_config->dpll_hw_state.pll1,
12195                               pipe_config->dpll_hw_state.pll2,
12196                               pipe_config->dpll_hw_state.pll3,
12197                               pipe_config->dpll_hw_state.pll6,
12198                               pipe_config->dpll_hw_state.pll8,
12199                               pipe_config->dpll_hw_state.pll9,
12200                               pipe_config->dpll_hw_state.pll10,
12201                               pipe_config->dpll_hw_state.pcsdw12);
12202         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12203                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12204                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12205                               pipe_config->ddi_pll_sel,
12206                               pipe_config->dpll_hw_state.ctrl1,
12207                               pipe_config->dpll_hw_state.cfgcr1,
12208                               pipe_config->dpll_hw_state.cfgcr2);
12209         } else if (HAS_DDI(dev)) {
12210                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12211                               pipe_config->ddi_pll_sel,
12212                               pipe_config->dpll_hw_state.wrpll,
12213                               pipe_config->dpll_hw_state.spll);
12214         } else {
12215                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12216                               "fp0: 0x%x, fp1: 0x%x\n",
12217                               pipe_config->dpll_hw_state.dpll,
12218                               pipe_config->dpll_hw_state.dpll_md,
12219                               pipe_config->dpll_hw_state.fp0,
12220                               pipe_config->dpll_hw_state.fp1);
12221         }
12222
12223         DRM_DEBUG_KMS("planes on this crtc\n");
12224         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12225                 intel_plane = to_intel_plane(plane);
12226                 if (intel_plane->pipe != crtc->pipe)
12227                         continue;
12228
12229                 state = to_intel_plane_state(plane->state);
12230                 fb = state->base.fb;
12231                 if (!fb) {
12232                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12233                                 "disabled, scaler_id = %d\n",
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), state->scaler_id);
12238                         continue;
12239                 }
12240
12241                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12242                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12243                         plane->base.id, intel_plane->pipe,
12244                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12245                         drm_plane_index(plane));
12246                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12247                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12248                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12249                         state->scaler_id,
12250                         state->src.x1 >> 16, state->src.y1 >> 16,
12251                         drm_rect_width(&state->src) >> 16,
12252                         drm_rect_height(&state->src) >> 16,
12253                         state->dst.x1, state->dst.y1,
12254                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12255         }
12256 }
12257
12258 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12259 {
12260         struct drm_device *dev = state->dev;
12261         struct drm_connector *connector;
12262         unsigned int used_ports = 0;
12263
12264         /*
12265          * Walk the connector list instead of the encoder
12266          * list to detect the problem on ddi platforms
12267          * where there's just one encoder per digital port.
12268          */
12269         drm_for_each_connector(connector, dev) {
12270                 struct drm_connector_state *connector_state;
12271                 struct intel_encoder *encoder;
12272
12273                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12274                 if (!connector_state)
12275                         connector_state = connector->state;
12276
12277                 if (!connector_state->best_encoder)
12278                         continue;
12279
12280                 encoder = to_intel_encoder(connector_state->best_encoder);
12281
12282                 WARN_ON(!connector_state->crtc);
12283
12284                 switch (encoder->type) {
12285                         unsigned int port_mask;
12286                 case INTEL_OUTPUT_UNKNOWN:
12287                         if (WARN_ON(!HAS_DDI(dev)))
12288                                 break;
12289                 case INTEL_OUTPUT_DISPLAYPORT:
12290                 case INTEL_OUTPUT_HDMI:
12291                 case INTEL_OUTPUT_EDP:
12292                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12293
12294                         /* the same port mustn't appear more than once */
12295                         if (used_ports & port_mask)
12296                                 return false;
12297
12298                         used_ports |= port_mask;
12299                 default:
12300                         break;
12301                 }
12302         }
12303
12304         return true;
12305 }
12306
12307 static void
12308 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12309 {
12310         struct drm_crtc_state tmp_state;
12311         struct intel_crtc_scaler_state scaler_state;
12312         struct intel_dpll_hw_state dpll_hw_state;
12313         struct intel_shared_dpll *shared_dpll;
12314         uint32_t ddi_pll_sel;
12315         bool force_thru;
12316
12317         /* FIXME: before the switch to atomic started, a new pipe_config was
12318          * kzalloc'd. Code that depends on any field being zero should be
12319          * fixed, so that the crtc_state can be safely duplicated. For now,
12320          * only fields that are know to not cause problems are preserved. */
12321
12322         tmp_state = crtc_state->base;
12323         scaler_state = crtc_state->scaler_state;
12324         shared_dpll = crtc_state->shared_dpll;
12325         dpll_hw_state = crtc_state->dpll_hw_state;
12326         ddi_pll_sel = crtc_state->ddi_pll_sel;
12327         force_thru = crtc_state->pch_pfit.force_thru;
12328
12329         memset(crtc_state, 0, sizeof *crtc_state);
12330
12331         crtc_state->base = tmp_state;
12332         crtc_state->scaler_state = scaler_state;
12333         crtc_state->shared_dpll = shared_dpll;
12334         crtc_state->dpll_hw_state = dpll_hw_state;
12335         crtc_state->ddi_pll_sel = ddi_pll_sel;
12336         crtc_state->pch_pfit.force_thru = force_thru;
12337 }
12338
12339 static int
12340 intel_modeset_pipe_config(struct drm_crtc *crtc,
12341                           struct intel_crtc_state *pipe_config)
12342 {
12343         struct drm_atomic_state *state = pipe_config->base.state;
12344         struct intel_encoder *encoder;
12345         struct drm_connector *connector;
12346         struct drm_connector_state *connector_state;
12347         int base_bpp, ret = -EINVAL;
12348         int i;
12349         bool retry = true;
12350
12351         clear_intel_crtc_state(pipe_config);
12352
12353         pipe_config->cpu_transcoder =
12354                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12355
12356         /*
12357          * Sanitize sync polarity flags based on requested ones. If neither
12358          * positive or negative polarity is requested, treat this as meaning
12359          * negative polarity.
12360          */
12361         if (!(pipe_config->base.adjusted_mode.flags &
12362               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12363                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12364
12365         if (!(pipe_config->base.adjusted_mode.flags &
12366               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12367                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12368
12369         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12370                                              pipe_config);
12371         if (base_bpp < 0)
12372                 goto fail;
12373
12374         /*
12375          * Determine the real pipe dimensions. Note that stereo modes can
12376          * increase the actual pipe size due to the frame doubling and
12377          * insertion of additional space for blanks between the frame. This
12378          * is stored in the crtc timings. We use the requested mode to do this
12379          * computation to clearly distinguish it from the adjusted mode, which
12380          * can be changed by the connectors in the below retry loop.
12381          */
12382         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12383                                &pipe_config->pipe_src_w,
12384                                &pipe_config->pipe_src_h);
12385
12386 encoder_retry:
12387         /* Ensure the port clock defaults are reset when retrying. */
12388         pipe_config->port_clock = 0;
12389         pipe_config->pixel_multiplier = 1;
12390
12391         /* Fill in default crtc timings, allow encoders to overwrite them. */
12392         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12393                               CRTC_STEREO_DOUBLE);
12394
12395         /* Pass our mode to the connectors and the CRTC to give them a chance to
12396          * adjust it according to limitations or connector properties, and also
12397          * a chance to reject the mode entirely.
12398          */
12399         for_each_connector_in_state(state, connector, connector_state, i) {
12400                 if (connector_state->crtc != crtc)
12401                         continue;
12402
12403                 encoder = to_intel_encoder(connector_state->best_encoder);
12404
12405                 if (!(encoder->compute_config(encoder, pipe_config))) {
12406                         DRM_DEBUG_KMS("Encoder config failure\n");
12407                         goto fail;
12408                 }
12409         }
12410
12411         /* Set default port clock if not overwritten by the encoder. Needs to be
12412          * done afterwards in case the encoder adjusts the mode. */
12413         if (!pipe_config->port_clock)
12414                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12415                         * pipe_config->pixel_multiplier;
12416
12417         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12418         if (ret < 0) {
12419                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12420                 goto fail;
12421         }
12422
12423         if (ret == RETRY) {
12424                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12425                         ret = -EINVAL;
12426                         goto fail;
12427                 }
12428
12429                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12430                 retry = false;
12431                 goto encoder_retry;
12432         }
12433
12434         /* Dithering seems to not pass-through bits correctly when it should, so
12435          * only enable it on 6bpc panels. */
12436         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12437         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12438                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12439
12440 fail:
12441         return ret;
12442 }
12443
12444 static void
12445 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12446 {
12447         struct drm_crtc *crtc;
12448         struct drm_crtc_state *crtc_state;
12449         int i;
12450
12451         /* Double check state. */
12452         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12453                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12454
12455                 /* Update hwmode for vblank functions */
12456                 if (crtc->state->active)
12457                         crtc->hwmode = crtc->state->adjusted_mode;
12458                 else
12459                         crtc->hwmode.crtc_clock = 0;
12460
12461                 /*
12462                  * Update legacy state to satisfy fbc code. This can
12463                  * be removed when fbc uses the atomic state.
12464                  */
12465                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12466                         struct drm_plane_state *plane_state = crtc->primary->state;
12467
12468                         crtc->primary->fb = plane_state->fb;
12469                         crtc->x = plane_state->src_x >> 16;
12470                         crtc->y = plane_state->src_y >> 16;
12471                 }
12472         }
12473 }
12474
12475 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12476 {
12477         int diff;
12478
12479         if (clock1 == clock2)
12480                 return true;
12481
12482         if (!clock1 || !clock2)
12483                 return false;
12484
12485         diff = abs(clock1 - clock2);
12486
12487         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12488                 return true;
12489
12490         return false;
12491 }
12492
12493 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12494         list_for_each_entry((intel_crtc), \
12495                             &(dev)->mode_config.crtc_list, \
12496                             base.head) \
12497                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12498
12499 static bool
12500 intel_compare_m_n(unsigned int m, unsigned int n,
12501                   unsigned int m2, unsigned int n2,
12502                   bool exact)
12503 {
12504         if (m == m2 && n == n2)
12505                 return true;
12506
12507         if (exact || !m || !n || !m2 || !n2)
12508                 return false;
12509
12510         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12511
12512         if (n > n2) {
12513                 while (n > n2) {
12514                         m2 <<= 1;
12515                         n2 <<= 1;
12516                 }
12517         } else if (n < n2) {
12518                 while (n < n2) {
12519                         m <<= 1;
12520                         n <<= 1;
12521                 }
12522         }
12523
12524         if (n != n2)
12525                 return false;
12526
12527         return intel_fuzzy_clock_check(m, m2);
12528 }
12529
12530 static bool
12531 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12532                        struct intel_link_m_n *m2_n2,
12533                        bool adjust)
12534 {
12535         if (m_n->tu == m2_n2->tu &&
12536             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12537                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12538             intel_compare_m_n(m_n->link_m, m_n->link_n,
12539                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12540                 if (adjust)
12541                         *m2_n2 = *m_n;
12542
12543                 return true;
12544         }
12545
12546         return false;
12547 }
12548
12549 static bool
12550 intel_pipe_config_compare(struct drm_device *dev,
12551                           struct intel_crtc_state *current_config,
12552                           struct intel_crtc_state *pipe_config,
12553                           bool adjust)
12554 {
12555         bool ret = true;
12556
12557 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12558         do { \
12559                 if (!adjust) \
12560                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12561                 else \
12562                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12563         } while (0)
12564
12565 #define PIPE_CONF_CHECK_X(name) \
12566         if (current_config->name != pipe_config->name) { \
12567                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12568                           "(expected 0x%08x, found 0x%08x)\n", \
12569                           current_config->name, \
12570                           pipe_config->name); \
12571                 ret = false; \
12572         }
12573
12574 #define PIPE_CONF_CHECK_I(name) \
12575         if (current_config->name != pipe_config->name) { \
12576                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12577                           "(expected %i, found %i)\n", \
12578                           current_config->name, \
12579                           pipe_config->name); \
12580                 ret = false; \
12581         }
12582
12583 #define PIPE_CONF_CHECK_P(name) \
12584         if (current_config->name != pipe_config->name) { \
12585                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12586                           "(expected %p, found %p)\n", \
12587                           current_config->name, \
12588                           pipe_config->name); \
12589                 ret = false; \
12590         }
12591
12592 #define PIPE_CONF_CHECK_M_N(name) \
12593         if (!intel_compare_link_m_n(&current_config->name, \
12594                                     &pipe_config->name,\
12595                                     adjust)) { \
12596                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12597                           "(expected tu %i gmch %i/%i link %i/%i, " \
12598                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12599                           current_config->name.tu, \
12600                           current_config->name.gmch_m, \
12601                           current_config->name.gmch_n, \
12602                           current_config->name.link_m, \
12603                           current_config->name.link_n, \
12604                           pipe_config->name.tu, \
12605                           pipe_config->name.gmch_m, \
12606                           pipe_config->name.gmch_n, \
12607                           pipe_config->name.link_m, \
12608                           pipe_config->name.link_n); \
12609                 ret = false; \
12610         }
12611
12612 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12613         if (!intel_compare_link_m_n(&current_config->name, \
12614                                     &pipe_config->name, adjust) && \
12615             !intel_compare_link_m_n(&current_config->alt_name, \
12616                                     &pipe_config->name, adjust)) { \
12617                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12618                           "(expected tu %i gmch %i/%i link %i/%i, " \
12619                           "or tu %i gmch %i/%i link %i/%i, " \
12620                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12621                           current_config->name.tu, \
12622                           current_config->name.gmch_m, \
12623                           current_config->name.gmch_n, \
12624                           current_config->name.link_m, \
12625                           current_config->name.link_n, \
12626                           current_config->alt_name.tu, \
12627                           current_config->alt_name.gmch_m, \
12628                           current_config->alt_name.gmch_n, \
12629                           current_config->alt_name.link_m, \
12630                           current_config->alt_name.link_n, \
12631                           pipe_config->name.tu, \
12632                           pipe_config->name.gmch_m, \
12633                           pipe_config->name.gmch_n, \
12634                           pipe_config->name.link_m, \
12635                           pipe_config->name.link_n); \
12636                 ret = false; \
12637         }
12638
12639 /* This is required for BDW+ where there is only one set of registers for
12640  * switching between high and low RR.
12641  * This macro can be used whenever a comparison has to be made between one
12642  * hw state and multiple sw state variables.
12643  */
12644 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12645         if ((current_config->name != pipe_config->name) && \
12646                 (current_config->alt_name != pipe_config->name)) { \
12647                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12648                                   "(expected %i or %i, found %i)\n", \
12649                                   current_config->name, \
12650                                   current_config->alt_name, \
12651                                   pipe_config->name); \
12652                         ret = false; \
12653         }
12654
12655 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12656         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12657                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12658                           "(expected %i, found %i)\n", \
12659                           current_config->name & (mask), \
12660                           pipe_config->name & (mask)); \
12661                 ret = false; \
12662         }
12663
12664 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12665         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12666                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12667                           "(expected %i, found %i)\n", \
12668                           current_config->name, \
12669                           pipe_config->name); \
12670                 ret = false; \
12671         }
12672
12673 #define PIPE_CONF_QUIRK(quirk)  \
12674         ((current_config->quirks | pipe_config->quirks) & (quirk))
12675
12676         PIPE_CONF_CHECK_I(cpu_transcoder);
12677
12678         PIPE_CONF_CHECK_I(has_pch_encoder);
12679         PIPE_CONF_CHECK_I(fdi_lanes);
12680         PIPE_CONF_CHECK_M_N(fdi_m_n);
12681
12682         PIPE_CONF_CHECK_I(has_dp_encoder);
12683         PIPE_CONF_CHECK_I(lane_count);
12684
12685         if (INTEL_INFO(dev)->gen < 8) {
12686                 PIPE_CONF_CHECK_M_N(dp_m_n);
12687
12688                 if (current_config->has_drrs)
12689                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12690         } else
12691                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12692
12693         PIPE_CONF_CHECK_I(has_dsi_encoder);
12694
12695         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12696         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12697         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12698         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12699         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12700         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12701
12702         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12703         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12704         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12705         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12706         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12707         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12708
12709         PIPE_CONF_CHECK_I(pixel_multiplier);
12710         PIPE_CONF_CHECK_I(has_hdmi_sink);
12711         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12712             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12713                 PIPE_CONF_CHECK_I(limited_color_range);
12714         PIPE_CONF_CHECK_I(has_infoframe);
12715
12716         PIPE_CONF_CHECK_I(has_audio);
12717
12718         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12719                               DRM_MODE_FLAG_INTERLACE);
12720
12721         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12722                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12723                                       DRM_MODE_FLAG_PHSYNC);
12724                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12725                                       DRM_MODE_FLAG_NHSYNC);
12726                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12727                                       DRM_MODE_FLAG_PVSYNC);
12728                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12729                                       DRM_MODE_FLAG_NVSYNC);
12730         }
12731
12732         PIPE_CONF_CHECK_X(gmch_pfit.control);
12733         /* pfit ratios are autocomputed by the hw on gen4+ */
12734         if (INTEL_INFO(dev)->gen < 4)
12735                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12736         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12737
12738         if (!adjust) {
12739                 PIPE_CONF_CHECK_I(pipe_src_w);
12740                 PIPE_CONF_CHECK_I(pipe_src_h);
12741
12742                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12743                 if (current_config->pch_pfit.enabled) {
12744                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12745                         PIPE_CONF_CHECK_X(pch_pfit.size);
12746                 }
12747
12748                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12749         }
12750
12751         /* BDW+ don't expose a synchronous way to read the state */
12752         if (IS_HASWELL(dev))
12753                 PIPE_CONF_CHECK_I(ips_enabled);
12754
12755         PIPE_CONF_CHECK_I(double_wide);
12756
12757         PIPE_CONF_CHECK_X(ddi_pll_sel);
12758
12759         PIPE_CONF_CHECK_P(shared_dpll);
12760         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12761         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12762         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12763         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12764         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12765         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12766         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12767         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12768         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12769
12770         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12771                 PIPE_CONF_CHECK_I(pipe_bpp);
12772
12773         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12774         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12775
12776 #undef PIPE_CONF_CHECK_X
12777 #undef PIPE_CONF_CHECK_I
12778 #undef PIPE_CONF_CHECK_P
12779 #undef PIPE_CONF_CHECK_I_ALT
12780 #undef PIPE_CONF_CHECK_FLAGS
12781 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12782 #undef PIPE_CONF_QUIRK
12783 #undef INTEL_ERR_OR_DBG_KMS
12784
12785         return ret;
12786 }
12787
12788 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12789                                            const struct intel_crtc_state *pipe_config)
12790 {
12791         if (pipe_config->has_pch_encoder) {
12792                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12793                                                             &pipe_config->fdi_m_n);
12794                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12795
12796                 /*
12797                  * FDI already provided one idea for the dotclock.
12798                  * Yell if the encoder disagrees.
12799                  */
12800                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12801                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12802                      fdi_dotclock, dotclock);
12803         }
12804 }
12805
12806 static void check_wm_state(struct drm_device *dev)
12807 {
12808         struct drm_i915_private *dev_priv = dev->dev_private;
12809         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12810         struct intel_crtc *intel_crtc;
12811         int plane;
12812
12813         if (INTEL_INFO(dev)->gen < 9)
12814                 return;
12815
12816         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12817         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12818
12819         for_each_intel_crtc(dev, intel_crtc) {
12820                 struct skl_ddb_entry *hw_entry, *sw_entry;
12821                 const enum pipe pipe = intel_crtc->pipe;
12822
12823                 if (!intel_crtc->active)
12824                         continue;
12825
12826                 /* planes */
12827                 for_each_plane(dev_priv, pipe, plane) {
12828                         hw_entry = &hw_ddb.plane[pipe][plane];
12829                         sw_entry = &sw_ddb->plane[pipe][plane];
12830
12831                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12832                                 continue;
12833
12834                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12835                                   "(expected (%u,%u), found (%u,%u))\n",
12836                                   pipe_name(pipe), plane + 1,
12837                                   sw_entry->start, sw_entry->end,
12838                                   hw_entry->start, hw_entry->end);
12839                 }
12840
12841                 /* cursor */
12842                 hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12843                 sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12844
12845                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12846                         continue;
12847
12848                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12849                           "(expected (%u,%u), found (%u,%u))\n",
12850                           pipe_name(pipe),
12851                           sw_entry->start, sw_entry->end,
12852                           hw_entry->start, hw_entry->end);
12853         }
12854 }
12855
12856 static void
12857 check_connector_state(struct drm_device *dev,
12858                       struct drm_atomic_state *old_state)
12859 {
12860         struct drm_connector_state *old_conn_state;
12861         struct drm_connector *connector;
12862         int i;
12863
12864         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12865                 struct drm_encoder *encoder = connector->encoder;
12866                 struct drm_connector_state *state = connector->state;
12867
12868                 /* This also checks the encoder/connector hw state with the
12869                  * ->get_hw_state callbacks. */
12870                 intel_connector_check_state(to_intel_connector(connector));
12871
12872                 I915_STATE_WARN(state->best_encoder != encoder,
12873                      "connector's atomic encoder doesn't match legacy encoder\n");
12874         }
12875 }
12876
12877 static void
12878 check_encoder_state(struct drm_device *dev)
12879 {
12880         struct intel_encoder *encoder;
12881         struct intel_connector *connector;
12882
12883         for_each_intel_encoder(dev, encoder) {
12884                 bool enabled = false;
12885                 enum pipe pipe;
12886
12887                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12888                               encoder->base.base.id,
12889                               encoder->base.name);
12890
12891                 for_each_intel_connector(dev, connector) {
12892                         if (connector->base.state->best_encoder != &encoder->base)
12893                                 continue;
12894                         enabled = true;
12895
12896                         I915_STATE_WARN(connector->base.state->crtc !=
12897                                         encoder->base.crtc,
12898                              "connector's crtc doesn't match encoder crtc\n");
12899                 }
12900
12901                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12902                      "encoder's enabled state mismatch "
12903                      "(expected %i, found %i)\n",
12904                      !!encoder->base.crtc, enabled);
12905
12906                 if (!encoder->base.crtc) {
12907                         bool active;
12908
12909                         active = encoder->get_hw_state(encoder, &pipe);
12910                         I915_STATE_WARN(active,
12911                              "encoder detached but still enabled on pipe %c.\n",
12912                              pipe_name(pipe));
12913                 }
12914         }
12915 }
12916
12917 static void
12918 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12919 {
12920         struct drm_i915_private *dev_priv = dev->dev_private;
12921         struct intel_encoder *encoder;
12922         struct drm_crtc_state *old_crtc_state;
12923         struct drm_crtc *crtc;
12924         int i;
12925
12926         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12927                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12928                 struct intel_crtc_state *pipe_config, *sw_config;
12929                 bool active;
12930
12931                 if (!needs_modeset(crtc->state) &&
12932                     !to_intel_crtc_state(crtc->state)->update_pipe)
12933                         continue;
12934
12935                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12936                 pipe_config = to_intel_crtc_state(old_crtc_state);
12937                 memset(pipe_config, 0, sizeof(*pipe_config));
12938                 pipe_config->base.crtc = crtc;
12939                 pipe_config->base.state = old_state;
12940
12941                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12942                               crtc->base.id);
12943
12944                 active = dev_priv->display.get_pipe_config(intel_crtc,
12945                                                            pipe_config);
12946
12947                 /* hw state is inconsistent with the pipe quirk */
12948                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12949                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12950                         active = crtc->state->active;
12951
12952                 I915_STATE_WARN(crtc->state->active != active,
12953                      "crtc active state doesn't match with hw state "
12954                      "(expected %i, found %i)\n", crtc->state->active, active);
12955
12956                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12957                      "transitional active state does not match atomic hw state "
12958                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12959
12960                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12961                         enum pipe pipe;
12962
12963                         active = encoder->get_hw_state(encoder, &pipe);
12964                         I915_STATE_WARN(active != crtc->state->active,
12965                                 "[ENCODER:%i] active %i with crtc active %i\n",
12966                                 encoder->base.base.id, active, crtc->state->active);
12967
12968                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12969                                         "Encoder connected to wrong pipe %c\n",
12970                                         pipe_name(pipe));
12971
12972                         if (active)
12973                                 encoder->get_config(encoder, pipe_config);
12974                 }
12975
12976                 if (!crtc->state->active)
12977                         continue;
12978
12979                 intel_pipe_config_sanity_check(dev_priv, pipe_config);
12980
12981                 sw_config = to_intel_crtc_state(crtc->state);
12982                 if (!intel_pipe_config_compare(dev, sw_config,
12983                                                pipe_config, false)) {
12984                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12985                         intel_dump_pipe_config(intel_crtc, pipe_config,
12986                                                "[hw state]");
12987                         intel_dump_pipe_config(intel_crtc, sw_config,
12988                                                "[sw state]");
12989                 }
12990         }
12991 }
12992
12993 static void
12994 check_shared_dpll_state(struct drm_device *dev)
12995 {
12996         struct drm_i915_private *dev_priv = dev->dev_private;
12997         struct intel_crtc *crtc;
12998         struct intel_dpll_hw_state dpll_hw_state;
12999         int i;
13000
13001         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
13002                 struct intel_shared_dpll *pll =
13003                         intel_get_shared_dpll_by_id(dev_priv, i);
13004                 unsigned enabled_crtcs = 0, active_crtcs = 0;
13005                 bool active;
13006
13007                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
13008
13009                 DRM_DEBUG_KMS("%s\n", pll->name);
13010
13011                 active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
13012
13013                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
13014                      "more active pll users than references: %x vs %x\n",
13015                      pll->active_mask, pll->config.crtc_mask);
13016
13017                 if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
13018                         I915_STATE_WARN(!pll->on && pll->active_mask,
13019                              "pll in active use but not on in sw tracking\n");
13020                         I915_STATE_WARN(pll->on && !pll->active_mask,
13021                              "pll is on but not used by any active crtc\n");
13022                         I915_STATE_WARN(pll->on != active,
13023                              "pll on state mismatch (expected %i, found %i)\n",
13024                              pll->on, active);
13025                 }
13026
13027                 for_each_intel_crtc(dev, crtc) {
13028                         if (crtc->base.state->enable && crtc->config->shared_dpll == pll)
13029                                 enabled_crtcs |= 1 << drm_crtc_index(&crtc->base);
13030                         if (crtc->base.state->active && crtc->config->shared_dpll == pll)
13031                                 active_crtcs |= 1 << drm_crtc_index(&crtc->base);
13032                 }
13033
13034                 I915_STATE_WARN(pll->active_mask != active_crtcs,
13035                      "pll active crtcs mismatch (expected %x, found %x)\n",
13036                      pll->active_mask, active_crtcs);
13037                 I915_STATE_WARN(pll->config.crtc_mask != enabled_crtcs,
13038                      "pll enabled crtcs mismatch (expected %x, found %x)\n",
13039                      pll->config.crtc_mask, enabled_crtcs);
13040
13041                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
13042                                        sizeof(dpll_hw_state)),
13043                      "pll hw state mismatch\n");
13044         }
13045 }
13046
13047 static void
13048 intel_modeset_check_state(struct drm_device *dev,
13049                           struct drm_atomic_state *old_state)
13050 {
13051         check_wm_state(dev);
13052         check_connector_state(dev, old_state);
13053         check_encoder_state(dev);
13054         check_crtc_state(dev, old_state);
13055         check_shared_dpll_state(dev);
13056 }
13057
13058 static void update_scanline_offset(struct intel_crtc *crtc)
13059 {
13060         struct drm_device *dev = crtc->base.dev;
13061
13062         /*
13063          * The scanline counter increments at the leading edge of hsync.
13064          *
13065          * On most platforms it starts counting from vtotal-1 on the
13066          * first active line. That means the scanline counter value is
13067          * always one less than what we would expect. Ie. just after
13068          * start of vblank, which also occurs at start of hsync (on the
13069          * last active line), the scanline counter will read vblank_start-1.
13070          *
13071          * On gen2 the scanline counter starts counting from 1 instead
13072          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13073          * to keep the value positive), instead of adding one.
13074          *
13075          * On HSW+ the behaviour of the scanline counter depends on the output
13076          * type. For DP ports it behaves like most other platforms, but on HDMI
13077          * there's an extra 1 line difference. So we need to add two instead of
13078          * one to the value.
13079          */
13080         if (IS_GEN2(dev)) {
13081                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13082                 int vtotal;
13083
13084                 vtotal = adjusted_mode->crtc_vtotal;
13085                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13086                         vtotal /= 2;
13087
13088                 crtc->scanline_offset = vtotal - 1;
13089         } else if (HAS_DDI(dev) &&
13090                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13091                 crtc->scanline_offset = 2;
13092         } else
13093                 crtc->scanline_offset = 1;
13094 }
13095
13096 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13097 {
13098         struct drm_device *dev = state->dev;
13099         struct drm_i915_private *dev_priv = to_i915(dev);
13100         struct intel_shared_dpll_config *shared_dpll = NULL;
13101         struct drm_crtc *crtc;
13102         struct drm_crtc_state *crtc_state;
13103         int i;
13104
13105         if (!dev_priv->display.crtc_compute_clock)
13106                 return;
13107
13108         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13109                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13110                 struct intel_shared_dpll *old_dpll =
13111                         to_intel_crtc_state(crtc->state)->shared_dpll;
13112
13113                 if (!needs_modeset(crtc_state))
13114                         continue;
13115
13116                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13117
13118                 if (!old_dpll)
13119                         continue;
13120
13121                 if (!shared_dpll)
13122                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13123
13124                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13125         }
13126 }
13127
13128 /*
13129  * This implements the workaround described in the "notes" section of the mode
13130  * set sequence documentation. When going from no pipes or single pipe to
13131  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13132  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13133  */
13134 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13135 {
13136         struct drm_crtc_state *crtc_state;
13137         struct intel_crtc *intel_crtc;
13138         struct drm_crtc *crtc;
13139         struct intel_crtc_state *first_crtc_state = NULL;
13140         struct intel_crtc_state *other_crtc_state = NULL;
13141         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13142         int i;
13143
13144         /* look at all crtc's that are going to be enabled in during modeset */
13145         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13146                 intel_crtc = to_intel_crtc(crtc);
13147
13148                 if (!crtc_state->active || !needs_modeset(crtc_state))
13149                         continue;
13150
13151                 if (first_crtc_state) {
13152                         other_crtc_state = to_intel_crtc_state(crtc_state);
13153                         break;
13154                 } else {
13155                         first_crtc_state = to_intel_crtc_state(crtc_state);
13156                         first_pipe = intel_crtc->pipe;
13157                 }
13158         }
13159
13160         /* No workaround needed? */
13161         if (!first_crtc_state)
13162                 return 0;
13163
13164         /* w/a possibly needed, check how many crtc's are already enabled. */
13165         for_each_intel_crtc(state->dev, intel_crtc) {
13166                 struct intel_crtc_state *pipe_config;
13167
13168                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13169                 if (IS_ERR(pipe_config))
13170                         return PTR_ERR(pipe_config);
13171
13172                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13173
13174                 if (!pipe_config->base.active ||
13175                     needs_modeset(&pipe_config->base))
13176                         continue;
13177
13178                 /* 2 or more enabled crtcs means no need for w/a */
13179                 if (enabled_pipe != INVALID_PIPE)
13180                         return 0;
13181
13182                 enabled_pipe = intel_crtc->pipe;
13183         }
13184
13185         if (enabled_pipe != INVALID_PIPE)
13186                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13187         else if (other_crtc_state)
13188                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13189
13190         return 0;
13191 }
13192
13193 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13194 {
13195         struct drm_crtc *crtc;
13196         struct drm_crtc_state *crtc_state;
13197         int ret = 0;
13198
13199         /* add all active pipes to the state */
13200         for_each_crtc(state->dev, crtc) {
13201                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13202                 if (IS_ERR(crtc_state))
13203                         return PTR_ERR(crtc_state);
13204
13205                 if (!crtc_state->active || needs_modeset(crtc_state))
13206                         continue;
13207
13208                 crtc_state->mode_changed = true;
13209
13210                 ret = drm_atomic_add_affected_connectors(state, crtc);
13211                 if (ret)
13212                         break;
13213
13214                 ret = drm_atomic_add_affected_planes(state, crtc);
13215                 if (ret)
13216                         break;
13217         }
13218
13219         return ret;
13220 }
13221
13222 static int intel_modeset_checks(struct drm_atomic_state *state)
13223 {
13224         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13225         struct drm_i915_private *dev_priv = state->dev->dev_private;
13226         struct drm_crtc *crtc;
13227         struct drm_crtc_state *crtc_state;
13228         int ret = 0, i;
13229
13230         if (!check_digital_port_conflicts(state)) {
13231                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13232                 return -EINVAL;
13233         }
13234
13235         intel_state->modeset = true;
13236         intel_state->active_crtcs = dev_priv->active_crtcs;
13237
13238         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13239                 if (crtc_state->active)
13240                         intel_state->active_crtcs |= 1 << i;
13241                 else
13242                         intel_state->active_crtcs &= ~(1 << i);
13243         }
13244
13245         /*
13246          * See if the config requires any additional preparation, e.g.
13247          * to adjust global state with pipes off.  We need to do this
13248          * here so we can get the modeset_pipe updated config for the new
13249          * mode set on this crtc.  For other crtcs we need to use the
13250          * adjusted_mode bits in the crtc directly.
13251          */
13252         if (dev_priv->display.modeset_calc_cdclk) {
13253                 ret = dev_priv->display.modeset_calc_cdclk(state);
13254
13255                 if (!ret && intel_state->dev_cdclk != dev_priv->cdclk_freq)
13256                         ret = intel_modeset_all_pipes(state);
13257
13258                 if (ret < 0)
13259                         return ret;
13260
13261                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13262                               intel_state->cdclk, intel_state->dev_cdclk);
13263         } else
13264                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13265
13266         intel_modeset_clear_plls(state);
13267
13268         if (IS_HASWELL(dev_priv))
13269                 return haswell_mode_set_planes_workaround(state);
13270
13271         return 0;
13272 }
13273
13274 /*
13275  * Handle calculation of various watermark data at the end of the atomic check
13276  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13277  * handlers to ensure that all derived state has been updated.
13278  */
13279 static void calc_watermark_data(struct drm_atomic_state *state)
13280 {
13281         struct drm_device *dev = state->dev;
13282         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13283         struct drm_crtc *crtc;
13284         struct drm_crtc_state *cstate;
13285         struct drm_plane *plane;
13286         struct drm_plane_state *pstate;
13287
13288         /*
13289          * Calculate watermark configuration details now that derived
13290          * plane/crtc state is all properly updated.
13291          */
13292         drm_for_each_crtc(crtc, dev) {
13293                 cstate = drm_atomic_get_existing_crtc_state(state, crtc) ?:
13294                         crtc->state;
13295
13296                 if (cstate->active)
13297                         intel_state->wm_config.num_pipes_active++;
13298         }
13299         drm_for_each_legacy_plane(plane, dev) {
13300                 pstate = drm_atomic_get_existing_plane_state(state, plane) ?:
13301                         plane->state;
13302
13303                 if (!to_intel_plane_state(pstate)->visible)
13304                         continue;
13305
13306                 intel_state->wm_config.sprites_enabled = true;
13307                 if (pstate->crtc_w != pstate->src_w >> 16 ||
13308                     pstate->crtc_h != pstate->src_h >> 16)
13309                         intel_state->wm_config.sprites_scaled = true;
13310         }
13311 }
13312
13313 /**
13314  * intel_atomic_check - validate state object
13315  * @dev: drm device
13316  * @state: state to validate
13317  */
13318 static int intel_atomic_check(struct drm_device *dev,
13319                               struct drm_atomic_state *state)
13320 {
13321         struct drm_i915_private *dev_priv = to_i915(dev);
13322         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13323         struct drm_crtc *crtc;
13324         struct drm_crtc_state *crtc_state;
13325         int ret, i;
13326         bool any_ms = false;
13327
13328         ret = drm_atomic_helper_check_modeset(dev, state);
13329         if (ret)
13330                 return ret;
13331
13332         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13333                 struct intel_crtc_state *pipe_config =
13334                         to_intel_crtc_state(crtc_state);
13335
13336                 /* Catch I915_MODE_FLAG_INHERITED */
13337                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13338                         crtc_state->mode_changed = true;
13339
13340                 if (!crtc_state->enable) {
13341                         if (needs_modeset(crtc_state))
13342                                 any_ms = true;
13343                         continue;
13344                 }
13345
13346                 if (!needs_modeset(crtc_state))
13347                         continue;
13348
13349                 /* FIXME: For only active_changed we shouldn't need to do any
13350                  * state recomputation at all. */
13351
13352                 ret = drm_atomic_add_affected_connectors(state, crtc);
13353                 if (ret)
13354                         return ret;
13355
13356                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13357                 if (ret)
13358                         return ret;
13359
13360                 if (i915.fastboot &&
13361                     intel_pipe_config_compare(dev,
13362                                         to_intel_crtc_state(crtc->state),
13363                                         pipe_config, true)) {
13364                         crtc_state->mode_changed = false;
13365                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13366                 }
13367
13368                 if (needs_modeset(crtc_state)) {
13369                         any_ms = true;
13370
13371                         ret = drm_atomic_add_affected_planes(state, crtc);
13372                         if (ret)
13373                                 return ret;
13374                 }
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         calc_watermark_data(state);
13395
13396         return 0;
13397 }
13398
13399 static int intel_atomic_prepare_commit(struct drm_device *dev,
13400                                        struct drm_atomic_state *state,
13401                                        bool async)
13402 {
13403         struct drm_i915_private *dev_priv = dev->dev_private;
13404         struct drm_plane_state *plane_state;
13405         struct drm_crtc_state *crtc_state;
13406         struct drm_plane *plane;
13407         struct drm_crtc *crtc;
13408         int i, ret;
13409
13410         if (async) {
13411                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13412                 return -EINVAL;
13413         }
13414
13415         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13416                 ret = intel_crtc_wait_for_pending_flips(crtc);
13417                 if (ret)
13418                         return ret;
13419
13420                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13421                         flush_workqueue(dev_priv->wq);
13422         }
13423
13424         ret = mutex_lock_interruptible(&dev->struct_mutex);
13425         if (ret)
13426                 return ret;
13427
13428         ret = drm_atomic_helper_prepare_planes(dev, state);
13429         if (!ret && !async && !i915_reset_in_progress(&dev_priv->gpu_error)) {
13430                 u32 reset_counter;
13431
13432                 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
13433                 mutex_unlock(&dev->struct_mutex);
13434
13435                 for_each_plane_in_state(state, plane, plane_state, i) {
13436                         struct intel_plane_state *intel_plane_state =
13437                                 to_intel_plane_state(plane_state);
13438
13439                         if (!intel_plane_state->wait_req)
13440                                 continue;
13441
13442                         ret = __i915_wait_request(intel_plane_state->wait_req,
13443                                                   reset_counter, true,
13444                                                   NULL, NULL);
13445
13446                         /* Swallow -EIO errors to allow updates during hw lockup. */
13447                         if (ret == -EIO)
13448                                 ret = 0;
13449
13450                         if (ret)
13451                                 break;
13452                 }
13453
13454                 if (!ret)
13455                         return 0;
13456
13457                 mutex_lock(&dev->struct_mutex);
13458                 drm_atomic_helper_cleanup_planes(dev, state);
13459         }
13460
13461         mutex_unlock(&dev->struct_mutex);
13462         return ret;
13463 }
13464
13465 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13466                                           struct drm_i915_private *dev_priv,
13467                                           unsigned crtc_mask)
13468 {
13469         unsigned last_vblank_count[I915_MAX_PIPES];
13470         enum pipe pipe;
13471         int ret;
13472
13473         if (!crtc_mask)
13474                 return;
13475
13476         for_each_pipe(dev_priv, pipe) {
13477                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13478
13479                 if (!((1 << pipe) & crtc_mask))
13480                         continue;
13481
13482                 ret = drm_crtc_vblank_get(crtc);
13483                 if (WARN_ON(ret != 0)) {
13484                         crtc_mask &= ~(1 << pipe);
13485                         continue;
13486                 }
13487
13488                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13489         }
13490
13491         for_each_pipe(dev_priv, pipe) {
13492                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13493                 long lret;
13494
13495                 if (!((1 << pipe) & crtc_mask))
13496                         continue;
13497
13498                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13499                                 last_vblank_count[pipe] !=
13500                                         drm_crtc_vblank_count(crtc),
13501                                 msecs_to_jiffies(50));
13502
13503                 WARN_ON(!lret);
13504
13505                 drm_crtc_vblank_put(crtc);
13506         }
13507 }
13508
13509 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13510 {
13511         /* fb updated, need to unpin old fb */
13512         if (crtc_state->fb_changed)
13513                 return true;
13514
13515         /* wm changes, need vblank before final wm's */
13516         if (crtc_state->update_wm_post)
13517                 return true;
13518
13519         /*
13520          * cxsr is re-enabled after vblank.
13521          * This is already handled by crtc_state->update_wm_post,
13522          * but added for clarity.
13523          */
13524         if (crtc_state->disable_cxsr)
13525                 return true;
13526
13527         return false;
13528 }
13529
13530 /**
13531  * intel_atomic_commit - commit validated state object
13532  * @dev: DRM device
13533  * @state: the top-level driver state object
13534  * @async: asynchronous commit
13535  *
13536  * This function commits a top-level state object that has been validated
13537  * with drm_atomic_helper_check().
13538  *
13539  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13540  * we can only handle plane-related operations and do not yet support
13541  * asynchronous commit.
13542  *
13543  * RETURNS
13544  * Zero for success or -errno.
13545  */
13546 static int intel_atomic_commit(struct drm_device *dev,
13547                                struct drm_atomic_state *state,
13548                                bool async)
13549 {
13550         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13551         struct drm_i915_private *dev_priv = dev->dev_private;
13552         struct drm_crtc_state *old_crtc_state;
13553         struct drm_crtc *crtc;
13554         struct intel_crtc_state *intel_cstate;
13555         int ret = 0, i;
13556         bool hw_check = intel_state->modeset;
13557         unsigned long put_domains[I915_MAX_PIPES] = {};
13558         unsigned crtc_vblank_mask = 0;
13559
13560         ret = intel_atomic_prepare_commit(dev, state, async);
13561         if (ret) {
13562                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13563                 return ret;
13564         }
13565
13566         drm_atomic_helper_swap_state(dev, state);
13567         dev_priv->wm.config = intel_state->wm_config;
13568         intel_shared_dpll_commit(state);
13569
13570         if (intel_state->modeset) {
13571                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13572                        sizeof(intel_state->min_pixclk));
13573                 dev_priv->active_crtcs = intel_state->active_crtcs;
13574                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13575
13576                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13577         }
13578
13579         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13580                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13581
13582                 if (needs_modeset(crtc->state) ||
13583                     to_intel_crtc_state(crtc->state)->update_pipe) {
13584                         hw_check = true;
13585
13586                         put_domains[to_intel_crtc(crtc)->pipe] =
13587                                 modeset_get_crtc_power_domains(crtc,
13588                                         to_intel_crtc_state(crtc->state));
13589                 }
13590
13591                 if (!needs_modeset(crtc->state))
13592                         continue;
13593
13594                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13595
13596                 if (old_crtc_state->active) {
13597                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13598                         dev_priv->display.crtc_disable(crtc);
13599                         intel_crtc->active = false;
13600                         intel_fbc_disable(intel_crtc);
13601                         intel_disable_shared_dpll(intel_crtc);
13602
13603                         /*
13604                          * Underruns don't always raise
13605                          * interrupts, so check manually.
13606                          */
13607                         intel_check_cpu_fifo_underruns(dev_priv);
13608                         intel_check_pch_fifo_underruns(dev_priv);
13609
13610                         if (!crtc->state->active)
13611                                 intel_update_watermarks(crtc);
13612                 }
13613         }
13614
13615         /* Only after disabling all output pipelines that will be changed can we
13616          * update the the output configuration. */
13617         intel_modeset_update_crtc_state(state);
13618
13619         if (intel_state->modeset) {
13620                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13621
13622                 if (dev_priv->display.modeset_commit_cdclk &&
13623                     intel_state->dev_cdclk != dev_priv->cdclk_freq)
13624                         dev_priv->display.modeset_commit_cdclk(state);
13625         }
13626
13627         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13628         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13629                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13630                 bool modeset = needs_modeset(crtc->state);
13631                 struct intel_crtc_state *pipe_config =
13632                         to_intel_crtc_state(crtc->state);
13633                 bool update_pipe = !modeset && pipe_config->update_pipe;
13634
13635                 if (modeset && crtc->state->active) {
13636                         update_scanline_offset(to_intel_crtc(crtc));
13637                         dev_priv->display.crtc_enable(crtc);
13638                 }
13639
13640                 if (!modeset)
13641                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13642
13643                 if (crtc->state->active &&
13644                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13645                         intel_fbc_enable(intel_crtc);
13646
13647                 if (crtc->state->active &&
13648                     (crtc->state->planes_changed || update_pipe))
13649                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13650
13651                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13652                         crtc_vblank_mask |= 1 << i;
13653         }
13654
13655         /* FIXME: add subpixel order */
13656
13657         if (!state->legacy_cursor_update)
13658                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13659
13660         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13661                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13662
13663                 if (put_domains[i])
13664                         modeset_put_power_domains(dev_priv, put_domains[i]);
13665         }
13666
13667         if (intel_state->modeset)
13668                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13669
13670         /*
13671          * Now that the vblank has passed, we can go ahead and program the
13672          * optimal watermarks on platforms that need two-step watermark
13673          * programming.
13674          *
13675          * TODO: Move this (and other cleanup) to an async worker eventually.
13676          */
13677         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13678                 intel_cstate = to_intel_crtc_state(crtc->state);
13679
13680                 if (dev_priv->display.optimize_watermarks)
13681                         dev_priv->display.optimize_watermarks(intel_cstate);
13682         }
13683
13684         mutex_lock(&dev->struct_mutex);
13685         drm_atomic_helper_cleanup_planes(dev, state);
13686         mutex_unlock(&dev->struct_mutex);
13687
13688         if (hw_check)
13689                 intel_modeset_check_state(dev, state);
13690
13691         drm_atomic_state_free(state);
13692
13693         /* As one of the primary mmio accessors, KMS has a high likelihood
13694          * of triggering bugs in unclaimed access. After we finish
13695          * modesetting, see if an error has been flagged, and if so
13696          * enable debugging for the next modeset - and hope we catch
13697          * the culprit.
13698          *
13699          * XXX note that we assume display power is on at this point.
13700          * This might hold true now but we need to add pm helper to check
13701          * unclaimed only when the hardware is on, as atomic commits
13702          * can happen also when the device is completely off.
13703          */
13704         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13705
13706         return 0;
13707 }
13708
13709 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13710 {
13711         struct drm_device *dev = crtc->dev;
13712         struct drm_atomic_state *state;
13713         struct drm_crtc_state *crtc_state;
13714         int ret;
13715
13716         state = drm_atomic_state_alloc(dev);
13717         if (!state) {
13718                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13719                               crtc->base.id);
13720                 return;
13721         }
13722
13723         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13724
13725 retry:
13726         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13727         ret = PTR_ERR_OR_ZERO(crtc_state);
13728         if (!ret) {
13729                 if (!crtc_state->active)
13730                         goto out;
13731
13732                 crtc_state->mode_changed = true;
13733                 ret = drm_atomic_commit(state);
13734         }
13735
13736         if (ret == -EDEADLK) {
13737                 drm_atomic_state_clear(state);
13738                 drm_modeset_backoff(state->acquire_ctx);
13739                 goto retry;
13740         }
13741
13742         if (ret)
13743 out:
13744                 drm_atomic_state_free(state);
13745 }
13746
13747 #undef for_each_intel_crtc_masked
13748
13749 static const struct drm_crtc_funcs intel_crtc_funcs = {
13750         .gamma_set = intel_crtc_gamma_set,
13751         .set_config = drm_atomic_helper_set_config,
13752         .destroy = intel_crtc_destroy,
13753         .page_flip = intel_crtc_page_flip,
13754         .atomic_duplicate_state = intel_crtc_duplicate_state,
13755         .atomic_destroy_state = intel_crtc_destroy_state,
13756 };
13757
13758 /**
13759  * intel_prepare_plane_fb - Prepare fb for usage on plane
13760  * @plane: drm plane to prepare for
13761  * @fb: framebuffer to prepare for presentation
13762  *
13763  * Prepares a framebuffer for usage on a display plane.  Generally this
13764  * involves pinning the underlying object and updating the frontbuffer tracking
13765  * bits.  Some older platforms need special physical address handling for
13766  * cursor planes.
13767  *
13768  * Must be called with struct_mutex held.
13769  *
13770  * Returns 0 on success, negative error code on failure.
13771  */
13772 int
13773 intel_prepare_plane_fb(struct drm_plane *plane,
13774                        const struct drm_plane_state *new_state)
13775 {
13776         struct drm_device *dev = plane->dev;
13777         struct drm_framebuffer *fb = new_state->fb;
13778         struct intel_plane *intel_plane = to_intel_plane(plane);
13779         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13780         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13781         int ret = 0;
13782
13783         if (!obj && !old_obj)
13784                 return 0;
13785
13786         if (old_obj) {
13787                 struct drm_crtc_state *crtc_state =
13788                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13789
13790                 /* Big Hammer, we also need to ensure that any pending
13791                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13792                  * current scanout is retired before unpinning the old
13793                  * framebuffer. Note that we rely on userspace rendering
13794                  * into the buffer attached to the pipe they are waiting
13795                  * on. If not, userspace generates a GPU hang with IPEHR
13796                  * point to the MI_WAIT_FOR_EVENT.
13797                  *
13798                  * This should only fail upon a hung GPU, in which case we
13799                  * can safely continue.
13800                  */
13801                 if (needs_modeset(crtc_state))
13802                         ret = i915_gem_object_wait_rendering(old_obj, true);
13803
13804                 /* Swallow -EIO errors to allow updates during hw lockup. */
13805                 if (ret && ret != -EIO)
13806                         return ret;
13807         }
13808
13809         /* For framebuffer backed by dmabuf, wait for fence */
13810         if (obj && obj->base.dma_buf) {
13811                 long lret;
13812
13813                 lret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
13814                                                            false, true,
13815                                                            MAX_SCHEDULE_TIMEOUT);
13816                 if (lret == -ERESTARTSYS)
13817                         return lret;
13818
13819                 WARN(lret < 0, "waiting returns %li\n", lret);
13820         }
13821
13822         if (!obj) {
13823                 ret = 0;
13824         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13825             INTEL_INFO(dev)->cursor_needs_physical) {
13826                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13827                 ret = i915_gem_object_attach_phys(obj, align);
13828                 if (ret)
13829                         DRM_DEBUG_KMS("failed to attach phys object\n");
13830         } else {
13831                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13832         }
13833
13834         if (ret == 0) {
13835                 if (obj) {
13836                         struct intel_plane_state *plane_state =
13837                                 to_intel_plane_state(new_state);
13838
13839                         i915_gem_request_assign(&plane_state->wait_req,
13840                                                 obj->last_write_req);
13841                 }
13842
13843                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13844         }
13845
13846         return ret;
13847 }
13848
13849 /**
13850  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13851  * @plane: drm plane to clean up for
13852  * @fb: old framebuffer that was on plane
13853  *
13854  * Cleans up a framebuffer that has just been removed from a plane.
13855  *
13856  * Must be called with struct_mutex held.
13857  */
13858 void
13859 intel_cleanup_plane_fb(struct drm_plane *plane,
13860                        const struct drm_plane_state *old_state)
13861 {
13862         struct drm_device *dev = plane->dev;
13863         struct intel_plane *intel_plane = to_intel_plane(plane);
13864         struct intel_plane_state *old_intel_state;
13865         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
13866         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
13867
13868         old_intel_state = to_intel_plane_state(old_state);
13869
13870         if (!obj && !old_obj)
13871                 return;
13872
13873         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
13874             !INTEL_INFO(dev)->cursor_needs_physical))
13875                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
13876
13877         /* prepare_fb aborted? */
13878         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
13879             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
13880                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13881
13882         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
13883 }
13884
13885 int
13886 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13887 {
13888         int max_scale;
13889         struct drm_device *dev;
13890         struct drm_i915_private *dev_priv;
13891         int crtc_clock, cdclk;
13892
13893         if (!intel_crtc || !crtc_state->base.enable)
13894                 return DRM_PLANE_HELPER_NO_SCALING;
13895
13896         dev = intel_crtc->base.dev;
13897         dev_priv = dev->dev_private;
13898         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13899         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13900
13901         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
13902                 return DRM_PLANE_HELPER_NO_SCALING;
13903
13904         /*
13905          * skl max scale is lower of:
13906          *    close to 3 but not 3, -1 is for that purpose
13907          *            or
13908          *    cdclk/crtc_clock
13909          */
13910         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13911
13912         return max_scale;
13913 }
13914
13915 static int
13916 intel_check_primary_plane(struct drm_plane *plane,
13917                           struct intel_crtc_state *crtc_state,
13918                           struct intel_plane_state *state)
13919 {
13920         struct drm_crtc *crtc = state->base.crtc;
13921         struct drm_framebuffer *fb = state->base.fb;
13922         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13923         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13924         bool can_position = false;
13925
13926         if (INTEL_INFO(plane->dev)->gen >= 9) {
13927                 /* use scaler when colorkey is not required */
13928                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13929                         min_scale = 1;
13930                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13931                 }
13932                 can_position = true;
13933         }
13934
13935         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13936                                              &state->dst, &state->clip,
13937                                              min_scale, max_scale,
13938                                              can_position, true,
13939                                              &state->visible);
13940 }
13941
13942 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13943                                     struct drm_crtc_state *old_crtc_state)
13944 {
13945         struct drm_device *dev = crtc->dev;
13946         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13947         struct intel_crtc_state *old_intel_state =
13948                 to_intel_crtc_state(old_crtc_state);
13949         bool modeset = needs_modeset(crtc->state);
13950
13951         /* Perform vblank evasion around commit operation */
13952         intel_pipe_update_start(intel_crtc);
13953
13954         if (modeset)
13955                 return;
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;
14001         struct intel_plane_state *state;
14002         const uint32_t *intel_primary_formats;
14003         unsigned int num_formats;
14004
14005         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
14006         if (primary == NULL)
14007                 return NULL;
14008
14009         state = intel_create_plane_state(&primary->base);
14010         if (!state) {
14011                 kfree(primary);
14012                 return NULL;
14013         }
14014         primary->base.state = &state->base;
14015
14016         primary->can_scale = false;
14017         primary->max_downscale = 1;
14018         if (INTEL_INFO(dev)->gen >= 9) {
14019                 primary->can_scale = true;
14020                 state->scaler_id = -1;
14021         }
14022         primary->pipe = pipe;
14023         primary->plane = pipe;
14024         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
14025         primary->check_plane = intel_check_primary_plane;
14026         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14027                 primary->plane = !pipe;
14028
14029         if (INTEL_INFO(dev)->gen >= 9) {
14030                 intel_primary_formats = skl_primary_formats;
14031                 num_formats = ARRAY_SIZE(skl_primary_formats);
14032
14033                 primary->update_plane = skylake_update_primary_plane;
14034                 primary->disable_plane = skylake_disable_primary_plane;
14035         } else if (HAS_PCH_SPLIT(dev)) {
14036                 intel_primary_formats = i965_primary_formats;
14037                 num_formats = ARRAY_SIZE(i965_primary_formats);
14038
14039                 primary->update_plane = ironlake_update_primary_plane;
14040                 primary->disable_plane = i9xx_disable_primary_plane;
14041         } else if (INTEL_INFO(dev)->gen >= 4) {
14042                 intel_primary_formats = i965_primary_formats;
14043                 num_formats = ARRAY_SIZE(i965_primary_formats);
14044
14045                 primary->update_plane = i9xx_update_primary_plane;
14046                 primary->disable_plane = i9xx_disable_primary_plane;
14047         } else {
14048                 intel_primary_formats = i8xx_primary_formats;
14049                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14050
14051                 primary->update_plane = i9xx_update_primary_plane;
14052                 primary->disable_plane = i9xx_disable_primary_plane;
14053         }
14054
14055         drm_universal_plane_init(dev, &primary->base, 0,
14056                                  &intel_plane_funcs,
14057                                  intel_primary_formats, num_formats,
14058                                  DRM_PLANE_TYPE_PRIMARY, NULL);
14059
14060         if (INTEL_INFO(dev)->gen >= 4)
14061                 intel_create_rotation_property(dev, primary);
14062
14063         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14064
14065         return &primary->base;
14066 }
14067
14068 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14069 {
14070         if (!dev->mode_config.rotation_property) {
14071                 unsigned long flags = BIT(DRM_ROTATE_0) |
14072                         BIT(DRM_ROTATE_180);
14073
14074                 if (INTEL_INFO(dev)->gen >= 9)
14075                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14076
14077                 dev->mode_config.rotation_property =
14078                         drm_mode_create_rotation_property(dev, flags);
14079         }
14080         if (dev->mode_config.rotation_property)
14081                 drm_object_attach_property(&plane->base.base,
14082                                 dev->mode_config.rotation_property,
14083                                 plane->base.state->rotation);
14084 }
14085
14086 static int
14087 intel_check_cursor_plane(struct drm_plane *plane,
14088                          struct intel_crtc_state *crtc_state,
14089                          struct intel_plane_state *state)
14090 {
14091         struct drm_crtc *crtc = crtc_state->base.crtc;
14092         struct drm_framebuffer *fb = state->base.fb;
14093         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14094         enum pipe pipe = to_intel_plane(plane)->pipe;
14095         unsigned stride;
14096         int ret;
14097
14098         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14099                                             &state->dst, &state->clip,
14100                                             DRM_PLANE_HELPER_NO_SCALING,
14101                                             DRM_PLANE_HELPER_NO_SCALING,
14102                                             true, true, &state->visible);
14103         if (ret)
14104                 return ret;
14105
14106         /* if we want to turn off the cursor ignore width and height */
14107         if (!obj)
14108                 return 0;
14109
14110         /* Check for which cursor types we support */
14111         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14112                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14113                           state->base.crtc_w, state->base.crtc_h);
14114                 return -EINVAL;
14115         }
14116
14117         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14118         if (obj->base.size < stride * state->base.crtc_h) {
14119                 DRM_DEBUG_KMS("buffer is too small\n");
14120                 return -ENOMEM;
14121         }
14122
14123         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14124                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14125                 return -EINVAL;
14126         }
14127
14128         /*
14129          * There's something wrong with the cursor on CHV pipe C.
14130          * If it straddles the left edge of the screen then
14131          * moving it away from the edge or disabling it often
14132          * results in a pipe underrun, and often that can lead to
14133          * dead pipe (constant underrun reported, and it scans
14134          * out just a solid color). To recover from that, the
14135          * display power well must be turned off and on again.
14136          * Refuse the put the cursor into that compromised position.
14137          */
14138         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14139             state->visible && state->base.crtc_x < 0) {
14140                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14141                 return -EINVAL;
14142         }
14143
14144         return 0;
14145 }
14146
14147 static void
14148 intel_disable_cursor_plane(struct drm_plane *plane,
14149                            struct drm_crtc *crtc)
14150 {
14151         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14152
14153         intel_crtc->cursor_addr = 0;
14154         intel_crtc_update_cursor(crtc, NULL);
14155 }
14156
14157 static void
14158 intel_update_cursor_plane(struct drm_plane *plane,
14159                           const struct intel_crtc_state *crtc_state,
14160                           const struct intel_plane_state *state)
14161 {
14162         struct drm_crtc *crtc = crtc_state->base.crtc;
14163         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14164         struct drm_device *dev = plane->dev;
14165         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14166         uint32_t addr;
14167
14168         if (!obj)
14169                 addr = 0;
14170         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14171                 addr = i915_gem_obj_ggtt_offset(obj);
14172         else
14173                 addr = obj->phys_handle->busaddr;
14174
14175         intel_crtc->cursor_addr = addr;
14176         intel_crtc_update_cursor(crtc, state);
14177 }
14178
14179 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14180                                                    int pipe)
14181 {
14182         struct intel_plane *cursor;
14183         struct intel_plane_state *state;
14184
14185         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14186         if (cursor == NULL)
14187                 return NULL;
14188
14189         state = intel_create_plane_state(&cursor->base);
14190         if (!state) {
14191                 kfree(cursor);
14192                 return NULL;
14193         }
14194         cursor->base.state = &state->base;
14195
14196         cursor->can_scale = false;
14197         cursor->max_downscale = 1;
14198         cursor->pipe = pipe;
14199         cursor->plane = pipe;
14200         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14201         cursor->check_plane = intel_check_cursor_plane;
14202         cursor->update_plane = intel_update_cursor_plane;
14203         cursor->disable_plane = intel_disable_cursor_plane;
14204
14205         drm_universal_plane_init(dev, &cursor->base, 0,
14206                                  &intel_plane_funcs,
14207                                  intel_cursor_formats,
14208                                  ARRAY_SIZE(intel_cursor_formats),
14209                                  DRM_PLANE_TYPE_CURSOR, NULL);
14210
14211         if (INTEL_INFO(dev)->gen >= 4) {
14212                 if (!dev->mode_config.rotation_property)
14213                         dev->mode_config.rotation_property =
14214                                 drm_mode_create_rotation_property(dev,
14215                                                         BIT(DRM_ROTATE_0) |
14216                                                         BIT(DRM_ROTATE_180));
14217                 if (dev->mode_config.rotation_property)
14218                         drm_object_attach_property(&cursor->base.base,
14219                                 dev->mode_config.rotation_property,
14220                                 state->base.rotation);
14221         }
14222
14223         if (INTEL_INFO(dev)->gen >=9)
14224                 state->scaler_id = -1;
14225
14226         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14227
14228         return &cursor->base;
14229 }
14230
14231 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14232         struct intel_crtc_state *crtc_state)
14233 {
14234         int i;
14235         struct intel_scaler *intel_scaler;
14236         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14237
14238         for (i = 0; i < intel_crtc->num_scalers; i++) {
14239                 intel_scaler = &scaler_state->scalers[i];
14240                 intel_scaler->in_use = 0;
14241                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14242         }
14243
14244         scaler_state->scaler_id = -1;
14245 }
14246
14247 static void intel_crtc_init(struct drm_device *dev, int pipe)
14248 {
14249         struct drm_i915_private *dev_priv = dev->dev_private;
14250         struct intel_crtc *intel_crtc;
14251         struct intel_crtc_state *crtc_state = NULL;
14252         struct drm_plane *primary = NULL;
14253         struct drm_plane *cursor = NULL;
14254         int i, ret;
14255
14256         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14257         if (intel_crtc == NULL)
14258                 return;
14259
14260         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14261         if (!crtc_state)
14262                 goto fail;
14263         intel_crtc->config = crtc_state;
14264         intel_crtc->base.state = &crtc_state->base;
14265         crtc_state->base.crtc = &intel_crtc->base;
14266
14267         /* initialize shared scalers */
14268         if (INTEL_INFO(dev)->gen >= 9) {
14269                 if (pipe == PIPE_C)
14270                         intel_crtc->num_scalers = 1;
14271                 else
14272                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14273
14274                 skl_init_scalers(dev, intel_crtc, crtc_state);
14275         }
14276
14277         primary = intel_primary_plane_create(dev, pipe);
14278         if (!primary)
14279                 goto fail;
14280
14281         cursor = intel_cursor_plane_create(dev, pipe);
14282         if (!cursor)
14283                 goto fail;
14284
14285         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14286                                         cursor, &intel_crtc_funcs, NULL);
14287         if (ret)
14288                 goto fail;
14289
14290         drm_mode_crtc_set_gamma_size(&intel_crtc->base, 256);
14291         for (i = 0; i < 256; i++) {
14292                 intel_crtc->lut_r[i] = i;
14293                 intel_crtc->lut_g[i] = i;
14294                 intel_crtc->lut_b[i] = i;
14295         }
14296
14297         /*
14298          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14299          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14300          */
14301         intel_crtc->pipe = pipe;
14302         intel_crtc->plane = pipe;
14303         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14304                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14305                 intel_crtc->plane = !pipe;
14306         }
14307
14308         intel_crtc->cursor_base = ~0;
14309         intel_crtc->cursor_cntl = ~0;
14310         intel_crtc->cursor_size = ~0;
14311
14312         intel_crtc->wm.cxsr_allowed = true;
14313
14314         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14315                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14316         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14317         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14318
14319         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14320
14321         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14322         return;
14323
14324 fail:
14325         if (primary)
14326                 drm_plane_cleanup(primary);
14327         if (cursor)
14328                 drm_plane_cleanup(cursor);
14329         kfree(crtc_state);
14330         kfree(intel_crtc);
14331 }
14332
14333 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14334 {
14335         struct drm_encoder *encoder = connector->base.encoder;
14336         struct drm_device *dev = connector->base.dev;
14337
14338         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14339
14340         if (!encoder || WARN_ON(!encoder->crtc))
14341                 return INVALID_PIPE;
14342
14343         return to_intel_crtc(encoder->crtc)->pipe;
14344 }
14345
14346 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14347                                 struct drm_file *file)
14348 {
14349         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14350         struct drm_crtc *drmmode_crtc;
14351         struct intel_crtc *crtc;
14352
14353         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14354
14355         if (!drmmode_crtc) {
14356                 DRM_ERROR("no such CRTC id\n");
14357                 return -ENOENT;
14358         }
14359
14360         crtc = to_intel_crtc(drmmode_crtc);
14361         pipe_from_crtc_id->pipe = crtc->pipe;
14362
14363         return 0;
14364 }
14365
14366 static int intel_encoder_clones(struct intel_encoder *encoder)
14367 {
14368         struct drm_device *dev = encoder->base.dev;
14369         struct intel_encoder *source_encoder;
14370         int index_mask = 0;
14371         int entry = 0;
14372
14373         for_each_intel_encoder(dev, source_encoder) {
14374                 if (encoders_cloneable(encoder, source_encoder))
14375                         index_mask |= (1 << entry);
14376
14377                 entry++;
14378         }
14379
14380         return index_mask;
14381 }
14382
14383 static bool has_edp_a(struct drm_device *dev)
14384 {
14385         struct drm_i915_private *dev_priv = dev->dev_private;
14386
14387         if (!IS_MOBILE(dev))
14388                 return false;
14389
14390         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14391                 return false;
14392
14393         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14394                 return false;
14395
14396         return true;
14397 }
14398
14399 static bool intel_crt_present(struct drm_device *dev)
14400 {
14401         struct drm_i915_private *dev_priv = dev->dev_private;
14402
14403         if (INTEL_INFO(dev)->gen >= 9)
14404                 return false;
14405
14406         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14407                 return false;
14408
14409         if (IS_CHERRYVIEW(dev))
14410                 return false;
14411
14412         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14413                 return false;
14414
14415         /* DDI E can't be used if DDI A requires 4 lanes */
14416         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14417                 return false;
14418
14419         if (!dev_priv->vbt.int_crt_support)
14420                 return false;
14421
14422         return true;
14423 }
14424
14425 static void intel_setup_outputs(struct drm_device *dev)
14426 {
14427         struct drm_i915_private *dev_priv = dev->dev_private;
14428         struct intel_encoder *encoder;
14429         bool dpd_is_edp = false;
14430
14431         intel_lvds_init(dev);
14432
14433         if (intel_crt_present(dev))
14434                 intel_crt_init(dev);
14435
14436         if (IS_BROXTON(dev)) {
14437                 /*
14438                  * FIXME: Broxton doesn't support port detection via the
14439                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14440                  * detect the ports.
14441                  */
14442                 intel_ddi_init(dev, PORT_A);
14443                 intel_ddi_init(dev, PORT_B);
14444                 intel_ddi_init(dev, PORT_C);
14445         } else if (HAS_DDI(dev)) {
14446                 int found;
14447
14448                 /*
14449                  * Haswell uses DDI functions to detect digital outputs.
14450                  * On SKL pre-D0 the strap isn't connected, so we assume
14451                  * it's there.
14452                  */
14453                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14454                 /* WaIgnoreDDIAStrap: skl */
14455                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14456                         intel_ddi_init(dev, PORT_A);
14457
14458                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14459                  * register */
14460                 found = I915_READ(SFUSE_STRAP);
14461
14462                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14463                         intel_ddi_init(dev, PORT_B);
14464                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14465                         intel_ddi_init(dev, PORT_C);
14466                 if (found & SFUSE_STRAP_DDID_DETECTED)
14467                         intel_ddi_init(dev, PORT_D);
14468                 /*
14469                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14470                  */
14471                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14472                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14473                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14474                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14475                         intel_ddi_init(dev, PORT_E);
14476
14477         } else if (HAS_PCH_SPLIT(dev)) {
14478                 int found;
14479                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14480
14481                 if (has_edp_a(dev))
14482                         intel_dp_init(dev, DP_A, PORT_A);
14483
14484                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14485                         /* PCH SDVOB multiplex with HDMIB */
14486                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14487                         if (!found)
14488                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14489                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14490                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14491                 }
14492
14493                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14494                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14495
14496                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14497                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14498
14499                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14500                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14501
14502                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14503                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14504         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14505                 /*
14506                  * The DP_DETECTED bit is the latched state of the DDC
14507                  * SDA pin at boot. However since eDP doesn't require DDC
14508                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14509                  * eDP ports may have been muxed to an alternate function.
14510                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14511                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14512                  * detect eDP ports.
14513                  */
14514                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14515                     !intel_dp_is_edp(dev, PORT_B))
14516                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14517                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14518                     intel_dp_is_edp(dev, PORT_B))
14519                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14520
14521                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14522                     !intel_dp_is_edp(dev, PORT_C))
14523                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14524                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14525                     intel_dp_is_edp(dev, PORT_C))
14526                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14527
14528                 if (IS_CHERRYVIEW(dev)) {
14529                         /* eDP not supported on port D, so don't check VBT */
14530                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14531                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14532                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14533                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14534                 }
14535
14536                 intel_dsi_init(dev);
14537         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14538                 bool found = false;
14539
14540                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14541                         DRM_DEBUG_KMS("probing SDVOB\n");
14542                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14543                         if (!found && IS_G4X(dev)) {
14544                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14545                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14546                         }
14547
14548                         if (!found && IS_G4X(dev))
14549                                 intel_dp_init(dev, DP_B, PORT_B);
14550                 }
14551
14552                 /* Before G4X SDVOC doesn't have its own detect register */
14553
14554                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14555                         DRM_DEBUG_KMS("probing SDVOC\n");
14556                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14557                 }
14558
14559                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14560
14561                         if (IS_G4X(dev)) {
14562                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14563                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14564                         }
14565                         if (IS_G4X(dev))
14566                                 intel_dp_init(dev, DP_C, PORT_C);
14567                 }
14568
14569                 if (IS_G4X(dev) &&
14570                     (I915_READ(DP_D) & DP_DETECTED))
14571                         intel_dp_init(dev, DP_D, PORT_D);
14572         } else if (IS_GEN2(dev))
14573                 intel_dvo_init(dev);
14574
14575         if (SUPPORTS_TV(dev))
14576                 intel_tv_init(dev);
14577
14578         intel_psr_init(dev);
14579
14580         for_each_intel_encoder(dev, encoder) {
14581                 encoder->base.possible_crtcs = encoder->crtc_mask;
14582                 encoder->base.possible_clones =
14583                         intel_encoder_clones(encoder);
14584         }
14585
14586         intel_init_pch_refclk(dev);
14587
14588         drm_helper_move_panel_connectors_to_head(dev);
14589 }
14590
14591 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14592 {
14593         struct drm_device *dev = fb->dev;
14594         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14595
14596         drm_framebuffer_cleanup(fb);
14597         mutex_lock(&dev->struct_mutex);
14598         WARN_ON(!intel_fb->obj->framebuffer_references--);
14599         drm_gem_object_unreference(&intel_fb->obj->base);
14600         mutex_unlock(&dev->struct_mutex);
14601         kfree(intel_fb);
14602 }
14603
14604 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14605                                                 struct drm_file *file,
14606                                                 unsigned int *handle)
14607 {
14608         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14609         struct drm_i915_gem_object *obj = intel_fb->obj;
14610
14611         if (obj->userptr.mm) {
14612                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14613                 return -EINVAL;
14614         }
14615
14616         return drm_gem_handle_create(file, &obj->base, handle);
14617 }
14618
14619 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14620                                         struct drm_file *file,
14621                                         unsigned flags, unsigned color,
14622                                         struct drm_clip_rect *clips,
14623                                         unsigned num_clips)
14624 {
14625         struct drm_device *dev = fb->dev;
14626         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14627         struct drm_i915_gem_object *obj = intel_fb->obj;
14628
14629         mutex_lock(&dev->struct_mutex);
14630         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14631         mutex_unlock(&dev->struct_mutex);
14632
14633         return 0;
14634 }
14635
14636 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14637         .destroy = intel_user_framebuffer_destroy,
14638         .create_handle = intel_user_framebuffer_create_handle,
14639         .dirty = intel_user_framebuffer_dirty,
14640 };
14641
14642 static
14643 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14644                          uint32_t pixel_format)
14645 {
14646         u32 gen = INTEL_INFO(dev)->gen;
14647
14648         if (gen >= 9) {
14649                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14650
14651                 /* "The stride in bytes must not exceed the of the size of 8K
14652                  *  pixels and 32K bytes."
14653                  */
14654                 return min(8192 * cpp, 32768);
14655         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14656                 return 32*1024;
14657         } else if (gen >= 4) {
14658                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14659                         return 16*1024;
14660                 else
14661                         return 32*1024;
14662         } else if (gen >= 3) {
14663                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14664                         return 8*1024;
14665                 else
14666                         return 16*1024;
14667         } else {
14668                 /* XXX DSPC is limited to 4k tiled */
14669                 return 8*1024;
14670         }
14671 }
14672
14673 static int intel_framebuffer_init(struct drm_device *dev,
14674                                   struct intel_framebuffer *intel_fb,
14675                                   struct drm_mode_fb_cmd2 *mode_cmd,
14676                                   struct drm_i915_gem_object *obj)
14677 {
14678         struct drm_i915_private *dev_priv = to_i915(dev);
14679         unsigned int aligned_height;
14680         int ret;
14681         u32 pitch_limit, stride_alignment;
14682
14683         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14684
14685         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14686                 /* Enforce that fb modifier and tiling mode match, but only for
14687                  * X-tiled. This is needed for FBC. */
14688                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14689                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14690                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14691                         return -EINVAL;
14692                 }
14693         } else {
14694                 if (obj->tiling_mode == I915_TILING_X)
14695                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14696                 else if (obj->tiling_mode == I915_TILING_Y) {
14697                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14698                         return -EINVAL;
14699                 }
14700         }
14701
14702         /* Passed in modifier sanity checking. */
14703         switch (mode_cmd->modifier[0]) {
14704         case I915_FORMAT_MOD_Y_TILED:
14705         case I915_FORMAT_MOD_Yf_TILED:
14706                 if (INTEL_INFO(dev)->gen < 9) {
14707                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14708                                   mode_cmd->modifier[0]);
14709                         return -EINVAL;
14710                 }
14711         case DRM_FORMAT_MOD_NONE:
14712         case I915_FORMAT_MOD_X_TILED:
14713                 break;
14714         default:
14715                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14716                           mode_cmd->modifier[0]);
14717                 return -EINVAL;
14718         }
14719
14720         stride_alignment = intel_fb_stride_alignment(dev_priv,
14721                                                      mode_cmd->modifier[0],
14722                                                      mode_cmd->pixel_format);
14723         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14724                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14725                           mode_cmd->pitches[0], stride_alignment);
14726                 return -EINVAL;
14727         }
14728
14729         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14730                                            mode_cmd->pixel_format);
14731         if (mode_cmd->pitches[0] > pitch_limit) {
14732                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14733                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14734                           "tiled" : "linear",
14735                           mode_cmd->pitches[0], pitch_limit);
14736                 return -EINVAL;
14737         }
14738
14739         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14740             mode_cmd->pitches[0] != obj->stride) {
14741                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14742                           mode_cmd->pitches[0], obj->stride);
14743                 return -EINVAL;
14744         }
14745
14746         /* Reject formats not supported by any plane early. */
14747         switch (mode_cmd->pixel_format) {
14748         case DRM_FORMAT_C8:
14749         case DRM_FORMAT_RGB565:
14750         case DRM_FORMAT_XRGB8888:
14751         case DRM_FORMAT_ARGB8888:
14752                 break;
14753         case DRM_FORMAT_XRGB1555:
14754                 if (INTEL_INFO(dev)->gen > 3) {
14755                         DRM_DEBUG("unsupported pixel format: %s\n",
14756                                   drm_get_format_name(mode_cmd->pixel_format));
14757                         return -EINVAL;
14758                 }
14759                 break;
14760         case DRM_FORMAT_ABGR8888:
14761                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14762                     INTEL_INFO(dev)->gen < 9) {
14763                         DRM_DEBUG("unsupported pixel format: %s\n",
14764                                   drm_get_format_name(mode_cmd->pixel_format));
14765                         return -EINVAL;
14766                 }
14767                 break;
14768         case DRM_FORMAT_XBGR8888:
14769         case DRM_FORMAT_XRGB2101010:
14770         case DRM_FORMAT_XBGR2101010:
14771                 if (INTEL_INFO(dev)->gen < 4) {
14772                         DRM_DEBUG("unsupported pixel format: %s\n",
14773                                   drm_get_format_name(mode_cmd->pixel_format));
14774                         return -EINVAL;
14775                 }
14776                 break;
14777         case DRM_FORMAT_ABGR2101010:
14778                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14779                         DRM_DEBUG("unsupported pixel format: %s\n",
14780                                   drm_get_format_name(mode_cmd->pixel_format));
14781                         return -EINVAL;
14782                 }
14783                 break;
14784         case DRM_FORMAT_YUYV:
14785         case DRM_FORMAT_UYVY:
14786         case DRM_FORMAT_YVYU:
14787         case DRM_FORMAT_VYUY:
14788                 if (INTEL_INFO(dev)->gen < 5) {
14789                         DRM_DEBUG("unsupported pixel format: %s\n",
14790                                   drm_get_format_name(mode_cmd->pixel_format));
14791                         return -EINVAL;
14792                 }
14793                 break;
14794         default:
14795                 DRM_DEBUG("unsupported pixel format: %s\n",
14796                           drm_get_format_name(mode_cmd->pixel_format));
14797                 return -EINVAL;
14798         }
14799
14800         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14801         if (mode_cmd->offsets[0] != 0)
14802                 return -EINVAL;
14803
14804         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14805                                                mode_cmd->pixel_format,
14806                                                mode_cmd->modifier[0]);
14807         /* FIXME drm helper for size checks (especially planar formats)? */
14808         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14809                 return -EINVAL;
14810
14811         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14812         intel_fb->obj = obj;
14813
14814         intel_fill_fb_info(dev_priv, &intel_fb->base);
14815
14816         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14817         if (ret) {
14818                 DRM_ERROR("framebuffer init failed %d\n", ret);
14819                 return ret;
14820         }
14821
14822         intel_fb->obj->framebuffer_references++;
14823
14824         return 0;
14825 }
14826
14827 static struct drm_framebuffer *
14828 intel_user_framebuffer_create(struct drm_device *dev,
14829                               struct drm_file *filp,
14830                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14831 {
14832         struct drm_framebuffer *fb;
14833         struct drm_i915_gem_object *obj;
14834         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14835
14836         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14837                                                 mode_cmd.handles[0]));
14838         if (&obj->base == NULL)
14839                 return ERR_PTR(-ENOENT);
14840
14841         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
14842         if (IS_ERR(fb))
14843                 drm_gem_object_unreference_unlocked(&obj->base);
14844
14845         return fb;
14846 }
14847
14848 #ifndef CONFIG_DRM_FBDEV_EMULATION
14849 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14850 {
14851 }
14852 #endif
14853
14854 static const struct drm_mode_config_funcs intel_mode_funcs = {
14855         .fb_create = intel_user_framebuffer_create,
14856         .output_poll_changed = intel_fbdev_output_poll_changed,
14857         .atomic_check = intel_atomic_check,
14858         .atomic_commit = intel_atomic_commit,
14859         .atomic_state_alloc = intel_atomic_state_alloc,
14860         .atomic_state_clear = intel_atomic_state_clear,
14861 };
14862
14863 /**
14864  * intel_init_display_hooks - initialize the display modesetting hooks
14865  * @dev_priv: device private
14866  */
14867 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14868 {
14869         if (HAS_PCH_SPLIT(dev_priv) || IS_G4X(dev_priv))
14870                 dev_priv->display.find_dpll = g4x_find_best_dpll;
14871         else if (IS_CHERRYVIEW(dev_priv))
14872                 dev_priv->display.find_dpll = chv_find_best_dpll;
14873         else if (IS_VALLEYVIEW(dev_priv))
14874                 dev_priv->display.find_dpll = vlv_find_best_dpll;
14875         else if (IS_PINEVIEW(dev_priv))
14876                 dev_priv->display.find_dpll = pnv_find_best_dpll;
14877         else
14878                 dev_priv->display.find_dpll = i9xx_find_best_dpll;
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_VALLEYVIEW(dev_priv) || 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 = i9xx_crtc_compute_clock;
14909                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14910                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14911         } else {
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 = i9xx_crtc_compute_clock;
14916                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14917                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14918         }
14919
14920         /* Returns the core display clock speed */
14921         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
14922                 dev_priv->display.get_display_clock_speed =
14923                         skylake_get_display_clock_speed;
14924         else if (IS_BROXTON(dev_priv))
14925                 dev_priv->display.get_display_clock_speed =
14926                         broxton_get_display_clock_speed;
14927         else if (IS_BROADWELL(dev_priv))
14928                 dev_priv->display.get_display_clock_speed =
14929                         broadwell_get_display_clock_speed;
14930         else if (IS_HASWELL(dev_priv))
14931                 dev_priv->display.get_display_clock_speed =
14932                         haswell_get_display_clock_speed;
14933         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14934                 dev_priv->display.get_display_clock_speed =
14935                         valleyview_get_display_clock_speed;
14936         else if (IS_GEN5(dev_priv))
14937                 dev_priv->display.get_display_clock_speed =
14938                         ilk_get_display_clock_speed;
14939         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
14940                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
14941                 dev_priv->display.get_display_clock_speed =
14942                         i945_get_display_clock_speed;
14943         else if (IS_GM45(dev_priv))
14944                 dev_priv->display.get_display_clock_speed =
14945                         gm45_get_display_clock_speed;
14946         else if (IS_CRESTLINE(dev_priv))
14947                 dev_priv->display.get_display_clock_speed =
14948                         i965gm_get_display_clock_speed;
14949         else if (IS_PINEVIEW(dev_priv))
14950                 dev_priv->display.get_display_clock_speed =
14951                         pnv_get_display_clock_speed;
14952         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
14953                 dev_priv->display.get_display_clock_speed =
14954                         g33_get_display_clock_speed;
14955         else if (IS_I915G(dev_priv))
14956                 dev_priv->display.get_display_clock_speed =
14957                         i915_get_display_clock_speed;
14958         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
14959                 dev_priv->display.get_display_clock_speed =
14960                         i9xx_misc_get_display_clock_speed;
14961         else if (IS_I915GM(dev_priv))
14962                 dev_priv->display.get_display_clock_speed =
14963                         i915gm_get_display_clock_speed;
14964         else if (IS_I865G(dev_priv))
14965                 dev_priv->display.get_display_clock_speed =
14966                         i865_get_display_clock_speed;
14967         else if (IS_I85X(dev_priv))
14968                 dev_priv->display.get_display_clock_speed =
14969                         i85x_get_display_clock_speed;
14970         else { /* 830 */
14971                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
14972                 dev_priv->display.get_display_clock_speed =
14973                         i830_get_display_clock_speed;
14974         }
14975
14976         if (IS_GEN5(dev_priv)) {
14977                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14978         } else if (IS_GEN6(dev_priv)) {
14979                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14980         } else if (IS_IVYBRIDGE(dev_priv)) {
14981                 /* FIXME: detect B0+ stepping and use auto training */
14982                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14983         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14984                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14985                 if (IS_BROADWELL(dev_priv)) {
14986                         dev_priv->display.modeset_commit_cdclk =
14987                                 broadwell_modeset_commit_cdclk;
14988                         dev_priv->display.modeset_calc_cdclk =
14989                                 broadwell_modeset_calc_cdclk;
14990                 }
14991         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14992                 dev_priv->display.modeset_commit_cdclk =
14993                         valleyview_modeset_commit_cdclk;
14994                 dev_priv->display.modeset_calc_cdclk =
14995                         valleyview_modeset_calc_cdclk;
14996         } else if (IS_BROXTON(dev_priv)) {
14997                 dev_priv->display.modeset_commit_cdclk =
14998                         broxton_modeset_commit_cdclk;
14999                 dev_priv->display.modeset_calc_cdclk =
15000                         broxton_modeset_calc_cdclk;
15001         }
15002
15003         switch (INTEL_INFO(dev_priv)->gen) {
15004         case 2:
15005                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
15006                 break;
15007
15008         case 3:
15009                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
15010                 break;
15011
15012         case 4:
15013         case 5:
15014                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15015                 break;
15016
15017         case 6:
15018                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15019                 break;
15020         case 7:
15021         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15022                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15023                 break;
15024         case 9:
15025                 /* Drop through - unsupported since execlist only. */
15026         default:
15027                 /* Default just returns -ENODEV to indicate unsupported */
15028                 dev_priv->display.queue_flip = intel_default_queue_flip;
15029         }
15030 }
15031
15032 /*
15033  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15034  * resume, or other times.  This quirk makes sure that's the case for
15035  * affected systems.
15036  */
15037 static void quirk_pipea_force(struct drm_device *dev)
15038 {
15039         struct drm_i915_private *dev_priv = dev->dev_private;
15040
15041         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15042         DRM_INFO("applying pipe a force quirk\n");
15043 }
15044
15045 static void quirk_pipeb_force(struct drm_device *dev)
15046 {
15047         struct drm_i915_private *dev_priv = dev->dev_private;
15048
15049         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15050         DRM_INFO("applying pipe b force quirk\n");
15051 }
15052
15053 /*
15054  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15055  */
15056 static void quirk_ssc_force_disable(struct drm_device *dev)
15057 {
15058         struct drm_i915_private *dev_priv = dev->dev_private;
15059         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15060         DRM_INFO("applying lvds SSC disable quirk\n");
15061 }
15062
15063 /*
15064  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15065  * brightness value
15066  */
15067 static void quirk_invert_brightness(struct drm_device *dev)
15068 {
15069         struct drm_i915_private *dev_priv = dev->dev_private;
15070         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15071         DRM_INFO("applying inverted panel brightness quirk\n");
15072 }
15073
15074 /* Some VBT's incorrectly indicate no backlight is present */
15075 static void quirk_backlight_present(struct drm_device *dev)
15076 {
15077         struct drm_i915_private *dev_priv = dev->dev_private;
15078         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15079         DRM_INFO("applying backlight present quirk\n");
15080 }
15081
15082 struct intel_quirk {
15083         int device;
15084         int subsystem_vendor;
15085         int subsystem_device;
15086         void (*hook)(struct drm_device *dev);
15087 };
15088
15089 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15090 struct intel_dmi_quirk {
15091         void (*hook)(struct drm_device *dev);
15092         const struct dmi_system_id (*dmi_id_list)[];
15093 };
15094
15095 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15096 {
15097         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15098         return 1;
15099 }
15100
15101 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15102         {
15103                 .dmi_id_list = &(const struct dmi_system_id[]) {
15104                         {
15105                                 .callback = intel_dmi_reverse_brightness,
15106                                 .ident = "NCR Corporation",
15107                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15108                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15109                                 },
15110                         },
15111                         { }  /* terminating entry */
15112                 },
15113                 .hook = quirk_invert_brightness,
15114         },
15115 };
15116
15117 static struct intel_quirk intel_quirks[] = {
15118         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15119         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15120
15121         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15122         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15123
15124         /* 830 needs to leave pipe A & dpll A up */
15125         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15126
15127         /* 830 needs to leave pipe B & dpll B up */
15128         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15129
15130         /* Lenovo U160 cannot use SSC on LVDS */
15131         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15132
15133         /* Sony Vaio Y cannot use SSC on LVDS */
15134         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15135
15136         /* Acer Aspire 5734Z must invert backlight brightness */
15137         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15138
15139         /* Acer/eMachines G725 */
15140         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15141
15142         /* Acer/eMachines e725 */
15143         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15144
15145         /* Acer/Packard Bell NCL20 */
15146         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15147
15148         /* Acer Aspire 4736Z */
15149         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15150
15151         /* Acer Aspire 5336 */
15152         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15153
15154         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15155         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15156
15157         /* Acer C720 Chromebook (Core i3 4005U) */
15158         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15159
15160         /* Apple Macbook 2,1 (Core 2 T7400) */
15161         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15162
15163         /* Apple Macbook 4,1 */
15164         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15165
15166         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15167         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15168
15169         /* HP Chromebook 14 (Celeron 2955U) */
15170         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15171
15172         /* Dell Chromebook 11 */
15173         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15174
15175         /* Dell Chromebook 11 (2015 version) */
15176         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15177 };
15178
15179 static void intel_init_quirks(struct drm_device *dev)
15180 {
15181         struct pci_dev *d = dev->pdev;
15182         int i;
15183
15184         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15185                 struct intel_quirk *q = &intel_quirks[i];
15186
15187                 if (d->device == q->device &&
15188                     (d->subsystem_vendor == q->subsystem_vendor ||
15189                      q->subsystem_vendor == PCI_ANY_ID) &&
15190                     (d->subsystem_device == q->subsystem_device ||
15191                      q->subsystem_device == PCI_ANY_ID))
15192                         q->hook(dev);
15193         }
15194         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15195                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15196                         intel_dmi_quirks[i].hook(dev);
15197         }
15198 }
15199
15200 /* Disable the VGA plane that we never use */
15201 static void i915_disable_vga(struct drm_device *dev)
15202 {
15203         struct drm_i915_private *dev_priv = dev->dev_private;
15204         u8 sr1;
15205         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15206
15207         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15208         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15209         outb(SR01, VGA_SR_INDEX);
15210         sr1 = inb(VGA_SR_DATA);
15211         outb(sr1 | 1<<5, VGA_SR_DATA);
15212         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15213         udelay(300);
15214
15215         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15216         POSTING_READ(vga_reg);
15217 }
15218
15219 void intel_modeset_init_hw(struct drm_device *dev)
15220 {
15221         struct drm_i915_private *dev_priv = dev->dev_private;
15222
15223         intel_update_cdclk(dev);
15224
15225         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15226
15227         intel_init_clock_gating(dev);
15228         intel_enable_gt_powersave(dev);
15229 }
15230
15231 /*
15232  * Calculate what we think the watermarks should be for the state we've read
15233  * out of the hardware and then immediately program those watermarks so that
15234  * we ensure the hardware settings match our internal state.
15235  *
15236  * We can calculate what we think WM's should be by creating a duplicate of the
15237  * current state (which was constructed during hardware readout) and running it
15238  * through the atomic check code to calculate new watermark values in the
15239  * state object.
15240  */
15241 static void sanitize_watermarks(struct drm_device *dev)
15242 {
15243         struct drm_i915_private *dev_priv = to_i915(dev);
15244         struct drm_atomic_state *state;
15245         struct drm_crtc *crtc;
15246         struct drm_crtc_state *cstate;
15247         struct drm_modeset_acquire_ctx ctx;
15248         int ret;
15249         int i;
15250
15251         /* Only supported on platforms that use atomic watermark design */
15252         if (!dev_priv->display.optimize_watermarks)
15253                 return;
15254
15255         /*
15256          * We need to hold connection_mutex before calling duplicate_state so
15257          * that the connector loop is protected.
15258          */
15259         drm_modeset_acquire_init(&ctx, 0);
15260 retry:
15261         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15262         if (ret == -EDEADLK) {
15263                 drm_modeset_backoff(&ctx);
15264                 goto retry;
15265         } else if (WARN_ON(ret)) {
15266                 goto fail;
15267         }
15268
15269         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15270         if (WARN_ON(IS_ERR(state)))
15271                 goto fail;
15272
15273         /*
15274          * Hardware readout is the only time we don't want to calculate
15275          * intermediate watermarks (since we don't trust the current
15276          * watermarks).
15277          */
15278         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15279
15280         ret = intel_atomic_check(dev, state);
15281         if (ret) {
15282                 /*
15283                  * If we fail here, it means that the hardware appears to be
15284                  * programmed in a way that shouldn't be possible, given our
15285                  * understanding of watermark requirements.  This might mean a
15286                  * mistake in the hardware readout code or a mistake in the
15287                  * watermark calculations for a given platform.  Raise a WARN
15288                  * so that this is noticeable.
15289                  *
15290                  * If this actually happens, we'll have to just leave the
15291                  * BIOS-programmed watermarks untouched and hope for the best.
15292                  */
15293                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15294                 goto fail;
15295         }
15296
15297         /* Write calculated watermark values back */
15298         to_i915(dev)->wm.config = to_intel_atomic_state(state)->wm_config;
15299         for_each_crtc_in_state(state, crtc, cstate, i) {
15300                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15301
15302                 cs->wm.need_postvbl_update = true;
15303                 dev_priv->display.optimize_watermarks(cs);
15304         }
15305
15306         drm_atomic_state_free(state);
15307 fail:
15308         drm_modeset_drop_locks(&ctx);
15309         drm_modeset_acquire_fini(&ctx);
15310 }
15311
15312 void intel_modeset_init(struct drm_device *dev)
15313 {
15314         struct drm_i915_private *dev_priv = dev->dev_private;
15315         int sprite, ret;
15316         enum pipe pipe;
15317         struct intel_crtc *crtc;
15318
15319         drm_mode_config_init(dev);
15320
15321         dev->mode_config.min_width = 0;
15322         dev->mode_config.min_height = 0;
15323
15324         dev->mode_config.preferred_depth = 24;
15325         dev->mode_config.prefer_shadow = 1;
15326
15327         dev->mode_config.allow_fb_modifiers = true;
15328
15329         dev->mode_config.funcs = &intel_mode_funcs;
15330
15331         intel_init_quirks(dev);
15332
15333         intel_init_pm(dev);
15334
15335         if (INTEL_INFO(dev)->num_pipes == 0)
15336                 return;
15337
15338         /*
15339          * There may be no VBT; and if the BIOS enabled SSC we can
15340          * just keep using it to avoid unnecessary flicker.  Whereas if the
15341          * BIOS isn't using it, don't assume it will work even if the VBT
15342          * indicates as much.
15343          */
15344         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15345                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15346                                             DREF_SSC1_ENABLE);
15347
15348                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15349                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15350                                      bios_lvds_use_ssc ? "en" : "dis",
15351                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15352                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15353                 }
15354         }
15355
15356         if (IS_GEN2(dev)) {
15357                 dev->mode_config.max_width = 2048;
15358                 dev->mode_config.max_height = 2048;
15359         } else if (IS_GEN3(dev)) {
15360                 dev->mode_config.max_width = 4096;
15361                 dev->mode_config.max_height = 4096;
15362         } else {
15363                 dev->mode_config.max_width = 8192;
15364                 dev->mode_config.max_height = 8192;
15365         }
15366
15367         if (IS_845G(dev) || IS_I865G(dev)) {
15368                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15369                 dev->mode_config.cursor_height = 1023;
15370         } else if (IS_GEN2(dev)) {
15371                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15372                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15373         } else {
15374                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15375                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15376         }
15377
15378         dev->mode_config.fb_base = dev_priv->ggtt.mappable_base;
15379
15380         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15381                       INTEL_INFO(dev)->num_pipes,
15382                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15383
15384         for_each_pipe(dev_priv, pipe) {
15385                 intel_crtc_init(dev, pipe);
15386                 for_each_sprite(dev_priv, pipe, sprite) {
15387                         ret = intel_plane_init(dev, pipe, sprite);
15388                         if (ret)
15389                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15390                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15391                 }
15392         }
15393
15394         intel_update_czclk(dev_priv);
15395         intel_update_rawclk(dev_priv);
15396         intel_update_cdclk(dev);
15397
15398         intel_shared_dpll_init(dev);
15399
15400         /* Just disable it once at startup */
15401         i915_disable_vga(dev);
15402         intel_setup_outputs(dev);
15403
15404         drm_modeset_lock_all(dev);
15405         intel_modeset_setup_hw_state(dev);
15406         drm_modeset_unlock_all(dev);
15407
15408         for_each_intel_crtc(dev, crtc) {
15409                 struct intel_initial_plane_config plane_config = {};
15410
15411                 if (!crtc->active)
15412                         continue;
15413
15414                 /*
15415                  * Note that reserving the BIOS fb up front prevents us
15416                  * from stuffing other stolen allocations like the ring
15417                  * on top.  This prevents some ugliness at boot time, and
15418                  * can even allow for smooth boot transitions if the BIOS
15419                  * fb is large enough for the active pipe configuration.
15420                  */
15421                 dev_priv->display.get_initial_plane_config(crtc,
15422                                                            &plane_config);
15423
15424                 /*
15425                  * If the fb is shared between multiple heads, we'll
15426                  * just get the first one.
15427                  */
15428                 intel_find_initial_plane_obj(crtc, &plane_config);
15429         }
15430
15431         /*
15432          * Make sure hardware watermarks really match the state we read out.
15433          * Note that we need to do this after reconstructing the BIOS fb's
15434          * since the watermark calculation done here will use pstate->fb.
15435          */
15436         sanitize_watermarks(dev);
15437 }
15438
15439 static void intel_enable_pipe_a(struct drm_device *dev)
15440 {
15441         struct intel_connector *connector;
15442         struct drm_connector *crt = NULL;
15443         struct intel_load_detect_pipe load_detect_temp;
15444         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15445
15446         /* We can't just switch on the pipe A, we need to set things up with a
15447          * proper mode and output configuration. As a gross hack, enable pipe A
15448          * by enabling the load detect pipe once. */
15449         for_each_intel_connector(dev, connector) {
15450                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15451                         crt = &connector->base;
15452                         break;
15453                 }
15454         }
15455
15456         if (!crt)
15457                 return;
15458
15459         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15460                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15461 }
15462
15463 static bool
15464 intel_check_plane_mapping(struct intel_crtc *crtc)
15465 {
15466         struct drm_device *dev = crtc->base.dev;
15467         struct drm_i915_private *dev_priv = dev->dev_private;
15468         u32 val;
15469
15470         if (INTEL_INFO(dev)->num_pipes == 1)
15471                 return true;
15472
15473         val = I915_READ(DSPCNTR(!crtc->plane));
15474
15475         if ((val & DISPLAY_PLANE_ENABLE) &&
15476             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15477                 return false;
15478
15479         return true;
15480 }
15481
15482 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15483 {
15484         struct drm_device *dev = crtc->base.dev;
15485         struct intel_encoder *encoder;
15486
15487         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15488                 return true;
15489
15490         return false;
15491 }
15492
15493 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15494 {
15495         struct drm_device *dev = encoder->base.dev;
15496         struct intel_connector *connector;
15497
15498         for_each_connector_on_encoder(dev, &encoder->base, connector)
15499                 return true;
15500
15501         return false;
15502 }
15503
15504 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15505 {
15506         struct drm_device *dev = crtc->base.dev;
15507         struct drm_i915_private *dev_priv = dev->dev_private;
15508         i915_reg_t reg = PIPECONF(crtc->config->cpu_transcoder);
15509
15510         /* Clear any frame start delays used for debugging left by the BIOS */
15511         I915_WRITE(reg, I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15512
15513         /* restore vblank interrupts to correct state */
15514         drm_crtc_vblank_reset(&crtc->base);
15515         if (crtc->active) {
15516                 struct intel_plane *plane;
15517
15518                 drm_crtc_vblank_on(&crtc->base);
15519
15520                 /* Disable everything but the primary plane */
15521                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15522                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15523                                 continue;
15524
15525                         plane->disable_plane(&plane->base, &crtc->base);
15526                 }
15527         }
15528
15529         /* We need to sanitize the plane -> pipe mapping first because this will
15530          * disable the crtc (and hence change the state) if it is wrong. Note
15531          * that gen4+ has a fixed plane -> pipe mapping.  */
15532         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15533                 bool plane;
15534
15535                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15536                               crtc->base.base.id);
15537
15538                 /* Pipe has the wrong plane attached and the plane is active.
15539                  * Temporarily change the plane mapping and disable everything
15540                  * ...  */
15541                 plane = crtc->plane;
15542                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15543                 crtc->plane = !plane;
15544                 intel_crtc_disable_noatomic(&crtc->base);
15545                 crtc->plane = plane;
15546         }
15547
15548         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15549             crtc->pipe == PIPE_A && !crtc->active) {
15550                 /* BIOS forgot to enable pipe A, this mostly happens after
15551                  * resume. Force-enable the pipe to fix this, the update_dpms
15552                  * call below we restore the pipe to the right state, but leave
15553                  * the required bits on. */
15554                 intel_enable_pipe_a(dev);
15555         }
15556
15557         /* Adjust the state of the output pipe according to whether we
15558          * have active connectors/encoders. */
15559         if (crtc->active && !intel_crtc_has_encoders(crtc))
15560                 intel_crtc_disable_noatomic(&crtc->base);
15561
15562         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15563                 /*
15564                  * We start out with underrun reporting disabled to avoid races.
15565                  * For correct bookkeeping mark this on active crtcs.
15566                  *
15567                  * Also on gmch platforms we dont have any hardware bits to
15568                  * disable the underrun reporting. Which means we need to start
15569                  * out with underrun reporting disabled also on inactive pipes,
15570                  * since otherwise we'll complain about the garbage we read when
15571                  * e.g. coming up after runtime pm.
15572                  *
15573                  * No protection against concurrent access is required - at
15574                  * worst a fifo underrun happens which also sets this to false.
15575                  */
15576                 crtc->cpu_fifo_underrun_disabled = true;
15577                 crtc->pch_fifo_underrun_disabled = true;
15578         }
15579 }
15580
15581 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15582 {
15583         struct intel_connector *connector;
15584         struct drm_device *dev = encoder->base.dev;
15585
15586         /* We need to check both for a crtc link (meaning that the
15587          * encoder is active and trying to read from a pipe) and the
15588          * pipe itself being active. */
15589         bool has_active_crtc = encoder->base.crtc &&
15590                 to_intel_crtc(encoder->base.crtc)->active;
15591
15592         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15593                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15594                               encoder->base.base.id,
15595                               encoder->base.name);
15596
15597                 /* Connector is active, but has no active pipe. This is
15598                  * fallout from our resume register restoring. Disable
15599                  * the encoder manually again. */
15600                 if (encoder->base.crtc) {
15601                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15602                                       encoder->base.base.id,
15603                                       encoder->base.name);
15604                         encoder->disable(encoder);
15605                         if (encoder->post_disable)
15606                                 encoder->post_disable(encoder);
15607                 }
15608                 encoder->base.crtc = NULL;
15609
15610                 /* Inconsistent output/port/pipe state happens presumably due to
15611                  * a bug in one of the get_hw_state functions. Or someplace else
15612                  * in our code, like the register restore mess on resume. Clamp
15613                  * things to off as a safer default. */
15614                 for_each_intel_connector(dev, connector) {
15615                         if (connector->encoder != encoder)
15616                                 continue;
15617                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15618                         connector->base.encoder = NULL;
15619                 }
15620         }
15621         /* Enabled encoders without active connectors will be fixed in
15622          * the crtc fixup. */
15623 }
15624
15625 void i915_redisable_vga_power_on(struct drm_device *dev)
15626 {
15627         struct drm_i915_private *dev_priv = dev->dev_private;
15628         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15629
15630         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15631                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15632                 i915_disable_vga(dev);
15633         }
15634 }
15635
15636 void i915_redisable_vga(struct drm_device *dev)
15637 {
15638         struct drm_i915_private *dev_priv = dev->dev_private;
15639
15640         /* This function can be called both from intel_modeset_setup_hw_state or
15641          * at a very early point in our resume sequence, where the power well
15642          * structures are not yet restored. Since this function is at a very
15643          * paranoid "someone might have enabled VGA while we were not looking"
15644          * level, just check if the power well is enabled instead of trying to
15645          * follow the "don't touch the power well if we don't need it" policy
15646          * the rest of the driver uses. */
15647         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15648                 return;
15649
15650         i915_redisable_vga_power_on(dev);
15651
15652         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15653 }
15654
15655 static bool primary_get_hw_state(struct intel_plane *plane)
15656 {
15657         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15658
15659         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15660 }
15661
15662 /* FIXME read out full plane state for all planes */
15663 static void readout_plane_state(struct intel_crtc *crtc)
15664 {
15665         struct drm_plane *primary = crtc->base.primary;
15666         struct intel_plane_state *plane_state =
15667                 to_intel_plane_state(primary->state);
15668
15669         plane_state->visible = crtc->active &&
15670                 primary_get_hw_state(to_intel_plane(primary));
15671
15672         if (plane_state->visible)
15673                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15674 }
15675
15676 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15677 {
15678         struct drm_i915_private *dev_priv = dev->dev_private;
15679         enum pipe pipe;
15680         struct intel_crtc *crtc;
15681         struct intel_encoder *encoder;
15682         struct intel_connector *connector;
15683         int i;
15684
15685         dev_priv->active_crtcs = 0;
15686
15687         for_each_intel_crtc(dev, crtc) {
15688                 struct intel_crtc_state *crtc_state = crtc->config;
15689                 int pixclk = 0;
15690
15691                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, &crtc_state->base);
15692                 memset(crtc_state, 0, sizeof(*crtc_state));
15693                 crtc_state->base.crtc = &crtc->base;
15694
15695                 crtc_state->base.active = crtc_state->base.enable =
15696                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15697
15698                 crtc->base.enabled = crtc_state->base.enable;
15699                 crtc->active = crtc_state->base.active;
15700
15701                 if (crtc_state->base.active) {
15702                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15703
15704                         if (IS_BROADWELL(dev_priv)) {
15705                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15706
15707                                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15708                                 if (crtc_state->ips_enabled)
15709                                         pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15710                         } else if (IS_VALLEYVIEW(dev_priv) ||
15711                                    IS_CHERRYVIEW(dev_priv) ||
15712                                    IS_BROXTON(dev_priv))
15713                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15714                         else
15715                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15716                 }
15717
15718                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15719
15720                 readout_plane_state(crtc);
15721
15722                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15723                               crtc->base.base.id,
15724                               crtc->active ? "enabled" : "disabled");
15725         }
15726
15727         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15728                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15729
15730                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15731                                                   &pll->config.hw_state);
15732                 pll->config.crtc_mask = 0;
15733                 for_each_intel_crtc(dev, crtc) {
15734                         if (crtc->active && crtc->config->shared_dpll == pll)
15735                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15736                 }
15737                 pll->active_mask = pll->config.crtc_mask;
15738
15739                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15740                               pll->name, pll->config.crtc_mask, pll->on);
15741         }
15742
15743         for_each_intel_encoder(dev, encoder) {
15744                 pipe = 0;
15745
15746                 if (encoder->get_hw_state(encoder, &pipe)) {
15747                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15748                         encoder->base.crtc = &crtc->base;
15749                         encoder->get_config(encoder, crtc->config);
15750                 } else {
15751                         encoder->base.crtc = NULL;
15752                 }
15753
15754                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15755                               encoder->base.base.id,
15756                               encoder->base.name,
15757                               encoder->base.crtc ? "enabled" : "disabled",
15758                               pipe_name(pipe));
15759         }
15760
15761         for_each_intel_connector(dev, connector) {
15762                 if (connector->get_hw_state(connector)) {
15763                         connector->base.dpms = DRM_MODE_DPMS_ON;
15764
15765                         encoder = connector->encoder;
15766                         connector->base.encoder = &encoder->base;
15767
15768                         if (encoder->base.crtc &&
15769                             encoder->base.crtc->state->active) {
15770                                 /*
15771                                  * This has to be done during hardware readout
15772                                  * because anything calling .crtc_disable may
15773                                  * rely on the connector_mask being accurate.
15774                                  */
15775                                 encoder->base.crtc->state->connector_mask |=
15776                                         1 << drm_connector_index(&connector->base);
15777                                 encoder->base.crtc->state->encoder_mask |=
15778                                         1 << drm_encoder_index(&encoder->base);
15779                         }
15780
15781                 } else {
15782                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15783                         connector->base.encoder = NULL;
15784                 }
15785                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15786                               connector->base.base.id,
15787                               connector->base.name,
15788                               connector->base.encoder ? "enabled" : "disabled");
15789         }
15790
15791         for_each_intel_crtc(dev, crtc) {
15792                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15793
15794                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15795                 if (crtc->base.state->active) {
15796                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15797                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15798                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15799
15800                         /*
15801                          * The initial mode needs to be set in order to keep
15802                          * the atomic core happy. It wants a valid mode if the
15803                          * crtc's enabled, so we do the above call.
15804                          *
15805                          * At this point some state updated by the connectors
15806                          * in their ->detect() callback has not run yet, so
15807                          * no recalculation can be done yet.
15808                          *
15809                          * Even if we could do a recalculation and modeset
15810                          * right now it would cause a double modeset if
15811                          * fbdev or userspace chooses a different initial mode.
15812                          *
15813                          * If that happens, someone indicated they wanted a
15814                          * mode change, which means it's safe to do a full
15815                          * recalculation.
15816                          */
15817                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15818
15819                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
15820                         update_scanline_offset(crtc);
15821                 }
15822
15823                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
15824         }
15825 }
15826
15827 /* Scan out the current hw modeset state,
15828  * and sanitizes it to the current state
15829  */
15830 static void
15831 intel_modeset_setup_hw_state(struct drm_device *dev)
15832 {
15833         struct drm_i915_private *dev_priv = dev->dev_private;
15834         enum pipe pipe;
15835         struct intel_crtc *crtc;
15836         struct intel_encoder *encoder;
15837         int i;
15838
15839         intel_modeset_readout_hw_state(dev);
15840
15841         /* HW state is read out, now we need to sanitize this mess. */
15842         for_each_intel_encoder(dev, encoder) {
15843                 intel_sanitize_encoder(encoder);
15844         }
15845
15846         for_each_pipe(dev_priv, pipe) {
15847                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15848                 intel_sanitize_crtc(crtc);
15849                 intel_dump_pipe_config(crtc, crtc->config,
15850                                        "[setup_hw_state]");
15851         }
15852
15853         intel_modeset_update_connector_atomic_state(dev);
15854
15855         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15856                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15857
15858                 if (!pll->on || pll->active_mask)
15859                         continue;
15860
15861                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15862
15863                 pll->funcs.disable(dev_priv, pll);
15864                 pll->on = false;
15865         }
15866
15867         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15868                 vlv_wm_get_hw_state(dev);
15869         else if (IS_GEN9(dev))
15870                 skl_wm_get_hw_state(dev);
15871         else if (HAS_PCH_SPLIT(dev))
15872                 ilk_wm_get_hw_state(dev);
15873
15874         for_each_intel_crtc(dev, crtc) {
15875                 unsigned long put_domains;
15876
15877                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15878                 if (WARN_ON(put_domains))
15879                         modeset_put_power_domains(dev_priv, put_domains);
15880         }
15881         intel_display_set_init_power(dev_priv, false);
15882
15883         intel_fbc_init_pipe_state(dev_priv);
15884 }
15885
15886 void intel_display_resume(struct drm_device *dev)
15887 {
15888         struct drm_i915_private *dev_priv = to_i915(dev);
15889         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15890         struct drm_modeset_acquire_ctx ctx;
15891         int ret;
15892         bool setup = false;
15893
15894         dev_priv->modeset_restore_state = NULL;
15895
15896         /*
15897          * This is a cludge because with real atomic modeset mode_config.mutex
15898          * won't be taken. Unfortunately some probed state like
15899          * audio_codec_enable is still protected by mode_config.mutex, so lock
15900          * it here for now.
15901          */
15902         mutex_lock(&dev->mode_config.mutex);
15903         drm_modeset_acquire_init(&ctx, 0);
15904
15905 retry:
15906         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15907
15908         if (ret == 0 && !setup) {
15909                 setup = true;
15910
15911                 intel_modeset_setup_hw_state(dev);
15912                 i915_redisable_vga(dev);
15913         }
15914
15915         if (ret == 0 && state) {
15916                 struct drm_crtc_state *crtc_state;
15917                 struct drm_crtc *crtc;
15918                 int i;
15919
15920                 state->acquire_ctx = &ctx;
15921
15922                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
15923                         /*
15924                          * Force recalculation even if we restore
15925                          * current state. With fast modeset this may not result
15926                          * in a modeset when the state is compatible.
15927                          */
15928                         crtc_state->mode_changed = true;
15929                 }
15930
15931                 ret = drm_atomic_commit(state);
15932         }
15933
15934         if (ret == -EDEADLK) {
15935                 drm_modeset_backoff(&ctx);
15936                 goto retry;
15937         }
15938
15939         drm_modeset_drop_locks(&ctx);
15940         drm_modeset_acquire_fini(&ctx);
15941         mutex_unlock(&dev->mode_config.mutex);
15942
15943         if (ret) {
15944                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15945                 drm_atomic_state_free(state);
15946         }
15947 }
15948
15949 void intel_modeset_gem_init(struct drm_device *dev)
15950 {
15951         struct drm_crtc *c;
15952         struct drm_i915_gem_object *obj;
15953         int ret;
15954
15955         intel_init_gt_powersave(dev);
15956
15957         intel_modeset_init_hw(dev);
15958
15959         intel_setup_overlay(dev);
15960
15961         /*
15962          * Make sure any fbs we allocated at startup are properly
15963          * pinned & fenced.  When we do the allocation it's too early
15964          * for this.
15965          */
15966         for_each_crtc(dev, c) {
15967                 obj = intel_fb_obj(c->primary->fb);
15968                 if (obj == NULL)
15969                         continue;
15970
15971                 mutex_lock(&dev->struct_mutex);
15972                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
15973                                                  c->primary->state->rotation);
15974                 mutex_unlock(&dev->struct_mutex);
15975                 if (ret) {
15976                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15977                                   to_intel_crtc(c)->pipe);
15978                         drm_framebuffer_unreference(c->primary->fb);
15979                         c->primary->fb = NULL;
15980                         c->primary->crtc = c->primary->state->crtc = NULL;
15981                         update_state_fb(c->primary);
15982                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15983                 }
15984         }
15985
15986         intel_backlight_register(dev);
15987 }
15988
15989 void intel_connector_unregister(struct intel_connector *intel_connector)
15990 {
15991         struct drm_connector *connector = &intel_connector->base;
15992
15993         intel_panel_destroy_backlight(connector);
15994         drm_connector_unregister(connector);
15995 }
15996
15997 void intel_modeset_cleanup(struct drm_device *dev)
15998 {
15999         struct drm_i915_private *dev_priv = dev->dev_private;
16000         struct intel_connector *connector;
16001
16002         intel_disable_gt_powersave(dev);
16003
16004         intel_backlight_unregister(dev);
16005
16006         /*
16007          * Interrupts and polling as the first thing to avoid creating havoc.
16008          * Too much stuff here (turning of connectors, ...) would
16009          * experience fancy races otherwise.
16010          */
16011         intel_irq_uninstall(dev_priv);
16012
16013         /*
16014          * Due to the hpd irq storm handling the hotplug work can re-arm the
16015          * poll handlers. Hence disable polling after hpd handling is shut down.
16016          */
16017         drm_kms_helper_poll_fini(dev);
16018
16019         intel_unregister_dsm_handler();
16020
16021         intel_fbc_global_disable(dev_priv);
16022
16023         /* flush any delayed tasks or pending work */
16024         flush_scheduled_work();
16025
16026         /* destroy the backlight and sysfs files before encoders/connectors */
16027         for_each_intel_connector(dev, connector)
16028                 connector->unregister(connector);
16029
16030         drm_mode_config_cleanup(dev);
16031
16032         intel_cleanup_overlay(dev);
16033
16034         intel_cleanup_gt_powersave(dev);
16035
16036         intel_teardown_gmbus(dev);
16037 }
16038
16039 /*
16040  * Return which encoder is currently attached for connector.
16041  */
16042 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
16043 {
16044         return &intel_attached_encoder(connector)->base;
16045 }
16046
16047 void intel_connector_attach_encoder(struct intel_connector *connector,
16048                                     struct intel_encoder *encoder)
16049 {
16050         connector->encoder = encoder;
16051         drm_mode_connector_attach_encoder(&connector->base,
16052                                           &encoder->base);
16053 }
16054
16055 /*
16056  * set vga decode state - true == enable VGA decode
16057  */
16058 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16059 {
16060         struct drm_i915_private *dev_priv = dev->dev_private;
16061         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16062         u16 gmch_ctrl;
16063
16064         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16065                 DRM_ERROR("failed to read control word\n");
16066                 return -EIO;
16067         }
16068
16069         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16070                 return 0;
16071
16072         if (state)
16073                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16074         else
16075                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16076
16077         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16078                 DRM_ERROR("failed to write control word\n");
16079                 return -EIO;
16080         }
16081
16082         return 0;
16083 }
16084
16085 struct intel_display_error_state {
16086
16087         u32 power_well_driver;
16088
16089         int num_transcoders;
16090
16091         struct intel_cursor_error_state {
16092                 u32 control;
16093                 u32 position;
16094                 u32 base;
16095                 u32 size;
16096         } cursor[I915_MAX_PIPES];
16097
16098         struct intel_pipe_error_state {
16099                 bool power_domain_on;
16100                 u32 source;
16101                 u32 stat;
16102         } pipe[I915_MAX_PIPES];
16103
16104         struct intel_plane_error_state {
16105                 u32 control;
16106                 u32 stride;
16107                 u32 size;
16108                 u32 pos;
16109                 u32 addr;
16110                 u32 surface;
16111                 u32 tile_offset;
16112         } plane[I915_MAX_PIPES];
16113
16114         struct intel_transcoder_error_state {
16115                 bool power_domain_on;
16116                 enum transcoder cpu_transcoder;
16117
16118                 u32 conf;
16119
16120                 u32 htotal;
16121                 u32 hblank;
16122                 u32 hsync;
16123                 u32 vtotal;
16124                 u32 vblank;
16125                 u32 vsync;
16126         } transcoder[4];
16127 };
16128
16129 struct intel_display_error_state *
16130 intel_display_capture_error_state(struct drm_device *dev)
16131 {
16132         struct drm_i915_private *dev_priv = dev->dev_private;
16133         struct intel_display_error_state *error;
16134         int transcoders[] = {
16135                 TRANSCODER_A,
16136                 TRANSCODER_B,
16137                 TRANSCODER_C,
16138                 TRANSCODER_EDP,
16139         };
16140         int i;
16141
16142         if (INTEL_INFO(dev)->num_pipes == 0)
16143                 return NULL;
16144
16145         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16146         if (error == NULL)
16147                 return NULL;
16148
16149         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16150                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16151
16152         for_each_pipe(dev_priv, i) {
16153                 error->pipe[i].power_domain_on =
16154                         __intel_display_power_is_enabled(dev_priv,
16155                                                          POWER_DOMAIN_PIPE(i));
16156                 if (!error->pipe[i].power_domain_on)
16157                         continue;
16158
16159                 error->cursor[i].control = I915_READ(CURCNTR(i));
16160                 error->cursor[i].position = I915_READ(CURPOS(i));
16161                 error->cursor[i].base = I915_READ(CURBASE(i));
16162
16163                 error->plane[i].control = I915_READ(DSPCNTR(i));
16164                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16165                 if (INTEL_INFO(dev)->gen <= 3) {
16166                         error->plane[i].size = I915_READ(DSPSIZE(i));
16167                         error->plane[i].pos = I915_READ(DSPPOS(i));
16168                 }
16169                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16170                         error->plane[i].addr = I915_READ(DSPADDR(i));
16171                 if (INTEL_INFO(dev)->gen >= 4) {
16172                         error->plane[i].surface = I915_READ(DSPSURF(i));
16173                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16174                 }
16175
16176                 error->pipe[i].source = I915_READ(PIPESRC(i));
16177
16178                 if (HAS_GMCH_DISPLAY(dev))
16179                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16180         }
16181
16182         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
16183         if (HAS_DDI(dev_priv->dev))
16184                 error->num_transcoders++; /* Account for eDP. */
16185
16186         for (i = 0; i < error->num_transcoders; i++) {
16187                 enum transcoder cpu_transcoder = transcoders[i];
16188
16189                 error->transcoder[i].power_domain_on =
16190                         __intel_display_power_is_enabled(dev_priv,
16191                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16192                 if (!error->transcoder[i].power_domain_on)
16193                         continue;
16194
16195                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16196
16197                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16198                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16199                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16200                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16201                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16202                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16203                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16204         }
16205
16206         return error;
16207 }
16208
16209 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16210
16211 void
16212 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16213                                 struct drm_device *dev,
16214                                 struct intel_display_error_state *error)
16215 {
16216         struct drm_i915_private *dev_priv = dev->dev_private;
16217         int i;
16218
16219         if (!error)
16220                 return;
16221
16222         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16223         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16224                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16225                            error->power_well_driver);
16226         for_each_pipe(dev_priv, i) {
16227                 err_printf(m, "Pipe [%d]:\n", i);
16228                 err_printf(m, "  Power: %s\n",
16229                            onoff(error->pipe[i].power_domain_on));
16230                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16231                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16232
16233                 err_printf(m, "Plane [%d]:\n", i);
16234                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16235                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16236                 if (INTEL_INFO(dev)->gen <= 3) {
16237                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16238                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16239                 }
16240                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16241                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16242                 if (INTEL_INFO(dev)->gen >= 4) {
16243                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16244                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16245                 }
16246
16247                 err_printf(m, "Cursor [%d]:\n", i);
16248                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16249                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16250                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16251         }
16252
16253         for (i = 0; i < error->num_transcoders; i++) {
16254                 err_printf(m, "CPU transcoder: %s\n",
16255                            transcoder_name(error->transcoder[i].cpu_transcoder));
16256                 err_printf(m, "  Power: %s\n",
16257                            onoff(error->transcoder[i].power_domain_on));
16258                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16259                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16260                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16261                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16262                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16263                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16264                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16265         }
16266 }